Manuel Fernández
Manuel Fernández

Reputation: 483

MySQLi query to MySQL query

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.

Upvotes: 1

Views: 185

Answers (2)

uınbɐɥs
uınbɐɥs

Reputation: 7341

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.

Upvotes: 0

Lusitanian
Lusitanian

Reputation: 11122

<?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.

Upvotes: 1

Related Questions