2

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

7
  • What do you mean with i1? That is invalid syntax. You mean 'i1' or $i1 or something else? Commented Jan 10, 2016 at 22:34
  • @trincot i1 is a valid array key Commented Jan 10, 2016 at 22:36
  • Not unless it is defined as a constant. Commented Jan 10, 2016 at 22:38
  • $array['i1']='fish';echo $array['i1']; =fish Commented Jan 10, 2016 at 22:38
  • Yes, but you put quotes. I don't see those in the question. That is why I asked. OK, I get it, it is the syntax where the quotes are around the whole expression. My bad. Commented Jan 10, 2016 at 22:39

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! The curly braces are what I'm missing!
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.