我正在尝试连续执行两个单独的PDO
个查询。但是,一次只能正确执行一个。无论哪一个是第一个正确查询数据库并返回任何值的唯一一个。我已经尝试使用var_dump来查看它们返回的内容,第二个PDO查询返回“boolean false”并且不包含任何信息。
这是我的代码:
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
// make and execute query for client information
$client_query = $db->prepare('SELECT * FROM clients WHERE id=:ID');
$client_query->execute(array('ID' => $client_id));
$client_result = $client_query->fetch(PDO::FETCH_ASSOC);
// set client information for captcha
$this->client_name = $client_result['name'];
$this->client_id = $client_result['id'];
$client_query->closeCursor();
// make and execute query for campaign information
$campaign_query = $db->prepare('SELECT * FROM campaigns WHERE id=:ID AND client_id=:CLIENT');
$campaign_query->execute(array('ID' => $campaign_id, 'CLIENT' => $client_id));
$campaign_result = $campaign_query->fetch(PDO::FETCH_OBJ);
// set campaign information for captcha
$this->campaign = $campaign_result;
如果我从第二个查询中删除参数,它们都会成功执行。我在这做错了什么?谢谢!
答案 0 :(得分:3)
您的SQL无效;改变这个:
SELECT * FROM campaigns WHERE id=:ID AND WHERE client_id=:CLIENT
到此:
SELECT * FROM campaigns WHERE id=:ID AND client_id=:CLIENT
答案 1 :(得分:2)
正如Errors and error handling章节所解释的那样:
PDO为您提供3种不同的错误处理策略选择
...默认为PDO::ERRMODE_SILENT
,这意味着:禁止所有错误消息,并希望开发人员不要忘记检查是否有错误。
总结一下:你需要做错误检查。
答案 2 :(得分:1)
乍一看......我会将你的代码更改为:(在数组中也使用冒号,并且在第二个sql语句中有重复的关键字“where”的副本)。我会例外而不是警告 - 然后在必要时捕获异常。
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// make and execute query for client information
$client_query = $db->prepare('SELECT * FROM clients WHERE id=:ID');
$client_query->execute(array(':ID' => $client_id));
$client_result = $client_query->fetch(PDO::FETCH_ASSOC);
// set client information for captcha
$this->client_name = $client_result['name'];
$this->client_id = $client_result['id'];
$client_query->closeCursor();
// make and execute query for campaign information
$campaign_query = $db->prepare('SELECT * FROM campaigns WHERE id=:ID AND client_id=:CLIENT');
$campaign_query->execute(array(':ID' => $campaign_id, ':CLIENT' => $client_id));
$campaign_result = $campaign_query->fetch(PDO::FETCH_OBJ);
// set campaign information for captcha
$this->campaign = $campaign_result;
在尝试检索值时你可以这样做,但是考虑使用JOINS而不是这样:
SELECT * FROM clients cls
LEFT JOIN campaigns cas ON (cls.id = cas.client_id)
WHERE cas.id=:ID
答案 3 :(得分:0)
令人尴尬的是,所有代码都是正确的(除了你们有些人抓到的一个小的SQL语法错误)。我的问题是$campaign_id
的值大于mySQL表中存储的任何值,因此查询实际上没有返回任何结果。所以实际上查询没有问题,第二个没有返回结果。我很感激所有的答案并为这种悲伤的疏忽道歉!