What best practices should be followed when retrieving and displaying data from a MySQL database using PHP functions like mysql_query() and mysql_fetch_array()?
When retrieving and displaying data from a MySQL database using PHP functions like mysql_query() and mysql_fetch_array(), it is important to properly sanitize user input to prevent SQL injection attacks. Additionally, always check for errors when executing queries and fetching data to handle any potential issues gracefully. Finally, close the database connection after you are done working with the data to free up resources.
// Connect to the database
$conn = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Sanitize user input
$user_input = mysqli_real_escape_string($conn, $_POST['user_input']);
// Execute query
$query = "SELECT * FROM table WHERE column = '$user_input'";
$result = mysqli_query($conn, $query);
// Check for errors
if (!$result) {
die("Query failed: " . mysqli_error($conn));
}
// Fetch and display data
while ($row = mysqli_fetch_array($result)) {
echo $row['column_name'] . "<br>";
}
// Close connection
mysqli_close($conn);
Keywords
Related Questions
- How can one dynamically load content using a Pulldown with include in PHP?
- What are the best practices for handling language redirects in PHP based on user preferences?
- What best practices should be followed when handling file and directory operations in PHP to ensure efficient and error-free code execution?