0

here my code-

$things = mysql_real_escape_string(implode(',', $_POST['things']),$link);

$q = "INSERT INTO tblslider(src) VALUES ('".$things."')";
print_r($q);
$result = $mysqli->query($q) or die(mysqli_error($mysqli));

but my query is getting generated INSERT INTO tblslider(src) VALUES ('4368122.jpg,5440051.jpg,1047428.jpg') but it should be INSERT INTO tblslider(src) VALUES ('4368122.jpg'),('5440051.jpg'),('1047428.jpg') thats why it is taking it as one record not three.

3 Answers 3

5

You could do:

$things = array_map('mysql_real_escape_string', $_POST['things']);
$q = "INSERT INTO tblslider(src) VALUES ('". implode("'),('", $things)."')";

It generates (with my test data):

INSERT INTO tblslider(src) VALUES ('a.jpg'),('b.jpg'),('c.jpg')

I forgot: Only use functions like mysql_real_escape_string on the real data, not the SQL string. In your example you apply the function on the already concatenated data.

Sign up to request clarification or add additional context in comments.

Comments

0

You have imploded things which is now an array, so you need to iterate over this with a foreach loop such as...

foreach ($things as $item) {

  $q = "INSERT INTO tblslider(src) VALUES ('".$item."')";
  echo '<br />'.$q;
  $result = $mysqli->query($q) or die(mysqli_error($mysqli));

}

You could echo $q to make sure you're getting the queries right for each item also.

1 Comment

Oops, my mistake. How about using str_replace $things = str_replace (',' '),(', $things);
0

try this:

$formatVals = function($x){$rx = mysql_real_escape_string($x); return "('$rx')";};

$valString = implode(',', array_map($formatVals, $_POST['things']);

$sql = "INSERT INTO tblslider (src) VALUES $valString";

5 Comments

You need PHP 5.3 for that, don't you?
no not for array_map, for the anonymous function maybe you'd need create_function instead of what i did, but it can still be done php.net/manual/en/function.array-map.php us.php.net/manual/en/function.create-function.php php.net/manual/en/functions.anonymous.php
more importantly, i forgot the parens
Yeah I know that you don't need it for array_map. But your code will generate "INSERT INTO tblslider (src) VALUES 'mysql_real_escape_string(a.jpg)','mysql_real_escape_string(b.jpg)','mysql_real_escape_string(c.jpg)'" which is not correct. mysql_real_escape_string() has to be evaluated by PHP, not be contained in the string. It is not a MySQL function.
never thought it was mysql function, but i thoughy that it would parse just like "x = $x". that statement is in double quotes, the singles are just there

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.