MySQL是一種自由和開放源代碼的關系型數(shù)據(jù)庫管理系統(tǒng)。它基于SQL數(shù)據(jù)語言,并支持多線程、事務處理和多用戶操作。MySQL廣泛應用于Web應用程序的開發(fā),特別是在LAMP(Linux、Apache、MySQL和PHP/Perl/Python)堆棧中。
//連接到MySQL數(shù)據(jù)庫服務器
$conn = mysqli_connect("localhost", "root", "password");
//創(chuàng)建數(shù)據(jù)庫
$sql = "CREATE DATABASE mydatabase";
if(mysqli_query($conn, $sql)){
echo "創(chuàng)建數(shù)據(jù)庫成功";
} else{
echo "創(chuàng)建數(shù)據(jù)庫失敗,錯誤信息: " . mysqli_error($conn);
}
//創(chuàng)建數(shù)據(jù)表
$sql = "CREATE TABLE mytable (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL
)";
if(mysqli_query($conn, $sql)){
echo "創(chuàng)建數(shù)據(jù)表成功";
} else{
echo "創(chuàng)建數(shù)據(jù)表失敗,錯誤信息: " . mysqli_error($conn);
}
//插入數(shù)據(jù)
$sql = "INSERT INTO mytable (firstname, lastname) VALUES ('John', 'Doe')";
if(mysqli_query($conn, $sql)){
echo "數(shù)據(jù)插入成功";
} else{
echo "數(shù)據(jù)插入失敗,錯誤信息: " . mysqli_error($conn);
}
//查詢數(shù)據(jù)
$sql = "SELECT * FROM mytable";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) >0){
while($row = mysqli_fetch_assoc($result)){
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "
";
}
} else{
echo "沒有數(shù)據(jù)";
}
//關閉數(shù)據(jù)庫連接
mysqli_close($conn);
以上代碼演示了如何使用PHP連接到MySQL服務器、創(chuàng)建數(shù)據(jù)庫和數(shù)據(jù)表、插入數(shù)據(jù)和查詢數(shù)據(jù)。