我正在尝试使用预处理语句创建一个简单的创建函数,但PHP今天不喜欢我。
function prepared_create ( $db, $table, $values, $columns = null ) {
// Exit if database, table of values are undefined
if ( !isset ( $db, $table, $values ) ) { return 'Prepared Create: Insufficient parameters'; }
if ( isset ( $columns ) ) {
$statement = $db->prepare("insert into $table ( $columns ) values ( :values )");
$statement->execute( array ( ':values' => $values ) );
} else {
$statement = $db->prepare("insert into $table values ( :values )");
$statement->execute( array ( ':values' => $values ) );
}
}
然后我执行:
print_r ( prepared_create ( $db, 'php_keyvalue', '"hello", "sir"' ) );
我受到了欢迎:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1' in /var/www/public/php-database-skeleton/connect-database.php:96 Stack trace: #0 /var/www/public/php-database-skeleton/connect-database.php(96): PDOStatement->execute(Array) #1 /var/www/public/php-database-skeleton/index.php(20): prepared_create(Object(PDO), 'php_keyvalue', '"hello", "sir"') #2 {main} thrown in /var/www/public/php-database-skeleton/connect-database.php on line 96
我尝试了很多东西:
事情是,当我手动执行相同的查询时:
insert into php_keyvalue values ( "Hello", "Sir" );
我得到了:
Query OK, 1 row affected (0.01 sec)
导致:
mysql> select * from php_keyvalue;
+-------------+---------+
| keyname | value |
+-------------+---------+
| first entry | correct |
| entered | mentor |
| entered | mentor |
| Hello | Sir |
+-------------+---------+
4 rows in set (0.00 sec)