在PHP中,使用MySQLi函數連接和操作MySQL數據庫時,需要正確設置參數。以下是一些常用的MySQLi函數及其參數設置:
mysqli_connect()
參數說明:
$host
:MySQL服務器的主機名或IP地址。$username
:用于連接到MySQL服務器的用戶名。$password
:用于連接到MySQL服務器的密碼。$database
:要連接的MySQL數據庫名稱(可選)。$port
:MySQL服務器的端口號(默認為3306)。示例代碼:
$conn = mysqli_connect("localhost", "username", "password", "database");
if (!$conn) {
die("連接失敗: " . mysqli_connect_error());
}
echo "連接成功";
mysqli_query()
參數說明:
$connection
:一個有效的MySQLi連接對象。$query
:要執行的SQL查詢字符串。示例代碼:
$conn = mysqli_connect("localhost", "username", "password", "database");
if (!$conn) {
die("連接失敗: " . mysqli_connect_error());
}
$sql = "SELECT id, name FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 結果";
}
mysqli_close($conn);
mysqli_prepare()
參數說明:
$connection
:一個有效的MySQLi連接對象。$query
:要準備的SQL查詢字符串。示例代碼:
$conn = mysqli_connect("localhost", "username", "password", "database");
if (!$conn) {
die("連接失敗: " . mysqli_connect_error());
}
$stmt = mysqli_prepare($conn, "INSERT INTO users (name, age) VALUES (?, ?)");
if (!$stmt) {
die("準備查詢失敗: " . mysqli_error($conn));
}
$name = "John";
$age = 25;
mysqli_stmt_bind_param($stmt, "si", $name, $age);
if (mysqli_stmt_execute($stmt)) {
echo "新記錄插入成功";
} else {
echo "Error: " . mysqli_error($conn);
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
mysqli_real_escape_string()
參數說明:
$connection
:一個有效的MySQLi連接對象。$string
:要轉義的字符串。示例代碼:
$conn = mysqli_connect("localhost", "username", "password", "database");
if (!$conn) {
die("連接失敗: " . mysqli_connect_error());
}
$username = "O'Reilly";
$password = "secret";
$username = mysqli_real_escape_string($conn, $username);
$password = mysqli_real_escape_string($conn, $password);
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "登錄成功";
}
} else {
echo "用戶名或密碼錯誤";
}
mysqli_close($conn);
注意:在實際開發中,為了提高安全性,建議使用預處理語句(prepared statements)來防止SQL注入攻擊。