Home > Article > Backend Development > PHP Programming Tips: Create an Efficient Many-to-One Address Book Application
Due to limited time, I will provide you with a sample code for a simple many-to-one address book application based on PHP and MySQL, and provide certain explanations. Hope this helps you understand how to build an efficient many-to-one address book application.
Now, let’s start building this address book application!
First, we need to create a MySQL database table named contacts to store contact data. The structure of the table is as follows:
CREATE TABLE contacts ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50) NOT NULL, phone_number VARCHAR(20) NOT NULL );
Next, we need to write PHP code to connect to the MySQL database. The following is a simple database connection code:
<?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); } ?>
Now, let us write the PHP code to retrieve the contacts from the database and display them on the web page. Here is a simple code example:
<?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."; } ?>
Next, let us write code to implement the function of adding new contacts. Here is a simple code example:
<?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; } } ?>
Finally, we need to add a form to the web page to enter the new contact information. Here is a simple code example:
<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>
The above is a simple implementation of the address book application. Through the above code, you can implement the functions of displaying the contact list and adding new contacts. Of course, there are more functional and safety issues that need to be considered in practical applications.
Hope this example can help you better understand how to use PHP and MySQL to build an efficient many-to-one address book application. Good luck with your programming!
The above is the detailed content of PHP Programming Tips: Create an Efficient Many-to-One Address Book Application. For more information, please follow other related articles on the PHP Chinese website!