php pdo 结果,php – 迭代PDO查询的结果

我想基于URL参数中的数据使用PDO运行查询(是的,我知道这很容易受到攻击,但是它的实用程序的内部代码).

$user = 'USER';

$pass = 'PASSWORD';

$dsn = 'mysql:dbname=PRODUCTS;host=HOST';

try {

$productDB = new PDO($dsn, $user, $pass);

$productDB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

}

catch(PDOException $e) {

$msg = 'PDO ERROR' . $e->getFile() . ' L.' . $e->getLine() . ' : ' . $e->getMessage();

die($msg);

}

if(isset($_GET['cat']))

{

$cat = $_GET['cat'];

print "cat = $cat
";

$products = $productDB->prepare('SELECT * FROM products WHERE cat_id LIKE ?');

$products->execute(array($cat));

$rows = $products->rowCount();

print "$rows rows returned";

?>

product_idproduct_name

foreach ($products->fetchAll() as $row) {

$id = $row['product_id'];

$product_name = $row['product_name'];

print "

";

print "

$id";

print "

$product_name ";

print "

";

}

print "

";

}

?>

当我运行此代码时,它会根据查询打印正确的行数,但不会填充表.

我也尝试用以下代码替换prepare和execute行:

$products = $productDB->query("SELECT * FROM products WHERE cat_id LIKE $cat");

返回正确的行数,但没有其他帮助.

最后,我尝试用以下内容替换foreach行:

$rows = $products->fetchAll();

foreach ($rows as $row) {

我尝试使用固定查询执行相同的操作都可以正常工作,但我无法确定如何在查询中放置变量元素,然后迭代结果.

解决方法:

试试这个(如果我理解正确的话):

$products = $productDB->prepare("SELECT * FROM products WHERE cat_id LIKE :cat");

// Now, you can either do this :

$products->bindParam('cat', '%'.$cat.'%');

$products->execute();

// or you can call execute with an associative array of your parameterized query.

$products->execute(array('cat' => '%'.$cat.'%'));

// Then, get all the results like this :

$rows = $products->fetchAll();

foreach ($rows as $row) {

// Do work here ..

}

// Or, like this :

while ($row = $products->fetch(PDO::FETCH_ASSOC)) {

// Do work here ..

}

我个人更喜欢while,因为你没有在一个var中获取整个查询,减少了所需的内存量.

我还建议您使用FETCH_*参数,以获得您想要的那种数组.

顺便说一下,您需要知道rowCount不应该用于计算SELECT返回的行数.正如php.net所说:

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

标签:php,mysql,pdo

来源: https://codeday.me/bug/20190620/1246112.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值