How can a login script be effectively written in PHP to validate user inputs against a MySQL database for a mobile app?
To create a login script in PHP for a mobile app, you need to validate user inputs against a MySQL database. This can be done by querying the database to check if the provided username and password match any existing records. If a match is found, the user can be granted access to the app.
<?php
// Establish a connection to the MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Retrieve user inputs from the mobile app
$username = $_POST['username'];
$password = $_POST['password'];
// Query the database to check if the username and password match
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($connection, $query);
// Check if a match is found
if (mysqli_num_rows($result) == 1) {
// User is authenticated, grant access to the mobile app
echo "Login successful!";
} else {
// User credentials are incorrect, display an error message
echo "Invalid username or password";
}
// Close the database connection
mysqli_close($connection);
?>