How can HTML forms be used to send username and password data to a MySQL database for authentication in PHP?
To send username and password data from an HTML form to a MySQL database for authentication in PHP, you can use the POST method to submit the form data to a PHP script. In the PHP script, you can retrieve the username and password values from the POST data and then query the MySQL database to check if the user exists and if the password is correct.
<?php
// Retrieve username and password from POST data
$username = $_POST['username'];
$password = $_POST['password'];
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Query database to check if user exists and password is correct
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($connection, $query);
// Check if a row was returned
if(mysqli_num_rows($result) > 0) {
// User authenticated
echo "User authenticated";
} else {
// User not authenticated
echo "Invalid username or password";
}
// Close database connection
mysqli_close($connection);
?>
Related Questions
- How can PHP be integrated with JavaScript or meta-refresh tags to achieve automatic redirection on a webpage?
- Are there alternative methods, such as arrays, that are recommended over using variable variables in PHP?
- What is the difference between normal variables and variables passed via URL or POST in PHP?