问题描述
我有一部分代码应该采用以表格形式输入的数据,将其存储在数组中,然后将其输入数据库.我在$ fields和$ data上使用了var_dump,它们都返回在字段中输入的信息(在add_habbo函数中).因此,我遇到的问题是MYSQL/PDO代码没有将此数据插入数据库.
I've got a portion of code that is supposed to take the data entered in a form, store it in an array and then enter it into the database. I have used var_dump on $fields and $data and they are both returning the information entered in the field (in the add_habbo function). So the problem I've got is that the MYSQL/PDO code isn't inserting this data into the database.
这是我用来将它们插入数据库的代码:
This is the code that I am using to insert them into the database:
$fields = '`' . implode('`, `', array_keys($habbo_data)) . '`';
$data = '\'' . implode('\', \'', $habbo_data) . '\'';
var_dump($fields);
var_dump($data);
global $con;
$query = "INSERT INTO `personnel` (:fields) VALUES (:data)";
$result = $con->prepare($query);
$result->bindParam(':fields', $fields, PDO::PARAM_STR);
$result->bindParam(':data', $data, PDO::PARAM_STR);
$result->execute();
我的印象是,它与bindParam部分有关,可能与PDO :: PARAM_STR有关?感谢您的协助!
I get the impression it has something to with the bindParam sections, possibly PDO::PARAM_STR? Thanks for your assistance!
更新:
$fields = '`' . implode('`, `', array_keys($habbo_data)) . '`';
$fields_data = ':' . implode(', :', array_keys($habbo_data));
var_dump($fields);
var_dump($fields_data);
global $con;
$query = "INSERT INTO `personnel` (`rank`, `habbo_name`, `rating`, `asts`, `promotion_date`, `transfer_rank_received`, `cnl_trainings`, `rdc_grade`,
`medals`, `branch`) VALUES ({$fields_data})";
$result = $con->prepare($query);
$result->execute($habbo_data);
$arr = $result->errorInfo();
print_r($arr);
错误:
推荐答案
您不能这样做:
- 您需要分别添加每个变量/字段名称和值;
- 您只能绑定值,而不能绑定表名或字段名.
您必须直接将表名和字段名注入到sql中,以防止sql注入问题,在执行此操作之前,您需要先对它们进行白名单检查.
Table- and field-names you will have to inject directly into your sql so to prevent sql injection problems, you need to check them against a white-list before doing that.
因此,在您的情况下,将类似于(草稿):
So in your case that would be something like (rough draft):
// assuming all fields have been checked against a whitelist
// also assuming that the array keys of `$habbo_data` do not contain funny stuff like spaces, etc.
$fields = '`' . implode('`, `', array_keys($habbo_data)) . '`';
$fields_data = ':' . implode(', :', array_keys($habbo_data));
var_dump($fields);
var_dump($fields_data);
global $con;
$query = "INSERT INTO `personnel` ({$fields}) VALUES ({$fields_data})";
$result = $con->prepare($query);
$result->execute($habbo_data);
请注意,我不再手动绑定变量,而是直接将关联的$habbo_data
数组作为参数发送给execute
方法,请参见示例#2 .
Note that I am not manually binding the variables any more but sending the associative $habbo_data
array directly as a parameter to the execute
method, see example #2.
这篇关于INSERT阵列-PDO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!