亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

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
九寨沟县| 图木舒克市| 青龙| 金阳县| 陆河县| 诸城市| 岑巩县| 寻乌县| 繁峙县| 谢通门县| 全州县| 松溪县| 道真| 建平县| 远安县| 山西省| 德化县| 津市市| 大姚县| 湾仔区| 河东区| 根河市| 阿拉善盟| 修武县| 湖口县| 南部县| 那坡县| 武鸣县| 三门峡市| 邵东县| 元氏县| 新竹县| 墨脱县| 临湘市| 扎鲁特旗| 碌曲县| 保靖县| 文成县| 晴隆县| 扶沟县| 岑巩县|