0

The question in simple.

What i have and what's the problem?
I do have two dimensional array $someArray[][]. The first bracket i could put "subject" or "date". The second one, goes from 1 to 4 (just an example - $someArray['date'][0])

Now when i try to get some data from database with mysql_query() i have some problems. I am trying to use this two dimensional array in WHERE part in query.

Examples what works and what doesn't
$result = mysql_query("SELECT some from table where date='$someArray[date][0]' AND subject='$someArray[subject][0]') or die(mysql_error());

When i use this, it doesn't return me anything. But when i first assing those values to new variables:

$variable1 = $someArray['date'][0];
$variable2 = $someArray['subject'][0];

and then use them in query

`$result = mysql_query("SELECT some from table where date='$variable1' AND subject='$variable2') or die(mysql_error());

It works like a charm.

Question
Whats wrong with my first query, am I writing those arrays wrong? I get no errors.
Tried to put single apostrophes inside [] brackets in mysql query, but then i do get errors. Also it works without them if i use array like: $someotherArray[somedata] in query.

1
  • 1
    Please change your code not to use mysql_ functions anymore. That is deprecated functionality in PHP and will be removed. Look at red block on php.net/manual/en/function.mysql-query.php. Change to mysqli or PDO for safety Commented Feb 4, 2013 at 22:42

2 Answers 2

2

Array interpolation only works for a single level of subscripting. For multidimensional arrays, you need to use {...} wrappers:

$result = mysql_query("SELECT some from table where date='{$someArray['date'][0]}' AND subject='{$someArray['subject'][0]}') or die(mysql_error());
Sign up to request clarification or add additional context in comments.

Comments

2

The syntax in the query is lacking a closing double quote. And concat the string in stead of just adding it within. The string parser doesn't like arrays, multi dimensional.

Solution:

$result = mysql_query("SELECT some from table where date='".$someArray[date][0]."' AND subject='".$someArray[subject][0]."'") or die(mysql_error());

And like @barmar mentioned brackets also work

On a side note, make sure you escape the data to make sure SQL injection is prevented!

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.