2

The while function in str_replace only returns the first line of information. This is email template.

// 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/>";

}

The result I should have.

Hi Jack how are you?

Hi Mike how are you?

Hi Alex how are you?

But I get the wrong result:

Hi Jack how are you?

Hi Jack how are you?

Hi Jack how are you?


If I do not use the str_replace function it works correctly.

How do I use the str_replace function in while loop? Thank you.

4
  • mysql_query is deprecated. Use mysqli or even better, PDO. Commented Apr 14, 2017 at 5:50
  • 2
    It will take a lot of time to fix all the software. But thank you for your suggestion. Commented Apr 14, 2017 at 5:53
  • @MertA. Have you tried to print the $row["member_name"]? Is it also printing the same value all the time? Commented Apr 14, 2017 at 6:00
  • @Difster If I do not use the str_replace function it works correctly. Commented Apr 14, 2017 at 6:05

3 Answers 3

2
    $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/>";

    }
Sign up to request clarification or add additional context in comments.

4 Comments

Sorry this is not the problem. There was a mistake when you were rewriting the codes here.
@Mert A. check it now
use @Stefan Avramovic solution
@Mert A. check my answer
1

You use sprintf() for this

Replace the percent (%) sign by a variable passed as an argument:

$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 = "";
}

mysql_* functions officially deprecated and removed in PHP 7.0.0. You should update your code with PDO or MySQLi.

Comments

0

Much easier:

$connect = mysql_query("SELECT * FROM members"); 
while($icerik=mysql_fetch_array($connect)){

echo $message =  "Hi" . $row["member_name"] . "how are you? <br/>";


}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.