Jump to content

[SOLVED] Hand coded array VS. mysql_fetch_array


suttercain

Recommended Posts

Hi guys,

 

I am having a heck of a time with a function and need some help.

 

Let's say I have CODE A:

$aUsers = array(
	"Ädams, Egbert",
	"Altman, Alisha",
	"Archibald, Janna",
	"Auman, Cody",
	"Bagley, Sheree",
	"Ballou, Wilmot",
	"Bard, Cassian",
	"Bash, Latanya");

 

Then there is CODE B:

require('get_connected.php'); //Connect to the database
$sql=mysql_query("SELECT first_name FROM canada WHERE first_name LIKE('" .$_GET['input']. "%') ORDER BY first_name");
$aUsers = mysql_fetch_array($sql);

 

Now that you have had a look at the two separate code examples I'll explain. I am using CODE A for an autocomplete box. It works fine. If I type in A it displays all the names in that array that start with an A.

 

Now let's say I replace CODE A with CODE B so I can run an auto complete from the database. If I type in A it only shows the first name that starts with an A and none of the others. I tried using a while loop and a for loop with no luck.

 

How can I get CODE B to act exactly like CODE A?

 

Thanks for any advice or help.

 

SC

the mysql_fetch_array function only returns the first result row as an array, not the whole result set, so in effect all you are retrieving is:

 

$aUsers = array ("Ädams, Egbert");

 

you need to set up an array variable and then loop through the result set adding each of the rows to it one at a time like this ..

 

$aUsers = array();
while($row = mysql_fetch_array($sql)) {
    $aUsers[] = $row[0];
}

How can I get CODE B to act exactly like CODE A?

 

mysql_fetch_array fetches 1 row at a time with each element representing a field in your database. To create the same $aUsers array you would need something like...

 

<?php

 require('get_connected.php');
 if ($result = mysql_query("SELECT first_name,last_name FROM canada WHERE first_name LIKE('" .$_GET['input']. "%') ORDER BY first_name")) {
   if (mysql_num_rows($result)) {
     while ($row = mysql_fetch_assoc($result)) {
       $aUsers[] = $row['last_name'] . ", " . $row['first_name'];
     }
   }
 }

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.