简体   繁体   中英

Replacing “?” in a string by values from array

I'm trying to replace every "?" in string by values from array. Each "?" is the next value from array.

I was wondering if there is a better way to do the following:

$query = 'SELECT * FROM pages WHERE id = ? AND language = ?';
$values = array('1', 'en');
foreach ($values as $value) {
    $query = preg_replace('/\?/', '\''.$value.'\'', $query, 1);
}
echo '<pre>'.print_r($query, true).'</pre>';

Would like to do that with native PHP (not a PDO extension).

Mysqli and PDO are as native as it gets with PHP.

You can use bind_param from mysqli to accomplish this. Example:

$stmt = $mysqli->prepare("SELECT * FROM pages WHERE id = ? AND language = ?");
$stmt->bind_param('is', 1, "en");

In this case the i and s are referencing the type of the parameter, as seen in this table (available in link):

i   corresponding variable has type integer
d   corresponding variable has type double
s   corresponding variable has type string
b   corresponding variable is a blob and will be sent in packets

Use binding

in PDO

$sth = $dbh->prepare('SELECT name, colour, calories
                      FROM fruit
                      WHERE calories < :calories AND colour = :colour');
$sth->bindValue(':calories', $calories, PDO::PARAM_INT);
$sth->bindValue(':colour', $colour, PDO::PARAM_STR);
$sth->execute();

http://php.net/manual/pl/pdostatement.bindvalue.php

in mysqli

$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);

http://www.php.net/manual/en/mysqli-stmt.bind-param.php

if you want to do it in STUPID way you can use loop or recursion

$select = "SELECT * FROM pages WHERE id = ? AND language = ?";
$params = array('param', 'param2');
while(preg_match('/\?/', $select)) $select = str_replace("?", array_shift($params),     $select);

but it's stupid

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM