[英]Is there a better way to insert values to MySQL query than just VALUES($var1, $var2, $var3)?
I just have the array of 15 values that all need to be inserted into the table.我只有 15 个值的数组,所有这些值都需要插入到表中。 And I was just wondering if there is anything like this:
我只是想知道是否有这样的事情:
INSERT INTO table VALUES($myarrayofvalues)
Just curious, would be very useful.只是好奇,会很有用。
Update:更新:
Just one row with 15 columns.只有一行 15 列。
$query = "INSERT INTO table VALUES('" . implode("', '", $myarrayofvalues) . "')";
Edit :编辑:
If you haven't done your escaping yet, you can do that in a tiny loop before the above statement, something like:如果您还没有完成 escaping,您可以在上述语句之前的一个小循环中执行此操作,例如:
foreach($myarrayofvalues as $k=>$v)
$myarrayofvalues[$k] = mysql_real_escape_string($v);
While you can do what's show in the answer by Rick , it is open to SQL injection.虽然您可以执行Rick的答案中显示的内容,但它对 SQL 注入开放。
There is really no good way to do this without some kind of column mapping.如果没有某种列映射,确实没有什么好的方法可以做到这一点。 That is something to state element 1 is a string, element 2 is an integer.
那就是 state 元素 1 是一个字符串,元素 2 是一个 integer。
As such, I see two choices:因此,我看到两个选择:
Escape everything逃离一切
$values = array(); foreach ($myarrayofvalues as $value) { $column[].= "'". mysql_real_escape_string($value). "'"; } $sql = "INSERT INTO table VALUES(". implode(',', $values). ")";
Write the complete SQL statement写出完整的 SQL 语句
$sql = "INSERT INTO table (column1_string, column2_int, ...) VALUES ('". mysql_real_escape_string($myarray[0]). "', ". (int)$myarray[1]. ", ...)
I prefer #2 because it is more readable and less brittle.我更喜欢#2,因为它更具可读性且不那么脆弱。 Currently if your schema or array changes, your code breaks.
目前,如果您的架构或数组发生更改,您的代码就会中断。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.