php使用PDO查询MYSQL的3种方法

直接看代码,我通常使用第1种方法

<?php

//连接数据库
$dsn = "mysql:host=localhost:3306;dbname=test";
$username = "root";
$password = "";
$conn = new PDO($dsn, $username, $password);
$conn->exec("SET NAMES 'utf8'");

//准备语句
$sql="select * from test2";
$stmt=$conn->prepare($sql);
$stmt->execute();

//方法1
foreach($stmt as $row){
    echo $row[0];
    echo $row["id"];
}

//方法2
while($row=$stmt->fetch(PDO::FETCH_BOTH)){
    echo $row[0];
    echo $row["id"];
}

//方法3
$rows=$stmt->fetchAll(PDO::FETCH_BOTH);
foreach($rows as $row){
    echo $row[0];
    echo $row["id"];
}


?>

 



发表评论

您的电子邮箱地址不会被公开。

90 − 84 =