Parameterized queries in PHP, Python & Ruby: what is your default pattern for dynamic SQL?

0

I work across PHP, Python, Ruby and plain SQL, and one thing I keep noticing in code reviews is that every stack has its own "safe" way to build queries, and people still end up concatenating strings when a query gets dynamic (search filters, ORDER BY, IN lists, etc.).

So I'm curious what everyone treats as their default pattern. Here's mine as a starting point:

PHP (PDO):

php

<?php
$stmt = $pdo->prepare('SELECT id, name FROM users WHERE email = :email');
$stmt->execute([':email' => $email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

Python (sqlite3 / DB-API):

python

cur.execute("SELECT id, name FROM users WHERE email = ?", (email,))
user = cur.fetchone()

Ruby (ActiveRecord):

ruby

user = User.where("email = ?", email).first

More examples per language (PHP PDO, Ruby, Java, .NET, Rust):

https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html

For Example:

Where it gets messy for me:

1. ORDER BY / column names can't be bound as parameters, so I use an allow-list map (user value -> known column). Does anyone do it differently?

2. IN (…) lists with a variable number of values. Do you generate the placeholders yourself or rely on the ORM?
3. When you review someone else's code, what's the first red flag you look for?

Drop your go-to pattern for your language (Java, C#, Go, Rust, Node, whatever) so this can turn into a useful reference thread for newer devs.

Want to practice? Free hands-on lab:

https://www.cs.montana.edu/pearsall/classes/fall2024/476/labs/Lab4.html

Loading discussion…Preparing formatted code and rich content.

Join the Discussion

Respond directly to the original thread. To respond to another member, use Reply under that response.

Join the discussion

Log in with your ProfoundSyntax account to participate.

Log In to Reply

0 Replies