What best practices should be followed to prevent SQL injection in PHP scripts like the one discussed in the forum thread?
To prevent SQL injection in PHP scripts, it is important to use prepared statements with parameterized queries instead of directly inserting user input into SQL queries. This helps to sanitize and escape user input, preventing malicious SQL code from being executed.
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Using prepared statements to prevent SQL injection
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $password);
// Set parameters and execute
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
Related Questions
- What is the purpose of using a checkbox with a database query in PHP?
- In what ways can the source of images obtained from third-party sources like tmdb.org be properly credited on a website to comply with API rules and copyright regulations?
- Are there any potential pitfalls to be aware of when handling series of events with the Synology Calendar API in PHP?