如何使用 PHP 建立数据库
步骤 1:建立连接
1
2
3
4
$servername = “localhost”;
$username = “root”;
$password = “password”;
$conn = new PDO(“mysql:host=$servername;dbname=db_name”, $username, $password);
步骤 2:创建数据库
步骤 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->搭建源码点我wcqh.cnprepare($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 搭建源码点我wcqh.cnname = ? 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:关闭连接
1
$conn->close();
以上就是如何用php建立数据库的详细内容,更多请关注青狐资源网其它相关文章!
暂无评论内容