Babu
Babu

Reputation: 455

How to store while loop result to array using php

I have a mysql query which is return matching data from db. I need to store matching results data to $autocompletiondata like that :

$autocompletiondata =  array(
        1 => "shibbir",
        2 => "ahmed",
        3 => "babu",
        4 => "rahim",
        5 => "shakil",
);

Sql query :

$sql = mysqli_query($link, "SELECT cdid, family_name FROM contact_details WHERE     
family_name LIKE '%$term' ");

while($res = mysqli_fetch_array($sql)){
    $cdid = $res['cdid'];
    $fname = $res['family_name'];    
    $autocompletiondata =  array(
        $cdid => "$fname");
}

How can I store all matching data to associative array ? Plz help.

Upvotes: 0

Views: 252

Answers (5)

AuZu
AuZu

Reputation: 90

Just set data to $autocompletiondata:

$autocompletiondata = array();
while($res = mysqli_fetch_array($sql)){
    $cdid = $res['cdid'];
    $fname = $res['family_name'];    
    $autocompletiondata [$cdid] = $fname;
}

Upvotes: 0

Utkarsh Dixit
Utkarsh Dixit

Reputation: 4275

Its simple just use the code below

$autocompletiondata =  array();
$sql = mysqli_query($link, "SELECT cdid, family_name FROM contact_details WHERE     
family_name LIKE '%$term' ");

while($res = mysqli_fetch_array($sql)){
    $cdid = $res['cdid'];
    $fname = $res['family_name'];    
    $autocompletiondata[$cdid] = $fname;
}

Hope this helps you

Upvotes: 0

rasso
rasso

Reputation: 2221

Try this

$sql = mysqli_query($link, "SELECT cdid, family_name FROM contact_details WHERE     
family_name LIKE '%$term' ");

while($res = mysqli_fetch_array($sql)){
    $cdid = $res['cdid'];
    $fname = $res['family_name'];    
    $autocompletiondata[$cdid] = $fname;
}

And print the array with

print_r($autocompletiondata);

Upvotes: 0

Lepanto
Lepanto

Reputation: 1413

while($res = mysqli_fetch_array($sql)){
  $cdid = $res['cdid'];
  $fname = $res['family_name'];    
  $autocompletiondata[$cdid] = $fname; // <== make this change to your code
}

Upvotes: 0

Minh Quy
Minh Quy

Reputation: 665

Can you try this?

$autocompletiondata = array();

while($res = mysqli_fetch_array($sql)){
    $cdid = $res['cdid'];
    $fname = $res['family_name'];    
    $autocompletiondata[$cdid] =  $fname;
}

Upvotes: 3

Related Questions