将参数绑定到pdo函数

时间:2012-10-29 08:41:31

标签: php mysql pdo

我正在尝试编写以下函数来显示MySQL表的内容。

$q=$_GET["q"];
function risk_allocation($db)  
  {    
    $result = $db->query("select r.risks as risks,r.risktype as risktype,j.job as job from risks r LEFT OUTER JOIN `jobsrisks` j on r.risks = j.risk and j.job=:q"); 
    $result ->bindParam(':q', $q, PDO::PARAM_INT);
    return $result; 
  }
        $allocationlist = risk_allocation($db); 

然后我用以下方式调用结尾:

while($row = $allocationlist->fetch(PDO::FETCH_ASSOC)) 
{
echo $line['risks'];
echo $line['risktype'];
}

我收到错误消息:

Fatal error: Call to a member function bindParam() on a non-object in /home/she/public_html/versionfour/getrisksperjob.php on line 11

第11行是

$result ->bindParam(':q', $q, PDO::PARAM_INT);

我觉得这是一个简单的问题,因为我刚刚被介绍给pdo,但任何帮助都会一如既往地受到赞赏。

更新

根据提出的答案,我的代码现在如下执行查询并包含变量q。但是仍然会发生同样的错误到目前为止,感谢您的帮助,任何想法?

致命错误:在第11行的/home/she/public_html/versionfour/getrisksperjob.php中的非对象上调用成员函数bindParam()

function risk_allocation($db,$q)  
  {    
    $result = $db->query("select r.risks as risks,r.risktype as risktype,j.job as job from risks r LEFT OUTER JOIN `jobsrisks` j on r.risks = j.risk and j.job=:q"); 
    $result ->bindParam(':q', $q, PDO::PARAM_INT);
    $result->execute();
    return $result; 
  }
  $allocationlist = risk_allocation($db,$q); 

2 个答案:

答案 0 :(得分:3)

您忘记了execute查询,您还需要准备而不是调用查询:

$result = $db->prepare("select r.risks as risks,r.risktype as risktype,j.job as job from risks r LEFT OUTER JOIN `jobsrisks` j on r.risks = j.risk and j.job=:q"); 
$result->bindParam(':q', $q, PDO::PARAM_INT);
$result->execute();

答案 1 :(得分:2)

1.您forgot to execute query

$result->execute();

2. $q outside function so you will never get value of that inside function.传递$ q作为函数的第二个参数

$q=$_GET["q"];
function risk_allocation($db,$q)  
  {    
    $result = $db->prepare("select r.risks as risks,r.risktype as risktype,j.job as job from risks r LEFT OUTER JOIN `jobsrisks` j on r.risks = j.risk and j.job=:q"); 
    $result ->bindParam(':q', $q, PDO::PARAM_INT);
    $result->execute();
    return $result; 
  }
  $allocationlist = risk_allocation($db,$q);