对不起伙计们,我是新来的,你能帮我解决一下我的疑问吗?
我的query()
功能出了什么问题? PDO有问题吗?
banco.php
<?php
class Banco {
private $pdo;
public function __construct($host,$dbname,$dbuser,$dbpass){
try {
$this->pdo = new PDO("mysql:dbname=".$dbname.";host=".$host."",$dbuser,$dbpass);
} catch (PDOException $e) {
echo "Conexao falhou".$e->getMessage();
}
}
public function query($sql) {
$this->pdo->query($sql);
}
}
?>
的index.php
<?php
require 'banco.php';
$banco = new Banco("127.0.0.1","test","root","");
$projeto = $banco->query("SELECT * FROM projetos") ;
$dado = $projeto->fetch();
print_r($dado);
?>
答案 0 :(得分:1)
像这样更改你的代码:(你忘了&#34;返回&#34;)
public function query($sql) {
return $this->pdo->query($sql);
}
答案 1 :(得分:0)
一些快速增强功能:
class Banco {
private $pdo;
public function __construct($host,$dbname,$dbuser,$dbpass){
try {
$this->pdo = new PDO("mysql:dbname=".$dbname.";host=".$host."",$dbuser,$dbpass);
} catch (PDOException $e) {
echo "Conexao falhou".$e->getMessage();
}
}
public function query($sql) {
return $this->pdo->query($sql);
}
}
$banco = new Banco("127.0.0.1","test","root","");
$projeto = $banco->query("SELECT * FROM projetos") ;
$dado = $projeto->fetch();
print_r($dado);
?>
如果PDO语句返回FALSE,则表示查询失败。即如果此行$banco->query("SELECT * FROM projetos");
不是正确的查询(可能有很多原因),它会给你
在非对象
上调用成员函数fetch()
如果您希望我们真正为您提供帮助,您应该上传数据库结构。