在 php 中建立数据库共有 8 个步骤:建立连接、创建数据库、创建表、插入数据、查询数据、更新数据、删除数据和关闭连接。
如何使用 php 建立数据库
步骤 1:建立连接
1
2
3
4
|
$servername = "localhost" ;
$username = "root" ;
$password = "password" ;
$conn = new PDO( "Mysql:host=$servername;dbname=db_name" , $username , $password );
|
步骤 2:创建数据库
1
2
|
$sql = "CREATE dataBASE db_name" ;
$conn ->query( $sql );
|
步骤 3:创建表
立即学习“PHP免费学习笔记(深入)”;
1
2
3
4
5
6
|
$sql = "CREATE Table table_name (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
age INT(3) UNSIGNED NOT NULL
)";
$conn ->query( $sql );
|
步骤 4:插入数据
1
2
3
4
5
6
|
$sql = "INSERT INTO table_name (name, age) VALUES (?, ?)" ;
$stmt = $conn ->prepare( $sql );
$stmt ->bind_param( "ss" , $name , $age );
$name = "John Doe" ;
$age = 30;
$stmt ->execute();
|
步骤 5:查询数据
1
2
3
4
5
|
$sql = "SELECT * FROM table_name" ;
$stmt = $conn ->query( $sql );
while ( $row = $stmt ->fetch_assoc()) {
echo $row [ 'name' ] . '<br>' ;
}
|
步骤 6:更新数据
1
2
3
4
5
6
|
$sql = "UPDATE table_name SET name = ? Where id = ?" ;
$stmt = $conn ->prepare( $sql );
$stmt ->bind_param( "si" , $name , $id );
$name = "John Smith" ;
$id = 1;
$stmt ->execute();
|
步骤 7:删除数据
1
2
3
4
5
|
$sql = "DELETE FROM table_name WHERE id = ?" ;
$stmt = $conn ->prepare( $sql );
$stmt ->bind_param( "i" , $id );
$id = 1;
$stmt ->execute();
|
步骤 8:关闭连接