PHP variables don't evaluate in the query

PHP variables don't evaluate in the query

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

PHP Variables Don't Evaluate in Queries

A common stumbling block for developers transitioning from procedural scripts to modern web frameworks involves a fundamental misunderstanding of how SQL strings are parsed. The specific error pattern seen when attempting to inject variables directly into query strings—such as $sql = 'SELECT * FROM $usertable WHERE PartNumber = $partid';—is not a bug in PHP or MySQL; it is a consequence of how the language handles string interpolation versus literal text. When you execute that code, the database receives the exact characters $usertable and $partid. It does not know to replace them with actual table names or values. To make this work, you must explicitly instruct PHP to interpolate variables within double-quoted strings, but even then, mixing dynamic SQL construction with data retrieval creates severe security vulnerabilities.

String Interpolation vs. Literal Text

The primary issue lies in the distinction between single and double quotes in PHP. In your example, the query is wrapped in single quotes. Single quotes treat everything inside them as literal text; no variable expansion occurs. Even if you change the delimiters to double quotes like $sql = "SELECT * FROM $usertable ...";, the approach remains flawed because it constructs a raw SQL string before sending it to the database driver.

The correct method for handling values that need to be inserted into a query is to use prepared statements with bound parameters. This technique separates the SQL logic from the data. By using placeholders like ? or named parameters, you ensure that the database engine treats the input as data rather than executable code. For instance, instead of concatenating the variable directly, you would write:

$sql = 'SELECT * FROM ? WHERE PartNumber = ?'; // Note: Table name binding is complex in some drivers
$stmt = $con->prepare($sql);
// Binding the table name separately if dynamic, or hardcoding safe tables

However, a critical nuance exists regarding table names. Most database drivers do not allow binding table identifiers (like $usertable) as parameters because they are not values but structural components of the query. Therefore, while you should bind the value ($partid) using a prepared statement to prevent SQL injection, the table name often must be hardcoded or validated against a strict whitelist before being inserted into the query string.

The Risk of SQL Injection

The original code snippet provided is vulnerable to SQL injection if $partid originates from user input via $_GET. If an attacker inputs ' OR '1'='1 as the value for part, the resulting query becomes:

SELECT * FROM usertable WHERE PartNumber = ' OR '1'='1'

This alters the logic of the query entirely, potentially exposing every row in the table. Prepared statements mitigate this by sending the SQL structure and the data to the server separately. The database parses the structure first, then validates the data against its type constraints (e.g., ensuring a string goes into a text field). This means that even if the input contains quotes or special characters, they are treated as literal data characters, not command operators.

Handling Data Types and Case Sensitivity

The source material mentions issues searching for numbers versus letters. In many MySQL configurations, string comparisons are case-insensitive by default, but numeric types handle inputs strictly. If your PartNumber column is defined as an integer in the schema, passing a string like 'abc' will result in no matches, which might look like an error to a novice developer. Conversely, if the column is a VARCHAR, you must ensure the data types align.

Using prepared statements handles this gracefully. When you bind $partid using mysqli_stmt_bind_param('s', $part), you explicitly tell MySQL, "This input is a string." If your schema expects an integer, the driver will return a type mismatch error immediately, alerting you to the schema discrepancy before any data is retrieved. This strict typing is often more helpful than silent failures that occur when PHP concatenates strings and sends malformed SQL.

Modern Best Practices with Laravel

While raw mysqli connections are useful for legacy scripts or simple tools, they require manual handling of connection pooling, prepared statements, and escaping. If you are building a new application or refactoring existing code, the Laravel framework abstracts these complexities. Laravel's query builder and Eloquent ORM enforce the use of bound parameters automatically.

For example, in a Laravel controller, the equivalent operation looks like this:

$part = request('part');
$result = DB::table('usertable')
    ->where('PartNumber', $part)
    ->first();

Here, Laravel generates the safe SQL behind the scenes and binds the parameter automatically. You don't need to worry about quote escaping or variable interpolation rules because the framework constructs the query using an array of conditions where keys are column names (strings) and values are parameters (data). This approach eliminates the possibility of accidentally injecting code into table names or column identifiers, which is a frequent source of bugs when writing raw SQL strings manually.

Our network