php编程实战:小白轻松构建灵活高效的多对一通讯录代码示例
1、创建一个名为contacts的MySQL数据库表
CREATE TABLE contacts (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
phone_number VARCHAR(20) NOT NULL
);
2、连接数据库
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "contacts";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
3、显示联系人列表
<?php
$results = $conn->query("SELECT * FROM contacts");
if ($results->num_rows > 0) {
while ($row = $results->fetch_assoc()) {
echo "ID: " . $row['id'] . " - Name: " . $row['name'] . " - Phone Number: " . $row['phone_number'] . "<br>";
}
} else {
echo "No contacts found.";
}
?>
4、添加新联系人
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$phone_number = $_POST['phone_number'];
$sql = "INSERT INTO contacts (name, phone_number) VALUES ('$name', '$phone_number')";
if ($conn->query($sql) === TRUE) {
echo "New contact added successfully.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
5、添加表单
<form method="post">
Name: <input type="text" name="name"><br>
Phone Number: <input type="text" name="phone_number"><br>
<input type="submit" value="Add Contact">
</form>
以上是编程学习网小编为您介绍的“php编程实战:小白轻松构建灵活高效的多对一通讯录代码示例”的全面内容,想了解更多关于 php入门 内容,请继续关注编程基础学习网。