经过无休止的测试不同方面,我已经确定PDO连接有效(我可以运行一个简单的查询并显示结果),我已经确定该语句已成功准备,并且值正确绑定.由于某种原因,该语句将不会执行.只是为了可爱,我已经尝试删除所有绑定变量并执行静态查询,这也无济于事.
码:
$dbh = new PDO( "mysql:host=localhost;dbname=".$GLOBALS['data_name'], $GLOBALS['data_user'], $GLOBALS['data_pass'] );
$dbh->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$sth = $dbh->prepare( "SELECT * FROM :table WHERE :field = :value" );
if( $sth != false ) TCDebug( 'prepared' );
if( $sth->bindValue( ":table", $table ) ) TCDebug( "table true" );
if( $sth->bindValue( ":field", $field ) ) TCDebug( "field true" );
if( $sth->bindValue( ":value", $value ) ) TCDebug( "value true" );
$flag = $sth->execute();
if( $flag === true ) {
TCDebug( 'flag = true' );
} else if( $flag === false ) {
TCDebug( 'flag = false' );
}
$result = $sth->fetchAll();
foreach( $result as $c ) TCDebugArr( $c );
TCDebug( count( $result ) );
if( count( $result ) > 0 ) {
return $result;
} else {
return null;
}
一致地回声调试’prepared”table true”字段true”value true”flag = false’告诉我准备和绑定工作,但执行没有,$result为空,函数返回null.
我可能忽略了一些非常明显的东西,而且我已经完全准备好让我的头完全羞愧了.先感谢您…
UPDATE
啊,连接 – 我今天的朋友.工作代码如下:
$dbh = new PDO( "mysql:host=localhost;dbname=".$GLOBALS['data_name'], $GLOBALS['data_user'], $GLOBALS['data_pass'] );
$dbh->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$prepare_str = "SELECT * FROM ". $table ." WHERE ". $field ." = :value";
$sth = $dbh->prepare( $prepare_str );
if( $sth != false ) TCDebug( 'prepared' );
if( $sth->bindValue( ":value", $value ) ) TCDebug( "value true" );
$flag = $sth->execute();
if( $flag === true ) {
TCDebug( 'flag = true' );
} else if( $flag === false ) {
TCDebug( 'flag = false' );
}
$result = $sth->fetchAll();
foreach( $result as $c ) TCDebugArr( $c );
TCDebug( count( $result ) );
if( count( $result ) > 0 ) {
return $result;
} else {
return null;
}
在这种情况下这是安全的,因为$table和$field是系统生成的,并且无法通过用户输入访问;只暴露$value.
谢谢*!你是我的最爱!