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();