Catch all values from the database [closed]

0

Could someone help me figure out the error:

<?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 get the values from the bank and print them, I tried using fetchAll, but I did not succeed either.

    
asked by anonymous 13.01.2018 / 15:46

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 you have to be careful because fetch_all works from PHP >= 5.3 .

But honestly, your code does not need prepare ( because in this case it is useless , use when you need to prepare parses for this SQL , ie its SQL it does not have and does not need to), with query and its return with the fetch_assoc method, is simpler and easier to manipulate in this SQL without 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'];
        }
    }
    
13.01.2018 / 16:02