此代码的第18行出现语法错误,该行包含变量{$ user}。
我想从查询中提取3个变量,并将它们放入代码中的PHP变量中。
$user = 'xxxxx';
$password = 'xxxxx';
$db = 'xxxxx';
$host = 'xxxxx';
$conn = new PDO("mysql:host=$host; dbname=$db", $user, $password);
//$conn = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
//7 day users
$query = "SELECT user,email_address,DATEDIFF(NOW(),OrderDate) AS DateDiff
FROM MyTable WHERE DATEDIFF(NOW(),OrderDate) >= 6 AND enabled = 1 AND products_id IN (377) AND user = 'xxxxx'";
$stmt = $conn->query($query);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$to = "aa@ab.com";
$subject = "expiries - ";
$message = {$user};
$from = "aa@ab.com";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
}
预期结果应该是使用户从SQL查询中进入名为$ message的变量
答案 0 :(得分:1)
while
上的->fetch
循环是多余的。提取以数组格式返回单个数据行。因此,这里不需要while循环(因为循环的用途是循环数据)。
来自docs:
PDOStatement :: fetch —从结果集中获取下一行
FETCH_ASSOC:
PDO :: FETCH_ASSOC:返回一个由列名索引的数组,该数组在结果s中返回此函数成功返回的值取决于访存类型。在所有情况下,失败均返回FALSE。
因此它返回一个数组。只需使用:
try {
$data = $stmt->fetch(PDO::FETCH_ASSOC);
$column = $data['column'];
# your code
} catch (Exception $e) {
# err handling
}
根据评论进行编辑:
如果结果集有多行,如何遍历它们?
您可以使用->fetchAll()使用foreach
循环
PDOStatement :: fetchAll —返回一个包含所有结果集行的数组
# here we declare our SQL and pass in params for a prepared statement
$sql = 'SELECT * FROM table where `field` = :value;';
$res = $conn->prepare($sql);
$res->execute(array(':value' => $_POST['value'])); # exec the qry
# loop through the data and print_r $row
foreach ($res->fetchAll(PDO::FETCH_ASSOC) as $row)
{
echo '<pre>'. print_r($row, 1) .'</pre>';
}