1

I am trying do multi-driver support for my Framework, which basically means I can use MySQL, MySQLi or PDO(MySQL) with ease.

So, let's say I have an array of values I want to insert.

array('Manuel', 'StackOverflow');

and I have this query..

mysql_query("INSERT INTO users(name, fav_site) VALUES(?, ?)");

So, I'd like to replace the question marks with those values in order, so Manuel goes first and then goes StackOverflow. Remembering that I need to add -> ' <- at the sides of these values so MySQL doesn't throw an error.

I have tried searching if someone has asked this and had no luck.

Any help is appreciated!

NOTE: I know I shouldn't even bother with MySQL, but hey! A feature is a feature.

2
  • 2
    The reason you shouldn't bother with mysql is, as you've seen, it makes the developer's attempts to do the right thing more difficult. Commented Jul 20, 2012 at 0:30
  • Mhm.. I agree with you, if I don't find how to do this I will just delete the feature :) Commented Jul 20, 2012 at 0:32

2 Answers 2

1
<?php
$query = "INSERT INTO users(name, fav_site) VALUES(?, ?)";
$args = array('joe', 'google goggles');
while(strpos($query, '?') !== FALSE)
{
  $query = preg_replace('/\?/', your_quoting_func(array_shift($args)), $query, 1);
}
echo $query;

Basically, this says...while there is still a ? remaining in the string, delete the first question mark and replace it with a quoted (use your own function or mysql_real_escape_string and surround with single quotes) string, and shift that item off the array. You should probably substr_count the ? marks versus the number of arguments for error checking.

I used preg_replace because it accepts an argument specifying how many values to replace, whereas str_replace does not.

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

Comments

0

I would do it this way (with one exeption: I wouldn't use mysql_):

<?php
$values = array('foo', 'bar');

$query_start = "INSERT INTO `users` (`name`, `fav_site`) VALUES ('";
$query_end = "')";

$query = $query_start . implode("', '", $values) . $query_end;

$result = mysql_query($query);
?>

$query_start contains the start of the MySQL query (notice the ' at the end), and $query_end goes at the end.

Then $values is imploded, with ', ' as the 'glue', and $result is set as:

$query_start (impoded $result) $query_end.

See implode - PHP Manual.

Comments

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.