The method to implement a many-to-one address book in php is: 1. Create two database tables, one to store user information and the other to store contact information; 2. In the contact table Add a foreign key field that points to the primary key in the user table to correspond to multiple contacts.
Operating system for this tutorial: Windows 10 system, php8.1.3 version, Dell G3 computer.
PHP can implement many-to-one address books by using database operations, object-oriented programming, etc.Among them, many-to-one means that multiple contacts correspond to one user (address book owner).
The implementation method is: create two database tables, one is used to store user information, including user name, password, etc., and the other is used to store contact information, including name, phone number, etc. Add a foreign key field to the Contacts table that points to the primary key in the Users table. In this way, one user can correspond to multiple contacts.
Benefits:
Can easily manage and maintain contact information.
can improve data security and prevent contact information from being accessed or tampered with by other users.
Easy to expand and optimize.
Code example: The following code demonstrates how to use PDO (PHP Data Objects) to implement basic many-to-one address book functionality.
```php // 创建数据库连接 $db = new PDO('mysql:host=localhost;dbname=mydb;charset=utf8', 'username', 'password'); // 新增用户 $stmt = $db->prepare("INSERT INTO users (username, password) VALUES (?, ?)"); $username = 'user1'; $password = 'pass1'; $stmt->execute([$username, $password]); $user_id = $db->lastInsertId(); // 获取新用户的ID // 新增联系人 $stmt = $db->prepare("INSERT INTO contacts (name, phone, user_id) VALUES (?, ?, ?)"); $name = 'contact1'; $phone = '1234567890'; $stmt->execute([$name, $phone, $user_id]); // 查询联系人 $stmt = $db->prepare("SELECT * FROM contacts WHERE user_id = ?"); $user_id = 1; // 假设要查询用户ID为1的联系人 $stmt->execute([$user_id]); $contacts = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach ($contacts as $contact) { echo "Name: {$contact['name']}, Phone: {$contact['phone']}\n"; } ```
The above is the detailed content of How to implement many-to-one address book in php. For more information, please follow other related articles on the PHP Chinese website!