Question

original post:

My script is not working (it's not recording the data). It was working before I added the mysql_real_escape_string, so I'm wondering if maybe I have not implemented it correctly:

$array = json_decode($downstream,TRUE);
$name = $array["status"]["name"];
$title = $array["status"]["title"];
$table = "mrTable";
$insert = "INSERT INTO $table (name, title) VALUES ('".mysql_real_escape_string($name)."', '".mysql_real_escape_string($title)."')";

Does that implementation at INSERT look correct to you?

UPDATE:

Here is the entire code, hopefully this will help. It is still not working though. When the real_escape_string function is used, NONE of the data elements get recorded in the database. As soon as I remove the escape function, data is written fine (unless of course an apostrophe shows up).

Here we go:

//read contents of this file:

$json_data = file_get_contents('../list.txt');

//json to a php array

$array = json_decode($json_data,TRUE));

//store in mysql table

$table = "table1";
$name = mysql_real_escape_string($array["current"]["name"]);
$code = mysql_real_escape_string($array["current"]["code"]);

$insert="INSERT INTO $table (name, code) VALUES ('$name', '$code')";

$con = mysql_connect($db, $user, $pass);
if (!$con)
    {
    die ('Could not connect: ' . mysql_error());
    };

mysql_select_db($yup, $con);

mysql_query($insert) OR die(mysql_error());

mysql_close($con);

UPDATE 2

Fixed! You need to connect to the database before first mentioning mysql_real_escape_string. Everything is working now...no blank data.

Was it helpful?

Solution

You need to be connected to a database to use mysql_real_escape_string. You don't seem to be. Make sure mysql_connect is over your line where you define $insert

OTHER TIPS

Never insert values directly into a query string! Even if they are escaped, it's not a smart idea. Instead, use parametrised statements as such, which will render attacks like ' OR 1 = 1-- useless. You don't need to escape values for parametrised statements either...

PREPARE statement FROM
'INSERT INTO table (col1, col2)
 VALUES
 (?, ?)'

EXECUTE statement USING ('val1', 'val2')

DEALLOCATE statement

Deallocate only when you're done. You can re-execute as many times as you'd like with different values. If you are going to re-execute anyways, there is a gain in performance as well from doing it this way! (Because the statement is only prepared once for an infinite number of executions.) I advise you to implement this method and then come back if you are still having problems.

Please don't try to escape your parameters. Use bind variables. See http://bobby-tables.com/php.html for examples.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top