简体   繁体   中英

PHP mysql select with rand() rows

I have this little logic that i dont get how to solve it.

I have this on my database named email_list 5 records

then i have this trackCode 15 records on it.

my problem is im doing something like when i click the email all it will get the email to my email_list which has 5 records then the trackCode will send it to those emails.

i have this code

$sql = mysql_query( "SELECT * FROM code WHERE track = '$_POST['track']' " ) or die ( mysql_error() );
$row = mysql_fetch_array( $sql );
$subject = 'You have received your code';
$message = '
Your code is '.$row['trackCode'].'

Please click here to activate your code - click here -

management
';

$header = "From: noreply@fastindexer.com \r\n";
$header .= 'Content-type: text/html' . "\r\n";

$sqlemail = mysql_query( "SELECT * FROM email_list ORDER BY rand() LIMIT 15" ) or die ( mysql_error() );
while ( $rowemail = mysql_fetch_array( $sqlemail ) ) {
  $to = $rowemail['emails'];
}
$send_contact = mail($to,$subject,$message,$header);

Can you tell me what is wrong with my code is it my while statement?

What im trying to solve is that when it send email it send to those 5 emails with different trackCodes

i think im lost with my process and logic.

thanks guys

Try to change it to:

$sqlemail = mysql_query("SELECT * FROM email_list ORDER BY rand() LIMIT 15") or die ( mysql_error());

while($rowemail = mysql_fetch_assoc($sqlemail))
{
    mail($rowemail['emails'], $subject, $message, $header);
}

And this:

$sql = mysql_query("SELECT * FROM code WHERE track = '$_POST['track']'") or die (mysql_error());

should be:

$sql = mysql_query("SELECT * FROM code WHERE track = '".mysql_real_escape_string($_POST['track'])."'") or die (mysql_error());

Important:

However, it is important to point out that the the use of the mysql extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used.

looks like you are setting $to variable to email id in each iteration, but never using it, until after while loop. Which means only last email id from the results get mailed. try moving mail into the while loop.

while ( $rowemail = mysql_fetch_array( $sqlemail ) ) {
    $to = $rowemail['emails'];
    $send_contact = mail($to,$subject,$message,$header);
}

PS: Use better mysql extension ( PDO or Mysqli ), use better escaping, or prepared statements for data insertion. looks like your code is for learning purpose only, in that case, always learn whats better. in case its for production, it is very very vulnerable!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM