評判が低いため、直接コメントすることはできません。したがって、これを2013年1月19日の15:58のRagenDazsの投稿への返信として想像してみてください。私はこのトピックが数日前であることを知っています、しかし私のような誰かがグーグル検索によってこれにつまずいたら...
ただし、最後から3行目の正規表現に問題がありました。この例でわかるように、式は時刻として00:00:00の時刻値にも一致します。したがって、この例の正規表現を使用することをお勧めします。
また、不要なパラメータがあるかどうかも知りたいと思いました。これが私が行った方法です。上記の例のようなSQLクエリとパラメータ配列が必要です(PDOStatement :: executeについてはphpドキュメントの例2を参照してください)。
/**
* Checks an parameter array against the sql query. it will tell you if there are any missing or needless parameters
*
* @param string $query Sql query
* @param array $parameters Parameters array
*
* @return bool|array Returns TRUE if no missing or needless parameters where found or a list with the missing
* or needless parameters
*/
private function checkParameters($query, $parameters)
{
$parameterTMP = $parameters;
$parameterCount = count($parameterTMP);
$regexMatchCounter = preg_match_all("/:[^]\\D\\w*/", $query, $regexMatches);
// if there are parameter in the $parameters array oder parameters in the sql query
if( $parameterCount > 0 || $regexMatchCounter > 0 )
{
// take every parameter found in the sql query
foreach( $regexMatches[ 0 ] as $parameterName )
{
// check if the required parameter is in the parameters array
if( !array_key_exists($parameterName, $parameters) )
{
// if it is not in the parameters array, add it to the list of missing parameters
// and continue with the next parameter from the query
$result[ 'missing' ][] = $parameterName;
continue;
}
// if the required parameter is in the parameter array, delete it from this array
// so we get a list of parameters that are needless
unset($parameterTMP[ $parameterName ]);
}
// check if there are (needless) parameters left
if( count($parameterTMP) > 0 )
{
// if so, add them to the list of needles parameters
$result[ 'needless' ] = array_keys($parameterTMP);
}
// if at this point $result is an array,
// some parameters are missing or needless, so we return the result list(s)
if( isset($result) && is_array($result) )
{
return $result;
}
}
// if we reach this point, no missing or needless parameters where found,
// you are good to go
return true;
}
何かが間違っている場合に例外をスローしたい場合は、「return$result;」を置き換えてください。次のコード行を使用します。
$missingCount = 0;
$missing = "";
$needlessCount = 0;
$needless = "";
if( array_key_exists('missing', $parameters) )
{
$missingCount = count($parameters[ 'missing' ]);
$missing = " (" . implode(", ", $parameters[ 'missing' ]) . ") ";
}
if( array_key_exists('needless', $parameters) )
{
$needlessCount = count($parameters[ 'needless' ]);
$needless = " (" . implode(", ", $parameters[ 'needless' ]) . ")";
}
$msg = "There are " . $missingCount . " missing parameter(s)".$missing." and ".$needlessCount." needless parameter(s)".$needless.".";
throw new Exception($msg);
楽しんで。