如何用php mysql類實(shí)現(xiàn)查詢功能

PHP
小樊
82
2024-09-22 00:10:37
欄目: 云計(jì)算

要用PHP和MySQL類實(shí)現(xiàn)查詢功能,首先需要?jiǎng)?chuàng)建一個(gè)MySQL連接,然后使用SQL查詢語句執(zhí)行查詢,最后處理查詢結(jié)果。以下是一個(gè)簡(jiǎn)單的示例:

  1. 創(chuàng)建一個(gè)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. 創(chuàng)建一個(gè)查詢類(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. 在主文件中使用這兩個(gè)類(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 結(jié)果";
}

$db->closeConnection();
?>

這個(gè)示例展示了如何使用PHP和MySQL類實(shí)現(xiàn)基本的查詢功能。你可以根據(jù)需要進(jìn)行修改和擴(kuò)展。

0