如何在PHP中通过PDO遍历MySQL查询?

如何在PHP中通过PDO遍历MySQL查询?,第1张

如何在PHP中通过PDO遍历MySQL查询

这是一个使用PDO连接到数据库,告诉它引发Exception(而不是php错误)(将帮助您调试)以及使用参数化语句而不是将动态值替换为查询本身的示例(强烈建议):

// $attrs is optional, this demonstrates using persistent connections,// the equivalent of mysql_pconnect$attrs = array(PDO::ATTR_PERSISTENT => true);// connect to PDO$pdo = new PDO("mysql:host=localhost;dbname=test", "user", "password", $attrs);// the following tells PDO we want it to throw Exceptions for every error.// this is far more useful than the default mode of throwing php errors$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);// prepare the statement. the place holders allow PDO to handle substituting// the values, which also prevents SQL injection$stmt = $pdo->prepare("SELECt * FROM product WHERe productTypeId=:productTypeId AND brand=:brand");// bind the parameters$stmt->bindValue(":productTypeId", 6);$stmt->bindValue(":brand", "Slurm");// initialise an array for the results $products = array();if ($stmt->execute()) {    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {        $products[] = $row;    }}// set PDO to null in order to close the connection$pdo = null;


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5052833.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-15
下一篇 2022-11-15

发表评论

登录后才能评论

评论列表(0条)

保存