lets say I have the following query in a variable:
$sql = "select id, salary, fname, lname from users where id = ? and salary > ?";
and an array like this:
$params = array (
0 => '38765',
1 => '4000');
I was wondering if there is a simple of built in PHP to do this to replace the "?" in the query to get the following result:
"select id, salary, fname, lname from users where id = '38765' and salary > '4000' ";
the query won't be executed by the way, this more of a sting manipulation question than a sql one.
this is as close as I got but it looks like PHP might have something built it for it:
foreach ($params as $param){
$pos = strpos($sql, '?');
$sql = substr_replace($sql, "'".$param."'", $pos, 1);
}
Yes, there is.
See this code example from php.net
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name = ?");
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
http://php.net/manual/en/pdo.prepared-statements.php#example-1016
But this variant requires that you work with PDO
.
See this link for more details: http://php.net/manual/en/book.pdo.php