Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert PHP array into SQL database

I'm trying to insert php array into sql database like this:

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

however, the name in the database is always Array[1]. it is not the value contained in $_SESSION[someVariable][$i]

I wonder if there is anyway to declare this? I know I'm messing up with the quotes

like image 476
weeo Avatar asked Jul 18 '26 10:07

weeo


1 Answers

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. You've changed it to somevariable after the discussion in comments, but being a variable, it needs a $, of course.

like image 150
GolezTrol Avatar answered Jul 20 '26 23:07

GolezTrol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!