weeo
weeo

Reputation: 2799

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

Upvotes: 2

Views: 769

Answers (2)

GolezTrol
GolezTrol

Reputation: 116110

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.

Upvotes: 7

wogsland
wogsland

Reputation: 9508

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.

Upvotes: 3

Related Questions