PHP MySQL 核心

MySQL 是跟 PHP 配套使用的最流行的开源数据库系统。

首先,我们可以在浏览器输入localhost打开phpMyAdmin,可以直观的看到我们对数据库操作后的结果

以下,我将全部以  面向过程  的方式来像大家讲解PHP操作SQL的过程:

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "myOneDB";  /* 这个是在创建之后才能查询连接成功的 */


// 创建连接

$conn = mysqli_connect($servername, $username, $password,$dbname);

if (!$conn)

{

die("连接失败: " . mysqli_connect_error($conn));

else

{

echo "链接成功";

}


// 创建数据库

$sql_create = "CREATE DATABASE myOneDB";

mysqli_query($conn, $sql_create);


//创建表

$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);


//插入数据

$sql_insert = "INSERT INTO
TableOne(id,name,phone)
VALUES(1,'zhangsan',13088888888)";

mysqli_query($conn,$sql_insert);


//插入多条数据

$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);


//查询数据

$sql_read = "SELECT id,name,phone,regist_time FROM TableOne";

$result = mysqli_query($conn,$sql_read);

if ($result -> num_rows > 0) 

{

echo "查询成功";

while ($row = $result -> fetch_assoc())

{

echo "id = ".$row["id"]."name = ".$row["name"]."phone = ".$row["phone"]."注册时间 = ".$row["regist_time"];

}

}


//where查询

$sql_where = "SELECT * FROM TableOne WHERE id='2'";

$result = mysqli_query($conn,$sql_where);

if ($result)

{

while ($row = mysqli_fetch_array($result))

{

echo "查询结果: id = ".$row["id"]."name = ".$row["name"];

}

}


//更新数据

$sql_update = "UPDATE TableOne SET name='ys' WHERE id=4";

mysqli_query($conn,$sql_update);


//关键词操作    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);  //关闭数据库!

你可能感兴趣的:(PHP MySQL 核心)