PDO - 简单连接查询

时间:2017-02-06 19:02:08

标签: php pdo

我想重复使用连接的查询,但它似乎无法正常工作。

我有这个用于计算行数(工作):

$q = $db->prepare("SELECT id, image_date, image_link, image_name, image_category FROM image WHERE image_date < NOW() AND image_category= :category";
$q->bindValue(':category', $category, PDO::PARAM_STR);
$q->execute();
$row = $q->fetchColumn();

我想与之合作使用数据(不工作):

$q .= " ORDER BY id DESC LIMIT :limit");
$q->bindValue(':limit', 1, PDO::PARAM_INT);
$q->execute();

我也用那个表格测试但没有工作:

$q=$q. " ORDER BY id DESC LIMIT :limit");

2 个答案:

答案 0 :(得分:0)

您需要将第二部分附加到SQL字符串, 但不是Prepared Statement变量Found peer TypeScript 2.0.10 12:31:01 AM - Compilation complete. Watching for file changes. Error: watch /var/www/html/train-locator/node_modules/adm-zip/headers ENOSPC at exports._errnoException (util.js:1036:11) at FSWatcher.start (fs.js:1429:19) at Object.fs.watch (fs.js:1456:11) at createFsWatchInstance (/usr/local/lib/node_modules/nativescript/node_modules/chokidar/lib/nodefs-handler.js:37:15) at setFsWatchListener (/usr/local/lib/node_modules/nativescript/node_modules/chokidar/lib/nodefs-handler.js:80:15) at FSWatcher.NodeFsHandler._watchWithNodeFs (/usr/local/lib/node_modules/nativescript/node_modules/chokidar/lib/nodefs-handler.js:228:14) at FSWatcher.NodeFsHandler._handleDir (/usr/local/lib/node_modules/nativescript/node_modules/chokidar/lib/nodefs-handler.js:407:19) at FSWatcher.<anonymous> (/usr/local/lib/node_modules/nativescript/node_modules/chokidar/lib/nodefs-handler.js:455:19) at FSWatcher.<anonymous> (/usr/local/lib/node_modules/nativescript/node_modules/chokidar/lib/nodefs-handler.js:460:16) at FSReqWrap.oncomplete (fs.js:123:15)

$q

答案 1 :(得分:0)

PDO的问题在于你必须先准备一个查询才能绑定任何东西,一旦准备好,查询显然不能再扩展了。

此外,您的第一个查询除了计数之外什么都不做。所以越简单越好 - 只运行两个单独的查询而不连接

$q = $db->prepare("SELECT count(*) FROM image WHERE image_date < NOW() AND image_category= ?";
$q->execute([$category]);
$count = $q->fetchColumn();

然后

$q = $db->prepare("SELECT id, image_date, image_link, image_name, image_category 
 FROM image WHERE image_date < NOW() AND image_category= ? ORDER BY id DESC LIMIT ?";
$q->execute([$category, $limit]);
$rows = $q->fetchall();