使用PDO尝试从mysql数据库中检索数据时发生错误

问题描述:

我想从使用PDO的mysql数据库中检索数据,但出现错误。使用PDO尝试从mysql数据库中检索数据时发生错误

下面是代码

<form id="form" action="sum1.php" method="post"> 
<td><p align="center"> IDNO : <input type="text" name="id" id="id" maxlength="10"</p></td> 
<input type="submit" id="submit" class='btnExample' value="Click here to get your Result"> 
    </form> 
    <?PHP 
    $dbhost  = "localhost"; 
    $dbname  = "demo"; 
    $dbuser  = "admin"; 
    $dbpass  = "123456"; 
    $db = new PDO("mysql:host=$dbhost;dbname=$dbname", "$dbuser", "$dbpass"); 
    $id = $_POST['id']; 
    $add = $db->prepare("SELECT SUM(tech) AS tech4 FROM (
    (SELECT SUM(tm) AS tech FROM jbit WHERE htno > :id) 
    UNION ALL 
    (SELECT SUM(tm) AS tech FROM hmm WHERE htno > :id))t1"); 
    $add -> execute(array('id'=>$id)); 
    $result3 = $db->query($add); 
    echo " <center><table id='mytable' cellspacing='0' border=3 align=center> 
    <tr><TH scope='col'>Total Marks</TH> </tr><center>"; 
    while ($row1 = $result3->fetch(PDO::FETCH_ASSOC)) 
    { 
    echo "<tr>"; 
    echo "<td align=center>" . $row1['tech4']. "</td>"; 
    echo "</tr>"; 
    } 
    $result3->closeCursor(); 
    $db = null; 
    ?> 

错误我得到

Warning: PDO::query() expects parameter 1 to be string, object given in /home/nhtsoft/public_html/engineershub/sum1.php on line 17 

Fatal error: Call to a member function fetch() on a non-object in /home/nhtsoft/public_html/engineershub/sum1.php on line 20 

第17行是

$result3 = $db->query($add); 

第20行是

while ($row1 = $result3->fetch(PDO::FETCH_ASSOC)) 

任何想法?

首先解决这个问题

$add -> execute(array('id'=>$id)); 
    //and remove 
$result3 = $db->query($add); 

并使用

$add -> execute(array(':id'=>$id)); 
    while($result=$add->fetch(PDO::FETCH_ASSOC)) 
+0

呀做,现在有没有错误,但仍然输出是空的 – Aryan

+0

@Aryan可能是由于您的查询空结果。尝试在phpmyadmin中运行此查询? – StaticVariable

+0

得到了输出..谢谢你很多,但显示不正确的输出,而使用Mysql查询我得到确切的输出,但通过使用PDO我得到错误的输出。请你检查一次查询 – Aryan

这是如何使用准备好的语句:

$add = $db->prepare(...); 
$add->execute(array('id' = >$id)); 
while ($row = $add->fetch(PDO::FETCH_ASSOC)) ... 

​​已经执行查询。 PDO::query()用于直接引发未准备好的查询。这里你不需要它。

+0

呀做,现在现在有错误,但仍然输出是空白 – Aryan