How can PHP be integrated with a database to store and retrieve product information for a shopping cart system?
To integrate PHP with a database for a shopping cart system, you can use SQL queries to store and retrieve product information. First, establish a connection to the database using PHP's mysqli or PDO extension. Then, write SQL queries to insert new products into the database and retrieve product information based on user input.
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "shopping_cart";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Insert new product into the database
$name = "Product Name";
$price = 10.99;
$category = "Electronics";
$sql = "INSERT INTO products (name, price, category) VALUES ('$name', $price, '$category')";
$conn->query($sql);
// Retrieve product information from the database
$category = "Electronics";
$sql = "SELECT * FROM products WHERE category = '$category'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"]. " - Price: $" . $row["price"]. "<br>";
}
} else {
echo "0 results";
}
// Close the database connection
$conn->close();
Related Questions
- How can the returned PhotoID be used to determine the actual URL of the uploaded image on Flickr?
- What are best practices for verifying the success of FTP operations in PHP before proceeding with additional steps?
- How can the use of JOIN operations in SQL queries improve the efficiency and readability of PHP code for database interactions?