PHP中PDO语句的新手。我在使用oops概念编写查询来实现pdo时遇到了麻烦。我希望实现的目标是可重复使用的选择功能。
public function selectpackage($table) {
try {
$query = $this->db->prepare("select * from $this->table");
return $query->fetch(PDO::FETCH_ASSOC);
}
catch(PDOException $e)
{
echo 'Query failed'.$e->getMessage();
}
}
$db
用于连接数据库。现在,在我调用此函数的页面中,我写了
$result = $obj->selectpackage("tbl_packages");
while($row = $result) {
echo $row['title']."</br>";
}
它没有给出结果。有谁知道问题出在哪里?
答案 0 :(得分:0)
我检查了Siraj代码,其工作
class oopCrud
{
private $host="localhost";
private $user="root";
private $db="databasename";
private $pass="";
private $conn;
public function __construct(){
$this->conn = new PDO("mysql:host=".$this->host.";dbname=".$this->db,$this->user,$this->pass);
}
public function showData($table){
try {
$sql="SELECT * FROM $table";
$q = $this->conn->query($sql) or die("failed!");
while($r = $q->fetch(PDO::FETCH_ASSOC)){ $data[]=$r; }
return $data;
}
catch(PDOException $e)
{
echo 'Query failed'.$e->getMessage();
}
}
}
$obj=new oopCrud;
$result = $obj->showData("tablename");
print_r($result);