How can PHP developers efficiently handle and display data from a MySQL database in a web application without compromising security?
To efficiently handle and display data from a MySQL database in a web application without compromising security, PHP developers should use prepared statements to prevent SQL injection attacks. Prepared statements separate SQL logic from user input, making it safer to interact with the database. Additionally, developers should validate and sanitize user input to prevent cross-site scripting attacks.
// Establish a connection to the MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Prepare a SQL statement
$stmt = $mysqli->prepare("SELECT id, name, email FROM users WHERE id = ?");
// Bind parameters
$stmt->bind_param("i", $id);
// Set the parameter values
$id = $_GET['id'];
// Execute the query
$stmt->execute();
// Bind result variables
$stmt->bind_result($id, $name, $email);
// Fetch results
$stmt->fetch();
// Display the data
echo "ID: " . $id . "<br>";
echo "Name: " . $name . "<br>";
echo "Email: " . $email . "<br>";
// Close the statement and connection
$stmt->close();
$mysqli->close();
Keywords
Related Questions
- How does setting the Zend_Navigation in Zend_Registry resolve the issue with the Navigation-View-Helper in PHP?
- How can a PHP developer save a selected employee's name as a variable and use it in an SQL query to display specific data?
- How can PHP be used to display user data in a detail page after clicking on a user's name?