str_replace中的while函数仅返回第一行信息。这是电子邮件模板。
// I have a macro in my message. (member name)
$message = "Hi {%write_member_name%} how are you?";
$connect = mysql_query("SELECT * FROM members");
while($row=mysql_fetch_array($connect)){
$membername = $row["member_name"];
$message = str_replace('{%write_member_name%}', $membername ,$message);
echo $message."<br/>";
}
我应该得到的结果。
嗨杰克你好吗?
你好 Mike 你好吗?
你好 Alex 你好吗?
但是我得到了错误的结果:
嗨杰克你好吗?
嗨杰克你好吗?
嗨杰克你好吗?
如果我不使用str_replace函数,它可以正常工作。
如何在while循环中使用str_replace函数? 谢谢。
答案 0 :(得分:1)
您使用sprintf()作为此
用作为参数传递的变量替换百分号(%):
$membername = "";
$connect = mysql_query("SELECT * FROM members");
while ($row = mysql_fetch_array($connect)) {
$membername = $row["member_name"];
$message = sprintf("Hi %s how are you?", $membername); // pass argument here
echo $message . "<br/>";
$membername = "";
}
在PHP 7.0.0中正式弃用并删除了mysql_ *函数。您 应该用PDO或MySQLi更新您的代码。
答案 1 :(得分:0)
$connect = mysql_query("SELECT * FROM members");
while($row=mysql_fetch_assoc($connect)){
$message = "Hi {%write_member_name%} how are you?";
$membername = $row["member_name"];
$message = str_replace('{%write_member_name%}', $membername ,$message);
echo $message."<br/>";
}
答案 2 :(得分:0)
更容易:
$connect = mysql_query("SELECT * FROM members");
while($icerik=mysql_fetch_array($connect)){
echo $message = "Hi" . $row["member_name"] . "how are you? <br/>";
}