首页 > 解决方案 > 用数据库值替换字符串中的字符

问题描述

我有字符串消息$message = 'Dear $firstname$ $lastname$, your point of city is $city$'

我想从 Mysql 数据表中获取值$firstname$, $lastname$$city$替换为消息。

我从数据库中选择了多个用户数据,并将新消息存储到数组中。

$query = $ab->pquery("select firstname, lastname, city from tblaccount where country = $country";

$numOfrows = $db->num_rows($query);
for($i=0; $i<$numOfrows; $i++) {
    $toNumber = array();
    $toNumber['firstname'] = $db->query_result($result, $i, 'firstname');
    $toNumber['lastname'] = $db->query_result($result, $i, 'lastname');
    $toNumbers[] = $toNumber;
}

我希望为所有用户动态替换名字、姓氏和城市,并将消息存储到数组中。

如何识别$firstname$替换为数据库归档的结果firstname

标签: phpmysql

解决方案


另一种方法是让 MySQL 完成连接工作,这将减少 PHP 指令。

$messageSQL = "CONCAT('Dear ', firstname, ' ', lastname, ', your point of city is ', city)";

$query = $ab->pquery("select $messageSQL AS themessage from tblaccount where country = $country";

$numOfrows = $db->num_rows($query);
for($i=0; $i<$numOfrows; $i++) {
    $message =  $db->query_result($result, $i, 'themessage');
    $toNumbers[] = $message;
}

推荐阅读