Forum Moderators: coopster

Message Too Old, No Replies

array into new query

         

mschultem

3:16 pm on Mar 28, 2007 (gmt 0)

10+ Year Member



hi,
i am trying to do two queries from different databases.
in $array the relevant ids (userid) are stored successfully. now i try to use the values from $array in a new query (in another db):


foreach ($array as $value) {
$query="SELECT * FROM table WHERE subject=". $value['userid']";
$result=mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
echo $row; }
}

with the above code i get the following error message:
mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource

anybody an idea of how i can get around this?
thanks
m

dreamcatcher

3:27 pm on Mar 28, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi mschultem,

Firstly, always debug your queries like this:

$result=mysql_query($query) or die(mysql_error());

Secondly, in your foreach loop, $value is set as your variable, so should be:

$query="SELECT * FROM table WHERE subject="$value";

dc

mschultem

3:38 pm on Mar 28, 2007 (gmt 0)

10+ Year Member



hi,
thanks for the debug tip.

however if i change to $value only 'array' is used in the new query - with the code i posted the queries were generated but the second fetch_assoc seems to have a problem ...

using this:

foreach ($array as $value) {
$query="SELECT * FROM .... WHERE subject='".$value['userid']."'";
echo $query;

$result=mysql_query($query) or die(mysql_error());

while ($row = mysql_fetch_assoc($result)) {
echo $row;

i get:
SELECT * FROM mlweb WHERE subject='...' VERY LONG LIST OF IP Adresses * FROM mlweb WHERE

m

dreamcatcher

8:10 pm on Mar 28, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



How are you populating $array?

dc

mschultem

4:32 pm on Mar 29, 2007 (gmt 0)

10+ Year Member



$array is populated through another query:

while ($row = mysql_fetch_assoc($result)) {
$array[] = $row; }

dreamcatcher

4:38 pm on Mar 29, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



$row is an array too. If you echo this you`ll see 'array' So, for each loop you are assigning the same value, which in this case will always be 'array'.

Try using your column names when populating the array:

while ($row = mysql_fetch_assoc($result)) {
$array[] = $row['field']; }

dc

panos

11:46 am on Mar 31, 2007 (gmt 0)

10+ Year Member



Just a small tip:

using your code if the array has x elements you will be making x queries to the database.

For example for an array with 1000 elements 1000 queries will be executed.

Try this:

$string=implode(",",$array);
$query=mysql_query("SELECT * FROM table WHERE subject IN ($string)");