SQL + php array result

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mhonnphp
Forum Commoner
Posts: 37
Joined: Fri Oct 12, 2007 11:29 pm
Location: Philippines
Contact:

SQL + php array result

Post by mhonnphp »

I encounter a big query with 2 sub queries in my maintaining project.
I want to remove this sub queries, is it possible to do something like this :

Code: Select all

function subquery(){
   $sql = 'SELECT * FROM Table2';
   $result = mysql_query($sql);
   while($row = db_fetch_array($result)){
       $rows[0] = $row[0];
   }
   return $rows;
}

$sql = 'SELECT Table1.*, sub1.* FROM Table1,( ' . subquery()  . ' )sub1 
           WHERE sub1.field1 = 1 
           AND Table1.field1 = sub1.field1' ;
$result = mysql_query($sql);
...
I tried it but getting error because mysql can't read php array.
If possible, code patern is really appreciated.

Thanks
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: SQL + php array result

Post by Apollo »

I use something like this:

Code: Select all

function query_array($sql)
{
	$rc = mysql_query($sql);
	while ($row=mysql_fetch_assoc($rc)) $rows[]=$row;
	return $rows;
}
Gives the selected rows as associative arrays, with the field names as indices. For example a print_r dump would give:

Array (
  [0] => Array ( [firstname] => John [lastname] => Doe )
  [1] => Array ( [firstname] => Justin [lastname] => Bieber )
)
Post Reply