我需要在php中将数组值作为MYSQL表中的列插入。
$new_user = array(
"Nom" => $_POST['Nom'],
"EmailID" => $_POST['EmailID'],
"localité" => $_POST['localité']
);
$table = "memfis";
$columnNames = implode(", ", array_keys($new_user));
$columnPlaceholders = "'" . implode("', '", array_keys($new_user)) . "'";
$sqld = "INSERT INTO $table ($columnNames) VALUES ($columnPlaceholders);";
var_dump($sqld); exit;
$stmt = $pdo->prepare($sqld);
foreach ($columnNames as $name) {
$placeholder = "'" . $name;
$stmt->bindParam($placeholder, $new_user[$name]);
}
$connection->execute($sqld);
echo "New record created successfully";
它应该显示“成功添加了新行”,并且该行应该已经添加到表中。
答案 0 :(得分:1)
我用原始字段名称测试了以下内容-特别记录了e
上的重音符号,但失败了-当我删除重音符号并替换为标准字母e
时,它可以正常工作
<?php
/* PDO dbo */
$dbport = 3306;
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$options=array(
PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL,
PDO::ATTR_PERSISTENT => false,
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
PDO::ATTR_EMULATE_PREPARES => true,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'utf8mb4\' COLLATE \'utf8mb4_general_ci\', @@sql_mode = STRICT_ALL_TABLES, @@foreign_key_checks = 1'
);
$dsn = 'mysql:host='.$dbhost.';port='.$dbport.';dbname='.$dbname.';charset=UTF8';
$db = new PDO( $dsn, $dbuser, $dbpwd, $options );
/* Emulate POST form submission */
$_POST=[
'Nom' => 'fred flintstone',
'EmailID' => 'fred@bedrock.com',
'localite' => 'Bedrock'
];
$table='memfis';
/* prepare field names */
$fields = sprintf( '`%s`', implode( '`,`', array_keys( $_POST ) ) );
/* placeholder arrays */
$args = [];
$vals = [];
/* create placeholder variable names */
foreach( $_POST as $field => $value ) {
$args[]=sprintf( ':%s', strtolower( $field ) );
$vals[ sprintf( ':%s', strtolower( $field ) ) ]=$value;
}
/* create the sql statement */
$sql=sprintf(
'insert into `%s` ( %s ) values ( %s );',
$table,
$fields,
implode( ', ', $args )
);
$stmt = $db->prepare( $sql );
if( $stmt ){
# debug info
printf("<pre>%s\n%s</pre>", $sql, print_r( $vals, true ) );
# execute the statement
$res=$stmt->execute( $vals );
# did it or did it not work?
if( $res ){
echo "OK!";
} else {
echo "Bogus!";
}
}
?>
输出到以上屏幕的结果是:
insert into `memfis` ( `Nom`,`EmailID`,`localite` ) values ( :nom, :emailid, :localite );
Array
(
[:nom] => fred flintstone
[:emailid] => fred@bedrock.com
[:localite] => Bedrock
)
OK!
使用原始字段名localité
时,会发生以下错误:
警告:PDOStatement :: execute()[pdostatement.execute.html]: SQLSTATE [HY093]:参数号无效:参数未定义 在.....