How can a navigation list be created and stored in a database in PHP?
To create and store a navigation list in a database in PHP, you can first design a database table to store the navigation items with columns like id, title, and link. Then, you can use PHP to insert, update, retrieve, and display the navigation items from the database.
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "navigation_db";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create a table to store navigation items
$sql = "CREATE TABLE navigation (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(30) NOT NULL,
link VARCHAR(50) NOT NULL
)";
if ($conn->query($sql) === TRUE) {
echo "Table navigation created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
// Insert a navigation item into the database
$title = "Home";
$link = "index.php";
$sql = "INSERT INTO navigation (title, link) VALUES ('$title', '$link')";
if ($conn->query($sql) === TRUE) {
echo "Navigation item inserted successfully";
} else {
echo "Error inserting navigation item: " . $conn->error;
}
// Retrieve and display navigation items from the database
$sql = "SELECT * FROM navigation";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Title: " . $row["title"]. " - Link: " . $row["link"]. "<br>";
}
} else {
echo "0 results";
}
// Close the database connection
$conn->close();
Keywords
Related Questions
- How can PHP functions like array_sum() be effectively utilized to calculate totals from multiple values stored in sessions?
- How can you ensure precision and clarity in formulating questions related to PHP development to receive accurate and helpful responses on forums?
- How can the script be modified to improve its readability and maintainability?