PHP code example of xp-forge / sql-parser

1. Go to this page and download the library: Download xp-forge/sql-parser library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

xp-forge / sql-parser example snippets


use text\sql\{Parser, SyntaxError};

$p= new Parser();
try {
  $statement= $p->parse('select * from user where user_id = 1');
} catch (SyntaxError $e) {
  // Handle
}

// new Select(
//   [new All()],
//   [new Table('user')],
//   new Comparison(new Field(null, 'uid'), '=', new Number(1))
// )

use text\sql\Parser;

$p= new Parser();

// Incomplete implementation of https://dev.mysql.com/doc/refman/8.0/en/show.html
$p->extend('show', function($parse, $token) {
  return ['show' => $parse->match([
    'events'    => function($parse, $token) { return 'events'; },
    'variables' => function($parse, $token) {
      if ('like' === $parse->token->symbol->id) {
        $parse->forward();
        return ['variables' => $parse->expression()];
      } else {
        return ['variables' => null];
      }
    }
  ])];
});

$statement= $p->parse('show variables like "sql_mode"');

// ['show' => ['variables' => new Text('sql_mode')]]