php - Format array from sql query result

452

I have the following query

$sql = "SELECT nomInteretUser from userInteret where idUser='$id_user' ";
$result = $conn->query(sprintf($sql));

I want to produce an array with following structure:array ('User1','User2')

I have tried this :

if ($result->num_rows != 0) {
    $rows=array(); 
    while($r=mysqli_fetch_assoc($result))
    { 
        $rows[]=$r;
    } 
}

But it gives following result:

{
   array(1) {
       ["nomInteretUser"]=> "foot"
   }
   array(1) {
       ["nomInteretUser"]=> "cyclisme"
   }
}
269

Answer

Solution:

use$rows[]=$r['nomInteretUser']; in your code than you get the right result. :)

if ($result->num_rows != 0) {
    $rows=array(); 
    while($r=mysqli_fetch_assoc($result))
    { 
        $rows[]=$r['nomInteretUser'];
    } 
}
11

Answer

Solution:

Simply update your code to :

if($result)
{           
   if ($result->num_rows != 0) {

      $rows=array(); 

      while($r=mysqli_fetch_assoc($result))
      { 
         $rows[]=$r["nomInteretUser"];
      } 
   }
 }
824

Answer

Solution:

You can do this 2 ways:

  1. Please update your current code like this

    while($r=mysqli_fetch_assoc($result))
    { 
        $rows[]=$r['nomInteretUser'];  //Update here
    }
    
  2. If you don't want to update your current code then modify code, then use array_column() (>= PHP 5.5 Required)

    $rows = array_column($rows, 'nomInteretUser');

Hope it helps!

892

Answer

Solution:

Please replace your code with

if ($result->num_rows != 0) {
$rows=array();
$i = 0;
while($r=mysqli_fetch_assoc($result))
{ 
    $rows[$i]=$r;
    $i++;
} 
}

People are also looking for solutions to the problem: php - I’m screwing up this LEFT JOIN

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.