Prepared Statements

Fillestar 13 min Siguria e Aplikacioneve Web

Hyrje

A prepared statement is a SQL template sent to the database ahead of the parameters; the database parses the template once and then executes it with each set of supplied values.

Teoria

In PHP PDO, a prepared statement looks like this: $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?"); $stmt->execute([$email]);. The parameter is never concatenated into the SQL string; the database treats it strictly as data regardless of its content. You could pass '; DROP TABLE users-- as the email and it would simply fail to match any row — no table gets dropped. In other languages the API looks similar: Python psycopg2 uses cur.execute("SELECT ... WHERE id=%s", (user_id,)), Java PreparedStatement uses positional ? placeholders and setInt/setString, Node.js mysql2 takes the query and parameters as two arguments. The common rule: if you find yourself building a SQL string with string concatenation, stop and use parameters instead. One subtlety: prepared statements protect values, not identifiers. If you need to dynamically choose a table or column name, you still have to validate that name against a strict allow-list yourself. Everything else — LIMIT values, ORDER BY direction, INSERT column lists — should either be parameterized (where the driver supports it) or validated against a hardcoded list.

Mjetet

Mjete:

  • PHP PDO, mysqli (me bind_param).
  • Python: psycopg2, sqlite3, pymysql.
  • Java JDBC PreparedStatement.
  • Node.js: pg, mysql2 me placeholders.

Praktika

PHP PDO i sigurt:

$pdo = new PDO($dsn, $user, $pass, [
    PDO::ATTR_EMULATE_PREPARES => false,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$stmt = $pdo->prepare('SELECT id, email FROM users WHERE email = ? AND is_active = 1');
$stmt->execute([$email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

Python psycopg:

cur.execute('SELECT id FROM users WHERE email=%s', (email,))  # OK
# cur.execute(f'... email={email}')  # GABIM!

Ushtrime

  1. Konverto 5 queries të pasigurta në një codebase ekzistues në prepared statements.
  2. Verifiko me sqlmap që nuk ka më SQLi.

Burime

  • PHP PDO — php.net.
  • OWASP — Query Parameterization Cheat Sheet.

Vlerësimet dhe komentet

Kyçu për të lënë një vlerësim.

Ende pa komente. Bëhu i pari!

Diskutime

Ende pa diskutime. Hap një temë të re