Asked
Updated
Viewed
2.6k times

I've implemented a PHP script to handle form submissions and insert data into a PostgreSQL database. However, I'm concerned about the potential security vulnerabilities, particularly SQL injection. While I've used pg_escape_string() to sanitize user input, I understand that it might not provide sufficient protection against all SQL injection attacks.

What are the best practices for enhancing security against SQL injection when using PHP with PostgreSQL? Should I switch to using parameterized queries (prepared statements) with PDO or mysqli extension instead of pg_escape_string()? If so, could someone provide guidance or code examples on how to implement parameterized queries securely in my PHP code?

add a comment
0

1 Answer

  • Votes
  • Oldest
  • Latest
Answered
Updated

Definitely use PDO and prepared statements. This will ensure that the SQL query and its parameters are separated, making it impossible for an attacker to inject malicious SQL code.

Assuming you have already setup $pdo to be a PDO connection to your PostgreSQL database, and assuming we are trying to insert a username and email into a users table, then it would simply look like this:

$username = 'Cool User';
$email = 'cool-user@domain.com';

// Prepare an SQL statement with placeholders
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");

// Bind the actual values to the placeholders
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);

// Execute the statement
$stmt->execute();
add a comment
0