1

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"
   }
}
1
  • 2
    Did you try $rows[]=$r["nomInteretUser"] ? Commented May 18, 2016 at 11:15

3 Answers 3

2

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'];
    } 
}
Sign up to request clarification or add additional context in comments.

Comments

1

Simply update your code to :

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

      $rows=array(); 

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

Comments

1

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.