如何从sql数据库表中获取列数据并将该数据放入PHP中的字符串中?

时间:2014-05-21 21:16:45

标签: php mysql sql database cakephp

我正在尝试很多,但对我来说没什么用。

我的查询是如何从sql数据库表中获取列数据并将该数据放入PHP中的字符串中?

请检查我在做什么。

我有“DriveRegisterTable”表,其中数据库表中有4列,第一个“id”第二个“用户名”第三个“txtMail”第四个“rxtMail”。

现在我想从数据库表中选择txtMail和rxtMail,其中username =“John”

现在在我的数据库表中“用户名”john有txtMail是“johnery99@gmail.com”而rxtMail是“sarah88@gmail.com”

现在我想在我的php字符串上获取这些东西。

现在我想从用户名=“John”的数据库表中选择txtMail和rxtMail,并在PHP字符串中输入johnery99@gmail.com和sarah88@gmail.com的txtMail和rxtMail值,然后发送邮件。

请检查我在做什么不适合我:

<?php


$db_host  = "localhost";
$username = "jacktask";
$db_pass  = "sormor4455";
$database = "myDatabaseDB";

mysql_connect("$db_host", "$username", "$db_pass");

@mysql_select_db($database) or die("Unable to find database4");

$txt_username          = $_REQUEST['txt_username']; // here user name is John


$query  = mysql_query("SELECT txt_email,rxt_email FROM DriveRegisterTable WHERE txt_username ='$txt_username'");


//$sql = "SELECT txt_email,rxt_email FROM DriveRegisterTable WHERE txt_username ='$txt_username' ORDER BY id ";
$res = mysql_query($query);


if($query){    // Dont know how to send mail or what to write in this condition block


$to      = $txt_Mail;      // want johnery99@gmail.com here only but not able to fetch this mail here
$subject = 'Hello Subject!';
$message = 'Hi';
$headers = 'From: $txt_email' . "\r\n" .
'Reply-To: txt_email' . "\r\n" .        // want sarah88@gmail.com here but txt_email does not give any value here means sarah88@gmail.com
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

}


mysql_close();

?>

我只想从John那里选择johnery99@gmail.com和sarah88@gmail.com并发送邮件。

非常欢迎任何想法或建议。

2 个答案:

答案 0 :(得分:2)

试试这个:

$txt_username = mysql_real_escape_string($txt_username);
$query = mysql_query("SELECT txt_email,rxt_email FROM DriveRegisterTable WHERE txt_username ='$txt_username'");

//use loop if you are expecting more than 1 rows, otherwise remove loop
// and just use $row = mysql_fetch_array($query);
while ($row = mysql_fetch_array($query)) {
     $email1 = $row['txt_email'];
     $email2 = $row['rxt_email'];

     //code to send email to those 2 emails
}

请注意,我添加了mysql_real_escape_string来转义变量。不要只是插入您的查询,它很容易被SQL Injection

我建议您查看 PDO MySQLi 预备语句。

答案 1 :(得分:0)

您将循环查询

你的$ res也是多余的,最好删除

if($query){    // Dont know how to send mail or what to write in this condition block

 while ($row = mysql_fetch_array($query)) {
   $txt_Mail = $row['txtMail'];
   $rxtMail = $row['rxtMail'];

   $to = $txt_Mail;  // want johnery99@gmail.com here only but not able to fetch  
   $subject = 'Hello Subject!';
   $message = 'Hi';
   $headers = 'From:'. $rxtMail .' . "\r\n" .
  'Reply-To: '. $rxtMail .' . "\r\n" .        // want sarah88@gmail.com here but txt_email  does not give any value here means sarah88@gmail.com
  'X-Mailer: PHP/' . phpversion();

   mail($to, $subject, $message, $headers);
}

}

下次,尝试使用mysqli(Mysql Improved)或PDO。不推荐使用mysql函数,将来不再支持它了