简体   繁体   English

如何将PHP数组插入SQL数据库

[英]How to insert PHP array into SQL database

I'm trying to insert php array into sql database like this: 我试图将php数组插入sql数据库,如下所示:

$i=1    
$sql="INSERT INTO table(itemname) VALUES ('$_SESSION[someVariable][$i]')";

however, the name in the database is always Array[1] . 但是,数据库中的名称始终为Array[1] it is not the value contained in $_SESSION[someVariable][$i] 它不是$_SESSION[someVariable][$i]包含的值

I wonder if there is anyway to declare this? 我想知道是否还有声明这个? I know I'm messing up with the quotes 我知道我搞砸了报价

If you embed array items in a string, make sure to embrace them in curly braces: 如果在字符串中嵌入数组项,请确保在花括号中包含它们:

$sql="INSERT INTO table(itemname) VALUES ('{$_SESSION[$somevariable][$i]}')";

Alternatively, use string concatenation: 或者,使用字符串连接:

$sql="INSERT INTO table(itemname) VALUES ('" . $_SESSION[$somevariable][$i] . "')";

or a temporary variable: 或临时变量:

$itemname = $_SESSION[$somevariable][$i];
$sql="INSERT INTO table(itemname) VALUES ('$itemname')";

PS, I've replaced i1 with $somevariable . PS,我用$somevariable替换了i1 You've changed it to somevariable after the discussion in comments, but being a variable, it needs a $ , of course. 在评论讨论后你已经将它改为somevariable ,但作为一个变量,它当然需要一个$

You need curly brackets to use an array in a string: 你需要花括号来在字符串中使用数组:

$sql="INSERT INTO table(itemname) VALUES ('{$_SESSION[i1][$i]}')";

The reason you were getting Array[1] is because the array was being converted to a string Array and $i was 1. 你得到Array[1]的原因是因为数组被转换为字符串Array$i是1。

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

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