In the context of the forum thread, what are some common pitfalls that PHP beginners may encounter when working with MySQL queries in their scripts?
One common pitfall for PHP beginners when working with MySQL queries is not properly sanitizing user input, which can leave the script vulnerable to SQL injection attacks. To solve this issue, it is recommended to use prepared statements with parameterized queries to securely interact with the database.
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare and bind statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Set parameters and execute
$username = $_POST['username'];
$stmt->execute();
// Get 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();