用数据库值替换字符串中的字符

时间:2018-05-14 13:26:45

标签: php mysql

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

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

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

$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,lastname和city动态替换所有用户并将消息存储到数组中。

如何识别$firstname$替换数据库归档firstname

3 个答案:

答案 0 :(得分:1)

另一种方法是让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;
}

答案 1 :(得分:0)

            $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();
$message = 'Dear $firstname$ $lastname$, your point of city is $city$';

        $toNumber['firstname'] = $db->query_result($result, $i, 'firstname');
$message=str_replace('$firstname$',$toNumber['firstname'],$message); ///something like that
        $toNumber['lastname'] = $db->query_result($result, $i, 'lastname');
  $toNumber['message'] = $message;

        $toNumbers[] = $toNumber;
    }

答案 2 :(得分:0)

只需创建一个名为$messages的新数组,并将每个数组存储在此数组中。

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

$messages = array();

$numOfrows = $db->num_rows($query);
for($i=0; $i<$numOfrows; $i++) {
    $firstname  = $db->query_result($result, $i, 'firstname');
    $lastname   = $db->query_result($result, $i, 'lastname');
    $city       = $db->query_result($result, $i, 'city');
    $messages[] = "Dear $firstname $lastname, your point of city is $city";
}