php - where to use mysql_real_escape_string on JSON data in GET request -
i using json data request selecting & inserting mysql. if had used mysql_real_escape_string json, please let me know
$json_data = mysql_real_escape_string($_get['json_data']); json_decode($json_data, true); mysql_queries
this way ok
or else have on every variable like
$json_data = mysql_real_escape_string($_get['json_data']); $string = json_decode($json_data, true); $variable1 = mysql_real_escape_string($string['variable1']); $variable2 = mysql_real_escape_string($string['variable2']); $variablen = mysql_real_escape_string($string['variablen']); mysql_queries
where use mysql_real_escape_string on json data in request
you put 3 different domains in single sentence, each of them having different syntax , different escape rules. don't mix them!
// $text text received in query string // might correct json representation of data structure // may else well; source injection // nonetheless, have thoroughly checked $text = $_get['json_data']; // check if $text looks valid json representation $data = json_decode($text, true); // expect array encoded json in $_get['json_data'] if (! is_array($data)) { // not good; recover situation somehow; // display error message or use default value instead or // abort script or combination of above exit(1); } // validate structure of $data , values contains if (! isset($data['variable1'])) { // something: use default value, display message etc. } // 'variable1' set, can work $var1 = $data['variable1']; // validate type , value of $var1 // f.e. if expect integer check if it's integer and/or // convert integer if (! is_int($var1)) { // something, example fix $var1 = (int)$var1; } // validate value; if it's quantity, f.e., must positive // (zero may or may not allowed, depends on application logic) if ($var1 <= 0) { // wrong here; // report error, fix value, abort processing, depends... } // $var1 looks legit now; use or put database // test joke let's realistic. it's 2015 , // old mysql php extension dead. don't use it! // use mysqli or pdo_mysql instead if (date('y') <= 2005) { $var1db = mysql_real_escape_string($var1); $query = "insert tbl1(col1) values ('$var1db')"; } else { // ma! no need "escape string" more! $query = "insert tbl1(col1) values (?)" $stmt = mysqli_prepare($conn, $query); mysqli_stmt_bind_param($stmt, 'i', $var1); mysqli_stmt_execute($stmt); }
stop using mysql
php extension!
it old, has limited functionality, not maintained more and, more important, deprecated on php 5.5 , removed altogether php 7.
use either mysqli
or pdo_mysql
. while pdo
seems more versatile me, easier switch mysql
mysqli
(using procedural interface of mysqli
). there articles on web explain how switch.
don't stick past, dare progress!
Comments
Post a Comment