What are the best practices for storing and retrieving user data in a MySQL database using PHP?
When storing and retrieving user data in a MySQL database using PHP, it is important to sanitize user input to prevent SQL injection attacks. Use prepared statements to safely execute SQL queries and bind parameters to prevent malicious input from affecting the database. Additionally, always validate user input to ensure data integrity and security.
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Sanitize user input
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
// Prepare and bind SQL statement
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $password);
// Execute SQL statement
$stmt->execute();
// Close statement and connection
$stmt->close();
$conn->close();
Related Questions
- What alternative approaches can be used to access POST variables if $_POST is not functioning properly in PHP5?
- What are some best practices for handling form validation and error messages in PHP?
- Are there specific resources or tutorials available to help beginners understand and address issues related to register_globals in PHP?