What is the potential issue with the code snippet provided for searching in a SQL database using PHP?
The potential issue with the code snippet provided is that it is vulnerable to SQL injection attacks. To solve this issue, you should use prepared statements with parameterized queries to prevent malicious input from being executed as SQL code.
// Fix for searching in a SQL database using PHP with prepared statements
$search_term = $_GET['search_term'];
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("SELECT * FROM table_name WHERE column_name LIKE ?");
$search_term = "%" . $search_term . "%";
$stmt->bind_param("s", $search_term);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Output the results
}
$stmt->close();
$conn->close();
Related Questions
- Are there any best practices for structuring PHP and HTML code within the same file?
- What is the purpose of using ADODB's Cache function in PHP and what are the potential benefits?
- What are the potential pitfalls of using COUNT(*) in a SQL query when trying to count the number of tables in a database?