How do you check sql query is correct or not in php?

From MySQL 5.6.3 on you can use EXPLAIN for most queries

I made this and it works lovely:

function checkMySqlSyntax[$mysqli, $query] {
   if [ trim[$query] ] {
      // Replace characters within string literals that may *** up the process
      $query = replaceCharacterWithinQuotes[$query, '#', '%'] ;
      $query = replaceCharacterWithinQuotes[$query, ';', ':'] ;
      // Prepare the query to make a valid EXPLAIN query
      // Remove comments # comment ; or  # comment newline
      // Remove SET @var=val;
      // Remove empty statements
      // Remove last ;
      // Put EXPLAIN in front of every MySQL statement [separated by ;] 
      $query = "EXPLAIN " .
               preg_replace[Array["/#[^\n\r;]*[[\n\r;]|$]/",
                              "/[Ss][Ee][Tt]\s+\@[A-Za-z0-9_]+\s*:?=\s*[^;]+[;|$]/",
                              "/;\s*;/",
                              "/;\s*$/",
                              "/;/"],
                        Array["","", ";","", "; EXPLAIN "], $query] ;

      foreach[explode[';', $query] as $q] {
         $result = $mysqli->query[$q] ;
         $err = !$result ? $mysqli->error : false ;
         if [ ! is_object[$result] && ! $err ] $err = "Unknown SQL error";
         if [ $err] return $err ;
      }
      return false ;
  }
}

function replaceCharacterWithinQuotes[$str, $char, $repl] {
    if [ strpos[ $str, $char ] === false ] return $str ;

    $placeholder = chr[7] ;
    $inSingleQuote = false ;
    $inDoubleQuotes = false ;
    $inBackQuotes = false ;
    for [ $p = 0 ; $p < strlen[$str] ; $p++ ] {
        switch [ $str[$p] ] {
            case "'": if [ ! $inDoubleQuotes && ! $inBackquotes ] $inSingleQuote = ! $inSingleQuote ; break ;
            case '"': if [ ! $inSingleQuote && ! $inBackquotes ] $inDoubleQuotes = ! $inDoubleQuotes ; break ;
            case '`': if [ ! $inSingleQuote && ! $inDoubleQuotes ] $inBackquotes  = ! $inBackquotes ; break ;
            case '\\': $p++ ; break ;
            case $char: if [ $inSingleQuote || $inDoubleQuotes || $inBackQuotes] $str[$p] = $placeholder ; break ;
        }
    }
    return str_replace[$placeholder, $repl, $str] ;
 }

It wil return False if de query is OK [multiple ; separated statements allowed], or an error message stating the error if there is a syntax or other MySQL other [like non-existent table or column].

PHP Fiddle

KNOWN BUGS:

  • MySQL errors with linenumbers: the linenumbers mostly will not match.
  • Does not work for MySQL statements other than SELECT, UPDATE, REPLACE, INSERT, DELETE

[PHP 4, PHP 5]

mysql_querySend a MySQL query

Description

mysql_query[string $query, resource $link_identifier = NULL]: mixed

Parameters

query

An SQL query

The query string should not end with a semicolon. Data inside the query should be properly escaped.

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect[] is assumed. If no such link is found, it will try to create one as if mysql_connect[] had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query[] returns a resource on success, or false on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query[] returns true on success or false on error.

The returned result resource should be passed to mysql_fetch_array[], and other functions for dealing with result tables, to access the returned data.

Use mysql_num_rows[] to find out how many rows were returned for a SELECT statement or mysql_affected_rows[] to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

mysql_query[] will also fail and return false if the user does not have permission to access the table[s] referenced by the query.

Examples

Example #1 Invalid Query

The following query is syntactically invalid, so mysql_query[] fails and returns false.

Example #2 Valid Query

The following query is valid, so mysql_query[] returns a resource.

ix at nivelzero dot ro

17 years ago

here's a script for parsing a *.sql file [tested only on dumps created with phpMyAdmin] which is short and simple [why do people say "here's a short and simple script" and it has a 100 lines?]. the script skips comments and allows ; to be present within the querys

fernandoleal at loytek dot com

14 years ago

Dunno if is it a bug but when you are working with replications servers and work with multiple databases queries if you don't select the database it will only insert,update,delete into the master and bypass the slave, I think it its because it doesn't insert the sql on the binary log so the work around its to just call mysql_select_db
MYSQL : 5.0.51a-log
PHP: 5.2.6
Example:

Chủ Đề