简体   繁体   中英

How to put two dimensional array into mysql_query in php

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.

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!

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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