您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

如何在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;
php 2022/1/1 18:15:55 有673人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶