2

I currently have this code:

$res= $mysqli->query("SELECT titre FROM Bibliographie WHERE Nom_Auteur LIKE '%$auteur%'"); 

while ($row=$res->fetch_assoc()) {
    var_dump($row);
} 

The outcome is:

array(1) {
    ["titre"]=>
    string(65) "Le droit privé dans les Pays-Bas méridionaux du 12e au 18e siècle"
}
 array(1) {
    ["titre"]=>
    string(41) "Le droit foncier à Bruxelles au moyen-âge"  
} 
array(1) {
    ["titre"]=>
    string(78) "Les sûretés personnelles dans les Pays-Bas méridionaux du XIe au XVIIIe siècle"
}
array(1) {
    ["titre"]=>
    string(44) "Chartes du chapitre de St-Gudule à Bruxelles"
}

But I want the outcome to be:

[0] => "Le droit privé dans les Pays-Bas méridionaux du 12e au 18e siècle"
[1] => "Le droit foncier à Bruxelles au moyen-âge"
[2] => "Chartes du chapitre de St-Gudule à Bruxelles"

I can't get my head around this and need some help obtaining this simple outcome...

Bhavesh G
  • 3,000
  • 4
  • 39
  • 66
thiebo
  • 1,339
  • 1
  • 17
  • 37

3 Answers3

2

You can achieve your desired result this way:

$result = array();
while ($row=$res->fetch_assoc()) {
    $result[] = $row['titre'];
} 
var_dump($result);
Gerald Schneider
  • 17,416
  • 9
  • 60
  • 78
1

You have various options to do this,

1) You can use fetch_all() method instead of fetch_assoc() to get all data in one variable at once and then you can flattern the array using this function.

$res= $mysqli->query("SELECT titre FROM Bibliographie WHERE Nom_Auteur LIKE '%$auteur%'"); 
$result = array_map(function($ary) {return $ary['titre'];}, $res->fetch_all());
// Just two lines of code. No big deal

2) As Gerald Schneider suggested,

$res= $mysqli->query("SELECT titre FROM Bibliographie WHERE Nom_Auteur LIKE '%$auteur%'"); 

$result = array();
while ($row=$res->fetch_assoc()) {
     $result[] = $row['titre'];
} 
var_dump($result);
// simple and easy to understand
Bhavesh G
  • 3,000
  • 4
  • 39
  • 66
0

Try using while ($row=$res->fetch_array()){var_dump($row);} instead. See Mysqli fetch_assoc vs fetch_array

Community
  • 1
  • 1
Ben Marshall
  • 1,724
  • 2
  • 17
  • 33