91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

php中怎么使用pdo查詢數據

PHP
小億
129
2024-02-01 10:35:40
欄目: 編程語言

在使用PDO查詢數據時,可以按照以下步驟進行操作:

  1. 連接到數據庫:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database_name";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
  1. 編寫SQL查詢語句:
$sql = "SELECT * FROM table_name";
  1. 準備并執行查詢語句:
$stmt = $conn->prepare($sql);
$stmt->execute();
  1. 獲取查詢結果:
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1. 處理查詢結果:
foreach($result as $row) {
    echo $row['column_name'];
}

完整的示例代碼如下:

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database_name";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";

    $sql = "SELECT * FROM table_name";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach($result as $row) {
        echo $row['column_name'];
    }
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

注意替換$servername$username$password$dbname為實際的數據庫連接信息。同時,將table_namecolumn_name替換為實際的表名和列名。

0
浑源县| 河西区| 靖宇县| 深水埗区| 南昌县| 平阳县| 栾城县| 平凉市| 梅州市| 磐安县| 随州市| 漠河县| 宝鸡市| 象山县| 纳雍县| 罗江县| 东至县| 浪卡子县| 庆云县| 曲靖市| 晋城| 德清县| 资溪县| 乌鲁木齐市| 文登市| 航空| 改则县| 黎平县| 读书| 子洲县| 郑州市| 南京市| 道真| 那坡县| 望奎县| 措勤县| 新郑市| 阿勒泰市| 仁化县| 西和县| 海阳市|