我正在尝试在 PDO 中查询我的数据库并将输出显示在表单上。但是 fetch 语句不起作用。代码是
try {
include '../../config/database.php';
$database = new Database();
$db = $database->getConnection();
//prepare query
$query = "select
payment_id, payment_supplier, payment_ref, payment_cost_rating, payment_amount
from
payments
where
payment_id = ?
limit 0,1";
$stmt = $db->prepare( $query );
//this is the first question mark
$stmt->bindParam(1, $_REQUEST['myData']);
//execute our query
if($stmt->execute()){
var_dump($stmt->fetch());
//store retrieved row to a variable
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//values to fill up our form
$payment_id = $row['payment_id'];
$payment_supplier = $row['payment_supplier'];
$payment_ref = $row['payment_ref'];
$payment_cost_rating = $row['payment_cost_rating'];
$payment_amount = $row['payment_amount'];
}else{
echo "Unable to read record.";
}
var_dump ($stmt); prints
object(PDOStatement)#3 (1) { ["queryString"]=> string(157) "select payment_id, payment_supplier, payment_ref, payment_cost_rating, payment_amount from payments where payment_id = ? limit 0,1"}
但是 fetch()
总是返回 false。如果有帮助,这是包含的 database.php 文件
class Database{
// database credentials
private $host = "localhost";
private $db_name = "test-project";
private $username = "root";
private $password = "";
public $conn;
// get the database connection
public function getConnection(){
$this->conn = null;
try{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}}
我在这里错过了什么?
最佳答案
问题在于提取被使用了两次。
可以这样做:
if($stmt->execute()){
//store retrieved row to a variable
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// display the row after fetching the contents.
var_dump($row);
//values to fill up our form
$payment_id = $row['payment_id'];
$payment_supplier = $row['payment_supplier'];
$payment_ref = $row['payment_ref'];
$payment_cost_rating = $row['payment_cost_rating'];
$payment_amount = $row['payment_amount'];
}else{
echo "Unable to read record.";
}
这应该可以正常工作。
关于php - 使用 PDO fetch 查询 Mysql 返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26358141/