MySQL 是跟 PHP 配套使用的最流行的開(kāi)源數(shù)據(jù)庫(kù)系統(tǒng)放案。
首先蓬痒,我們可以在瀏覽器輸入localhost打開(kāi)phpMyAdmin,可以直觀(guān)的看到我們對(duì)數(shù)據(jù)庫(kù)操作后的結(jié)果
以下,我將全部以 ?面向過(guò)程? 的方式來(lái)像大家講解PHP操作SQL的過(guò)程:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myOneDB"; ?/* 這個(gè)是在創(chuàng)建之后才能查詢(xún)連接成功的 */
// 創(chuàng)建連接
$conn = mysqli_connect($servername, $username, $password,$dbname);
if (!$conn)
{
die("連接失敗: " . mysqli_connect_error($conn));
}?
else
{
echo "鏈接成功";
}
// 創(chuàng)建數(shù)據(jù)庫(kù)
$sql_create = "CREATE DATABASE myOneDB";
mysqli_query($conn, $sql_create);
//創(chuàng)建表
$createTable = "CREATE TABLE TableOne?(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
phone INT(11) UNSIGNED NOT NULL,
regist_time TIMESTAMP
)";
mysqli_query($conn,$createTable);
//插入數(shù)據(jù)
$sql_insert = "INSERT INTO
TableOne(id,name,phone)
VALUES(1,'zhangsan',13088888888)";
mysqli_query($conn,$sql_insert);
//插入多條數(shù)據(jù)
$sql_insert? = "INSERT INTO TableOne(id,name,phone)
VALUES (2,'lisi',15738298760);";
$sql_insert .= "INSERT INTO TableOne(id,name,phone)
VALUES (3,'wangwu',13083458800);";
$sql_insert .= "INSERT INTO TableOne(id,name,phone)
VALUES (4,'zhaoliu',17798209357);";
mysqli_multi_query($conn,$sql_insert);
//刪除
$sql_deleteTable? = "DELETE FROM TableOne WHERE id=3;";
$sql_deleteTable .= "DELETE FROM TableOne WHERE id=4;";
$sql_deleteTable .= "DELETE FROM TableOne WHERE id=5;";
mysqli_multi_query($conn,$sql_deleteTable);
//查詢(xún)數(shù)據(jù)
$sql_read = "SELECT id,name,phone,regist_time FROM TableOne";
$result = mysqli_query($conn,$sql_read);
if ($result -> num_rows > 0)?
{
echo "查詢(xún)成功";
while ($row = $result -> fetch_assoc())
{
echo "id = ".$row["id"]."name = ".$row["name"]."phone = ".$row["phone"]."注冊(cè)時(shí)間 = ".$row["regist_time"];
}
}
//where查詢(xún)
$sql_where = "SELECT * FROM TableOne WHERE id='2'";
$result = mysqli_query($conn,$sql_where);
if ($result)
{
while ($row = mysqli_fetch_array($result))
{
echo "查詢(xún)結(jié)果: id = ".$row["id"]."name = ".$row["name"];
}
}
//更新數(shù)據(jù)
$sql_update = "UPDATE TableOne SET name='ys' WHERE id=4";
mysqli_query($conn,$sql_update);
//關(guān)鍵詞操作? ? DESC降序? ? ASC升序
$sql_orderby = "SELECT * FROM TableOne ORDER BY id DESC";
$result = mysqli_query($conn,$sql_orderby);
if ($result)
{
while ($row = mysqli_fetch_array($result))
{
echo "id = ".$row["id"]." name = ".$row["name"];
}
}
mysqli_close($conn); ?//關(guān)閉數(shù)據(jù)庫(kù)垄潮!