How can one ensure data security when using PHP to search a MySQL database?
To ensure data security when using PHP to search a MySQL database, it is important to use prepared statements with parameterized queries. This helps prevent SQL injection attacks by separating SQL code from user input. Additionally, it is recommended to sanitize and validate user input before using it in database queries.
// Connect to MySQL 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 SQL query with a parameterized statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $search_username);
// Sanitize and validate user input
$search_username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
// Execute the query
$stmt->execute();
// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Output the results
}
// Close the statement and connection
$stmt->close();
$conn->close();
Related questions
-
regular expressions preg_split PHP
-
PHP MySQL database design
-
PHP file_get_contents include