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入门 内容,请继续关注web建站教程。
当前网址:https://m.ipkd.cn/webs_15773.html
声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!