How do I display a MySQL error in PHP for a long query that depends on the user input?

How do I display a MySQL error in PHP for a long query that depends on the user input?

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

Stefan Bogdanescu

Founder & Senior Architect

Debugging MySQL Errors in Dynamic PHP Queries

When a complex query built from user input fails silently or outputs a generic "Query Failed" message, the immediate instinct is to assume the database is unreachable. However, in your specific scenario, the connection is likely fine; the issue lies in how the SQL string is constructed and executed. The code snippet you provided demonstrates a classic pattern: building a query dynamically based on GET or POST parameters without sanitization.

The line $where = "Findings.ServiceType_ID= ServiceType_Lookup..." reveals the root cause. You are directly interpolating user input ($service) and keywords into the SQL string. If a user enters a value containing a single quote (e.g., ' OR '1'='1), it breaks the syntax of your WHERE clause, causing the query to fail. Standard MySQL error reporting often catches this, but if you are using a framework or a specific driver configuration that suppresses detailed errors, you might only see a generic failure flag.

In your code, you have two distinct execution points: $this->db_link->query($query) and $r = mysqli_query(...). The first call uses the connection object's query method, while the second uses the global function. Crucially, mysqli_connect_error() checks for connection-level issues (like timeout or network loss), not SQL syntax errors. When a query fails due to bad syntax, you must use mysqli_error($this->db_link) instead.

To fix this immediately, update your error handling block:

$r = mysqli_query($this->db_link, $query);

if ($r === false) {
    // Check for connection errors first
    if (mysqli_connect_errno($this->db_link)) {
        printf("Database connection failed: %s", mysqli_connect_error());
    } else {
        // This is the correct function for SQL syntax errors
        printf("SQL Error: %s [Code: %d]", mysqli_error($this->db_link), mysqli_errno($this->db_link));
    }
}

Using mysqli_error() exposes the actual reason for failure. You will likely see messages like "You have an error in your SQL syntax near '...'" which points directly to the malicious or malformed input that broke the query structure.

However, fixing the error display is only half the battle. The underlying architecture of your code presents a severe security vulnerability. Since $service and $keyword come from user input, they must be treated as untrusted data. Concatenating them into a string before execution opens the door to SQL Injection attacks. An attacker could inject arbitrary commands, potentially extracting sensitive data from the Findings or ServiceType_Lookup tables.

The robust solution is to use prepared statements with bound parameters. This approach separates the query structure from the user data, ensuring that special characters like quotes are escaped automatically and never interpreted as SQL code. Here is how you should refactor the logic using PDO, which is generally preferred for its consistency across MySQL versions:

$pdo = new PDO("mysql:host=localhost;dbname=your_db", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $pdo->prepare("SELECT Finding_ID, Title FROM Findings WHERE ...");
// Bind the parameters securely
$stmt->execute([
    ':service' => $service, 
    ':keyword' => $keyword
]);

By binding parameters, you eliminate the risk of syntax errors caused by user input breaking your WHERE clause logic. The database driver handles the escaping transparently.

If you are using the legacy MySQLi extension, the process is similar but requires a slightly different syntax:

$stmt = $this->db_link->prepare("SELECT ... FROM " . $from . " WHERE ...");
// Bind parameters
$stmt->bind_param('ss', $service, $keyword); // Adjust types based on variable content
$stmt->execute();
$result = $stmt->get_result();

The trade-off here is a small performance overhead for the preparation step, but it guarantees that your application remains secure even if a user inputs a string designed to crash your query. Always prioritize prepared statements over string concatenation when handling dynamic filters or search terms.

Our network