Web Hosting Talk







View Full Version : Question abut str_replace & text box


Rob83
06-23-2005, 04:34 PM
Could I use str_replace to replace a string in a text box with a variable from a text box to be emailed through php?

Something like:




$message = $_POST['message'];

$sql = mysql_query("SELECT FirstName FROM users");

while($row = mysql_fetch_object($sql))
{
// Send the emails in this loop.
$member_name = $row->FirstName;

$body = str_replace('{MEMBER_NAME}', $member_name, $message);




Then in the textbox we'd use {MEMBER_NAME} To define the member name?

then something like

mail(" <$email>", "$subject", "$body", "From: $sitename<$fromemail>", "-fi$fromemail");

WLHosting
06-24-2005, 07:34 PM
Yes, you can use use str_replace() to perform that action. You can also go more "advance" and make your code something like this:

$replace = array('{member_name}','{member_email}','{member_password}');
$replace_with = array($row[Firstname],$row[email],$row[password])
$body = str_replace($replace, $replace_with, $message);

Hope this helps

maxymizer
06-24-2005, 07:50 PM
Note to the people reading this - using unquoted indexes within array will make php to issue a notice (unless they are previously defined with define()).

Semantically correct would be:
$replace_with = array($row['Firstname'],$row['email'],$row['password']);

kuja
06-24-2005, 09:35 PM
Syntactically, you mean.

maxymizer
06-25-2005, 05:10 AM
Regarding the syntax, there would be no syntax errors in the unqoted example. The error would occur because of undefined constants. So sintactically, using unqoted associative indexes is also correct.

Rob83
06-25-2005, 01:15 PM
Thanks. I got it working with this:

$sql = mysql_query("SELECT fname,lname,email FROM mailing");

while($r = mysql_fetch_array($sql)){
$fname = $r['fname'];
$lname = $r['lname'];
$email = $r['email'];

$body=stripslashes($message);
$body = str_replace('%FNAME%', $fname, $body);
$body = str_replace('%LNAME%', $lname, $body);
$body = str_replace('%EMAIL%', $email, $body);


FWIW, it works!