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

溫馨提示×

如何用php mysql類實現查詢功能

PHP
小樊
84
2024-09-22 00:10:37
欄目: 云計算

要用PHP和MySQL類實現查詢功能,首先需要創建一個MySQL連接,然后使用SQL查詢語句執行查詢,最后處理查詢結果。以下是一個簡單的示例:

  1. 創建一個MySQL連接類(DatabaseConnection.php):
<?php
class DatabaseConnection {
    private $host = 'localhost';
    private $username = 'your_username';
    private $password = 'your_password';
    private $database = 'your_database';

    public function __construct() {
        $this->connection = new mysqli($this->host, $this->username, $this->password, $this->database);
        if ($this->connection->connect_error) {
            die("連接失敗: " . $this->connection->connect_error);
        }
    }

    public function closeConnection() {
        $this->connection->close();
    }
}
?>
  1. 創建一個查詢類(Query.php):
<?php
class Query {
    private $connection;

    public function __construct($connection) {
        $this->connection = $connection;
    }

    public function select($table, $columns = "*", $condition = []) {
        $sql = "SELECT " . implode(", ", $columns) . " FROM " . $table;

        if (!empty($condition)) {
            $sql .= " WHERE ";
            $conditions = [];
            foreach ($condition as $key => $value) {
                $conditions[] = $key . " = '" . $value . "'";
            }
            $sql .= implode(" AND ", $conditions);
        }

        $result = $this->connection->query($sql);
        return $result;
    }
}
?>
  1. 在主文件中使用這兩個類(index.php):
<?php
require_once 'DatabaseConnection.php';
require_once 'Query.php';

$db = new DatabaseConnection();
$query = new Query($db->connection);

// 查詢示例
$table = 'users';
$columns = ['id', 'name', 'email'];
$condition = ['id' => 1];
$result = $query->select($table, $columns, $condition);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
    }
} else {
    echo "0 結果";
}

$db->closeConnection();
?>

這個示例展示了如何使用PHP和MySQL類實現基本的查詢功能。你可以根據需要進行修改和擴展。

0
芒康县| 淳安县| 区。| 安图县| 上高县| 六安市| 克什克腾旗| 开封县| 阜南县| 陈巴尔虎旗| 聂拉木县| 金寨县| 砚山县| 嘉定区| 中江县| 海林市| 崇阳县| 儋州市| 融水| 红桥区| 福安市| 益阳市| 九龙坡区| 巧家县| 古丈县| 获嘉县| 磐石市| 北京市| 鹤庆县| 井冈山市| 孟州市| 芮城县| 广南县| 望江县| 黄龙县| 临高县| 济宁市| 长治市| 苍溪县| 平乡县| 栖霞市|