What are common mistakes made when querying a MySQL database using PHP?
One common mistake when querying a MySQL database using PHP is not properly sanitizing user input, which can lead to SQL injection attacks. To prevent this, always use prepared statements with parameterized queries to securely interact with the database.
// Connect to the 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);
}
// Prepare a statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Set parameters and execute
$username = $_POST['username'];
$stmt->execute();
// Get the result
$result = $stmt->get_result();
// Fetch data
while ($row = $result->fetch_assoc()) {
echo "Username: " . $row['username'] . "<br>";
}
// Close statement and connection
$stmt->close();
$conn->close();
Keywords
Related Questions
- Are there alternative methods or technologies that can be used in place of traditional Captcha systems in PHP applications to improve security and user experience?
- How can PHP be used to extract specific text from a file on a server?
- How can the user ID and birthdate be effectively used to create a unique download path in PHP?