Fill array with database values

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
User avatar
waradmin
Forum Contributor
Posts: 240
Joined: Fri Nov 04, 2005 2:57 pm

Fill array with database values

Post by waradmin »

I am using some ajax do automaticly offer suggestions on search terms as people type in their desired words. So I want the array ($a[]="";) to be populated with values from a database. Here is the code with the query, what would I need to add to assign the table row Fname and Lname to the array, so when people search $a[] will = $row['Fname'] then a space, then $row['Lname'].

Example: User types in "Ste" and that will offer suggestions Steve Jones AND Steve Hanson (so the first name that matches the letters, AND the last name. The code is there, just need to assign $a[] with Fname *space* Lname

Code: Select all

<?php
include('inc.php');
$result = mysql_query("SELECT * FROM loginphp") or die(mysql_error()); //query on the loginphp table where Fname and Lname are held
$row = mysql_fetch_array( $result ); //assigns $row
// Fill up array with names

$a[]="Steve"; //I want these to be set as $row['Fname'] $row['Lname'] so then they can do full name finds.
$a[]="Bob"; //Another example of the code... but again this needs to update from the DB.

//get the q parameter from URL
$q=$_GET["q"];

//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
  $hint="";
  for($i=0; $i<count($a); $i++)
  {
  if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
    {
    if ($hint=="")
      {
      $hint=$a[$i];
      }
    else
      {
      $hint=$hint." , ".$a[$i];
      }
    }
  }
}

// Set output to "no suggestion" if no hint where found
// or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}

//output the response
echo $response;
?>
Thanks in advance, I did do some reading but came up with nothing.
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

loop over your result array rather than just setting $row to it.

ie

Code: Select all

while($row = mysql_fetch_assoc($result))
{
  $a[] = $row['fname'];
}
Post Reply