What common mistake is made in the PHP code provided for outputting data from a database table?
The common mistake in the provided PHP code is that it is vulnerable to SQL injection attacks due to directly concatenating user input into the SQL query. To solve this issue, it is recommended to use prepared statements with parameterized queries to safely handle user input.
// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL statement
$stmt = $pdo->prepare("SELECT * FROM mytable WHERE id = :id");
// Bind the parameter
$stmt->bindParam(':id', $_GET['id']);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();
// Output the data
foreach($results as $row) {
echo $row['column1'] . ' - ' . $row['column2'] . '<br>';
}
Related Questions
- What are the common pitfalls to avoid when working with timestamps and integer values in SQL queries in PHP?
- Are there any specific security measures to consider when using sessions in PHP for user authentication?
- How can one efficiently create a new array by looping through the length of an existing array in PHP?