Grab all valuables from the database

Asked

Viewed 208 times

0

Could someone help me figure out the mistake:

<?php
$mysqli = new mysqli("localhost", "user", 
"senha", "dbname");

if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$sth = $mysqli->prepare("SELECT * FROM clientes");
$sth->execute();
$result = $sth->fetchAll();

foreach($result as $item){
 echo $item->id;
}

I wanted to take the bank’s values and print them, tried using fetchAll, but I couldn’t even succeed.

  • Just so we’re clear, there’s no fetchAll() as a method, in which case the use of prepare (is not wrong, but, is unnecessary, useless), until there is the fetch_all but then the syntax is different, the ideal is how I answered, the given answer is more coherent to what needs.

  • Bestfastfire, follow the official PHP manual with the method fetch_all() of mysqli to see the correct syntax: https://php.net/manual/en/mysqli-result.fetch-all.php

1 answer

1


Your initial code has typing problems and also lacks commands to work, a basic example of your code is:

<?php

    $mysqli = new mysqli("localhost", "root", "senha", "dbname");


    if (mysqli_connect_errno()) 
    {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    $sth = $mysqli->prepare("SELECT * FROM clientes");  
    $sth->execute();
    $result = $sth->get_result();   

    $items = $result->fetch_all(MYSQLI_ASSOC);
    foreach ($items as $row) 
    {
        echo $row['id'];
        echo '<br>';
    }

and has to be careful because, the fetch_all function from the PHP >= 5.3.

But, sincerity your code doesn’t need prepare (because then it’s useless, use when you need to prepare vestments for this SQL, that is, its SQL has not and does not need), with the query and their return with the method fetch_assoc, is simpler and easier to manipulate in this SQL no parameter, a functional example with another form:

<?php

    $mysqli = new mysqli("localhost", "user", "senha", "dbname");

    if (mysqli_connect_errno()) 
    {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    if ($sth = $mysqli->query("SELECT * FROM clientes"))
    {
        while ($row = $sth->fetch_assoc()) 
        {
            echo $row['id'];
        }
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.