xxxxxxxxxx
function isSimpleValidQuery($query) {
// Allowed starting keywords
$allowedKeywords = ['SELECT', 'UPDATE', 'DELETE', 'INSERT'];
// Basic pattern for alphanumeric characters, underscores, spaces, and allowed keywords
$pattern = '/^(' . implode('|', $allowedKeywords) . ')\s+(?:(?:[a-zA-Z0-9_ ]+|' . implode('|', ['FROM', 'SET', 'WHERE']) . ')(?:\s+[a-zA-Z0-9_ ,=\.]+)*)+\s*;$/i';
return preg_match($pattern, $query);
}
xxxxxxxxxx
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 ;
}
}