嗨,我很难弄清楚为什么我的简单select语句为$ result和$ row变量返回布尔值0。
我有一个数据库类:
<?php
class Database {
private static $dsn='mysql:host=localhost;dbase=my_guitar_shop1';
private static $username='mgs_user';
private static $password='pa55word';
private static $db;
private function __construct(){}
public static function getDB(){
if(!isset(self::$db)){
try {
self::$db=new PDO ( self::$dsn, self::$username , self::$password);
} catch (Exception $ex) {
$error_message=$e->getMessage();
include('../errors/database_error.php');
exit();
}
}
return self::$db;
}
}
我有一个CategoryDB类:
<?php
class CategoryDB {
public static function getCategories(){
$db= Database::getDB();
// Insert to Test
$query= "INSERT INTO categories
(categoryID, categoryName)
VALUES ( 6,'test')";
$statement= $db->prepare($query);
$statement->execute();
$query="SELECT * FROM categories";
$statement=$db->prepare($query);
$statement->execute();
$row=$statement->fetch();
$query= "SELECT * from categories";
$statement= $db->prepare($query);
$statement->execute();
var_dump($statement);
$result=$statement->fetchAll();
var_dump($result);
$statement->closeCursor();
$categories=array();
foreach($result as $row){
$category=new Category($row['categoryID'],$row['categoryName']);
$categories[]=$category;
}
return $categories;
}
public static function getCategory($category_id){
$db=Database::getDB();
$query="SELECT * from category
WHERE categoryID=:category_id";
$statement= $db->prepare($query);
$statement->bindValue(':category_id', "$category_id");
$statement->execute();
var_dump($statement);
$row=$statement->fetch();
var_dump($row);
$statement->closeCursor();
$category=new Category($row['categoryID'],$row['categoryName']);
return $category;
}
}
对数据库的查询不起作用。我跟踪了代码,发现getCategories()和getCategory()函数的$ result和$ row变量分别是布尔值0。 $ db是一个PDO对象。有人可以帮我为什么查询不起作用吗? 在两个变量的var dump中,我得到了:
object(PDO)[1]
array (size=0)
empty
boolean false
在两个函数中的两个var_dump
的{{1}}中,我得到:
$statement