过去三天来,我一直在努力解决这个问题。看来无论我做什么,如果我在传递参数的同时尝试执行一条准备好的PDO语句,它将始终返回false。
function login($email,$password)
$outcome;
$conn;
$servername = ...
$username = ...
$password = ...
$database = ...
try {
$conn = new PDO(...);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute( PDO::ATTR_EMULATE_PREPARES, FALSE );
} catch(PDOException $e) {
$outcome = "Connection failed: " . $e->getMessage();
return $outcome;
die();
}
$sql = "SELECT * FROM `users` WHERE user_email = ?";
$stmt = $conn->prepare($sql);
$stmt->execute(array($email));
$user = $stmt->fetch(PDO::FETCH_ASSOC);
echo (json_encode($user));
...
我尝试使用bindValue()和bindParam()显式将$ email变量绑定到占位符,无论哪种方式,$ user变量总是评估为false。它应该以关联数组的形式返回查询结果的第一行。
答案 0 :(得分:0)
$sql = "SELECT * FROM `users` WHERE user_email = :user_email";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':user_email', $email);
$stmt->execute();
答案 1 :(得分:0)
尝试一下,看看它能为您带来什么。一旦看到错误所在,就可以从那里去
<?php
function login($email,$password)
{
$servername = 'localhost';
$username = 'DB_USERNAME';
$password = 'DB_PASSWORD';
$database = 'DB_NAME';
$charset = 'utf8mb4';
$dsn = "mysql:host=$servername;dbname=$database;charset=$charset";
try
{
$opt = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ];
$conn = new PDO($dsn, $username, $password, $opt);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$stmt = $conn->prepare('SELECT * FROM users WHERE user_email = :user_email');
$stmt->bindParam(':user_email', $email);
if ($stmt->execute())
{
if ($user = $stmt->fetch())
{
echo (json_encode($user));
} else {
echo "Error, failed fetching data";
}
} else {
echo "Error, failed executing query";
}
}