How can MySQL tables be effectively utilized to store and retrieve FAQ categories and articles in PHP?
To effectively store and retrieve FAQ categories and articles in MySQL tables using PHP, you can create two tables: one for categories and another for articles with a foreign key linking them. You can use SQL queries to insert, update, and retrieve data from these tables based on the user's input or queries.
// Connect to MySQL database
$mysqli = new mysqli('localhost', 'username', 'password', 'database_name');
// Create categories table
$mysqli->query("CREATE TABLE categories (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL
)");
// Create articles table
$mysqli->query("CREATE TABLE articles (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(100) NOT NULL,
content TEXT,
category_id INT,
FOREIGN KEY (category_id) REFERENCES categories(id)
)");
// Insert a new category
$mysqli->query("INSERT INTO categories (name) VALUES ('Category Name')");
// Insert a new article
$mysqli->query("INSERT INTO articles (title, content, category_id) VALUES ('Article Title', 'Article Content', 1)");
// Retrieve articles for a specific category
$category_id = 1;
$result = $mysqli->query("SELECT * FROM articles WHERE category_id = $category_id");
// Display articles
while ($row = $result->fetch_assoc()) {
echo $row['title'] . ': ' . $row['content'] . '<br>';
}
// Close database connection
$mysqli->close();
Keywords
Related Questions
- What are the potential pitfalls and complexities that PHP beginners may face when using PHP for scripting file interfaces and job control tasks, and how can these be mitigated?
- What are the potential pitfalls of using hidden fields in PHP to store values?
- What are some potential pitfalls when using arrays in PHP, especially when trying to store unique values?