In the provided code, how can the issue of each product getting a new database record be prevented?
The issue of each product getting a new database record can be prevented by checking if a record with the same product name already exists in the database before inserting a new record. This can be achieved by querying the database to see if a record with the same product name exists, and if it does, updating the existing record instead of inserting a new one.
// Check if a record with the same product name already exists in the database
$query = "SELECT * FROM products WHERE product_name = '$product_name'";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0) {
// Update the existing record
$row = mysqli_fetch_assoc($result);
$existing_product_id = $row['product_id'];
$update_query = "UPDATE products SET product_price = '$product_price', product_quantity = '$product_quantity' WHERE product_id = '$existing_product_id'";
mysqli_query($conn, $update_query);
} else {
// Insert a new record
$insert_query = "INSERT INTO products (product_name, product_price, product_quantity) VALUES ('$product_name', '$product_price', '$product_quantity')";
mysqli_query($conn, $insert_query);
}
Related Questions
- What are some best practices for creating multiple SQL tables in PHP using loops or arrays?
- How can the use of prepared statements in PHP help prevent SQL injection attacks?
- What are common issues with using htmlspecialchars() in PHP, particularly with strings containing special characters like umlauts?