我想构建一个 PHP 脚本来验证 SQL 查询,但不执行它。它不仅应该验证语法,而且应该在可能的情况下让您知道在给定查询中的命令的情况下是否可以执行查询。这是我希望它做的伪代码:
<?php
//connect user
//connect to database
//v_query = $_GET['usrinput'];
if(validate v_query == true){
echo "This query can be executed";
}
else{
echo "This query can't be executed because the table does not exist.";
}
//disconnect
?>
Run Code Online (Sandbox Code Playgroud)
像这样的东西。我希望它在不执行查询的情况下模拟查询。这就是我想要的,我在这方面找不到任何东西。
我们不希望执行查询的一个例子是查询是否向数据库添加了一些内容。我们只是想让它在不修改数据库的情况下模拟它。
任何链接或示例将不胜感激!
从 MySQL 5.6.3 开始,您可以对大多数查询使用 EXPLAIN
我做了这个,效果很好:
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 ;
for ( $p = 0 ; $p < strlen($str) ; $p++ ) {
switch ( $str[$p] ) {
case "'": if ( ! $inDoubleQuotes ) $inSingleQuote = ! $inSingleQuote ; break ;
case '"': if ( ! $inSingleQuote ) $inDoubleQuotes = ! $inDoubleQuotes ; break ;
case '\\': $p++ ; break ;
case $char: if ( $inSingleQuote || $inDoubleQuotes) $str[$p] = $placeholder ; break ;
}
}
return str_replace($placeholder, $repl, $str) ;
}
Run Code Online (Sandbox Code Playgroud)
如果 de 查询正常(允许多个 ; 分隔语句),它将返回 False ,或者如果存在语法或其他 MySQL 其他(如不存在的表或列),则返回错误消息说明错误。
已知错误: