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...

3 Answers 3

2

You can achieve your desired result this way:

$result = array();
while ($row=$res->fetch_assoc()) {
    $result[] = $row['titre'];
} 
var_dump($result);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

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.