0

Below is the code being used to generate the code to be executed inside the mysql_query function

for($i=1;$i<=$totalcols;$i++) {
    $val_array[] = "\'\".\$data->val(\$i,$i).\"\'";

}

the array above is then converted into string without slashes using implode and stripslashes function.

$val = stripslashes(implode(",",$val_array));

And all of it produces a string as follows

'".$data->val($i,1)."','".$data->val($i,2)."','".$data->val($i,3)."'

This is the string that I am using inside the VALUES() . Instead of executing the code and then inserting the values in database, the string is being inserted into the database as it is.The mysql_query function is being used as follows.

mysql_query("INSERT INTO import_excel ($val_string) VALUES($val)") or die(mysql_error());

Here is screenshot if data inserted into DB enter image description here

10
  • Have it echo the final query to be executed. Also, what's the error...? Commented Oct 15, 2012 at 6:41
  • There is no error. Its just giving unpredictable result. Commented Oct 15, 2012 at 6:45
  • If you already have an array, use mysqli and bind parameters. What you are doing is dangerous. If you're using php 5.3+, you already have it installed and pre configured, so there would simply be no excuse not to use it. Commented Oct 15, 2012 at 6:52
  • @Harbhag care to tell us what the unexpected result is...? We can't help you fix a problem we know nothing about. Commented Oct 15, 2012 at 6:55
  • He is basically trying to eval() the code inside the string before passing it to mysql_query. The dollar signs in $val are being taken as literals. Commented Oct 15, 2012 at 6:57

1 Answer 1

1

What you want to do is usually done this way:

$val_array[] = "'{$data->val($i)}'";

i.e. the variable value is inserted into the string when building it, not when executing it.

This is because clean PHP code doesn't usually use the "eval" function, although there are ways to abuse PHP to do it.

Also, you usually need to apply the function to escape quotes in the value, to be safe from SQL injection:

$val_array[] = "'".mysql_real_escape_string($data->val($i))."'";
Sign up to request clarification or add additional context in comments.

2 Comments

php does actually have an eval function, it is just highly discouraged for anyone to use it.
Thanks, I edited my comment after checking the php website for "eval".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.