这是我的代码:
function connect() {
$pdo = new PDO("mysql:host=localhost;dbname=www","user","pass");
$xmax = "SELECT MAX(x) FROM headerfooter WHERE site = 'Brighter_Vista'";
$xresult = $pdo->query($xmax);
while($row = $xresult->fetch(PDO::FETCH_ASSOC)) {
print_r($row);
}
$ymax = "SELECT MAX(y) FROM headerfooter WHERE site = 'Brighter_Vista'";
$yresult = $pdo->query($ymax);
while($row = $yresult->fetch(PDO::FETCH_ASSOC)) {
print_r($row);
}
}
我调用该函数并且没有显示任何内容。
我在mysql终端中检查了查询,它确实有效。
我是PDO的新手,我做错了什么?
答案 0 :(得分:1)
将您的查询包装在try catch块中。有可能悄然失败。
function connect() {
try{
$pdo = new PDO("mysql:host=localhost;dbname=www","user","pass");
$xmax = "SELECT MAX(x) FROM headerfooter WHERE site = 'Brighter_Vista'";
$xresult = $pdo->query($xmax);
while($row = $xresult->fetch(PDO::FETCH_ASSOC)) {
print_r($row);
}
$ymax = "SELECT MAX(y) FROM headerfooter WHERE site = 'Brighter_Vista'";
$yresult = $pdo->query($ymax);
while($row = $yresult->fetch(PDO::FETCH_ASSOC)) {
print_r($row);
}
}catch (Exception $e){
echo $e->getMessage();
exit;
}
}
如果抛出异常,则会显示消息,指出您的问题所在。
答案 1 :(得分:1)
该函数在语法上是正确的。一切似乎都很好,我能看到的唯一问题与PDO试图连接的问题有关。只需用以下功能替换您的功能:
function connect() {
try {
$pdo = new \PDO("mysql:host=localhost;dbname=www","user","pass");
$xmax = "SELECT MAX(x) FROM headerfooter WHERE site = 'Brighter_Vista'";
$xresult = $pdo->query($xmax);
while($row = $xresult->fetch(PDO::FETCH_ASSOC))
print_r($row);
$ymax = "SELECT MAX(y) FROM headerfooter WHERE site = 'Brighter_Vista'";
$yresult = $pdo->query($ymax);
while($row = $yresult->fetch(PDO::FETCH_ASSOC))
print_r($row);
} catch (\PDOException $e) {
exit($e->getMessage());
}
}
此功能在以下情况下显示或防止错误: