How can PHP and MySQL be effectively used to manage user logins and shopping carts in an online shop?
To manage user logins and shopping carts in an online shop using PHP and MySQL, you can create a database table to store user information including usernames, passwords, and shopping cart items. When a user logs in, you can authenticate their credentials against the database. To manage shopping carts, you can store cart items in a separate table linked to the user's ID.
// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "shop";
$conn = new mysqli($servername, $username, $password, $dbname);
// User login authentication
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// User authenticated, set session variables
$_SESSION['username'] = $username;
}
// Add item to shopping cart
$item_id = $_POST['item_id'];
$user_id = $_SESSION['user_id'];
$sql = "INSERT INTO shopping_cart (user_id, item_id) VALUES ('$user_id', '$item_id')";
$conn->query($sql);
Keywords
Related Questions
- Can you provide a best practice example of how to retrieve Google Login email using Ajax and pass it to a PHP script for validation?
- What are some best practices for handling Excel file downloads in PHP to avoid format or extension errors?
- What potential issues can arise when using number_format in PHP for formatting values in a PDF table?