我正在尝试在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;
}}
我在这里缺少什么?
答案 0 :(得分:0)
添加执行结果检查并查看错误:
if($stmt->execute()){
...
}else{
echo "Unable to read record:". print_r($stmt->errorInfo(), true);
}
答案 1 :(得分:0)
的问题是与取指被使用两次。
可以通过以下方式完成:
y
这应该很好。