简体   繁体   English

使用具有不同数据类型的array_implode的数组mysql插入

[英]Array mysql insert using array_implode with different datatype

Hi i been trying to inserting array's into MySql database 嗨,我一直试图将数组的插入MySql数据库

The problem i am having is that i have different datatypes and sometime data can be a 0 value, having () curly brackets, percentage value with % sign. 我遇到的问题是我有不同的数据类型,有时数据可以是0值,带有()大括号,带有%符号的百分比值。 I would like to know a way use some already built php function that can deal with this issues. 我想知道一种使用一些已经构建的php函数来处理此问题的方法。

So here is what i have done so far: 所以这是我到目前为止所做的:

$t = array('country_code' => $data->country_code,   
           'Name' => $data->Name,
           'money' => $data->money,
           'chanceToDie' => $data->death,
           'age' => $cb->age)

/*  FORMAT EXAMPLE
    country_code = Africa (AF)
    name = jack
    chanceToDie = 5.5
    age = 62
*/

$columns = implode(", ",array_keys($t));

//Tried
$values = implode(", ",array_values($t));           //Dont work
$values = "'".implode("', '",array_values($t))."'";     //Dont work

$sql = "INSERT INTO table ($columns) VALUES ($values)";

You need to quote each individual value and use array_values() instead of array_keys() : 您需要引用每个单独的值,并使用array_values()而不是array_keys()

$values = '"' . implode('", "', array_values($t)) . '"';

However , this leaves you with an sql injection problem so you should really use a prepared statement. 但是 ,这给您带来了sql注入问题,因此您实际上应该使用准备好的语句。

In PDO you could use something like (assuming you control the keys and they are safe to use): 在PDO中,您可以使用类似的命令(假设您控制密钥并且可以安全使用):

$values = ':' . implode(', :', array_keys($t));
// generates: ... VALUES(:country_code, :Name, :money,  // etc

Now you can prepare and execute your query using the array to bind the values to the placeholders. 现在,您可以使用数组准备并执行查询,以将值绑定到占位符。 See for example http://php.net/manual/en/pdo.prepared-statements.php (the 6th example). 参见例如http://php.net/manual/en/pdo.prepared-statements.php (第6个示例)。

Try to use the advantage of PDO prepared queries - it is more safe and convinient. 尝试利用PDO准备的查询的优势-更安全,更方便。

Your code may look like this: 您的代码可能如下所示:

$col_names = array_keys($t);
// filter column names before inserting to sql to prevent sql injection
array_filter($col_names, function($v){return preg_relace("@\W@", "_", $v);});
// generate placeholders list: ?,?,?,?
$placeholders = implode(',', array_fill(0, count(t), "?"));
$values = array_values($t);

$q = $pdo->prepare('insert into (' . implode(",", $col_names) . ') values (' . $placeholders . ')');
$q->execute($values);

PDO will deal with data types and correctly replace every placeholder with the corresponding value. PDO将处理数据类型,并用相应的值正确替换每个占位符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM