Run query without foreach

Asked

Viewed 64 times

1

As I do to execute this code without foreach,it is completely empty and is only serving to give value to the attributes, so it is not listing anything, and I wanted to make the code cleaner and clean, so I wanted to know how to run the line $con->query($sql, PDO::FETCH_ASSOC) as $row" without needing the foreach.

$con = new PDO("mysql:host=localhost; dbname=estagio;charset=utf8", "root", "");
$sql = "SELECT * FROM clientes WHERE id_cliente = '$_SESSION[id]'";
foreach($con->query($sql, PDO::FETCH_ASSOC) as $row){
}

1 answer

1


Would that be:

$var = $con->query($sql, PDO::FETCH_ASSOC);
print_r($var);

But if you have more than 1 record, will only bring the last.

The repetition serves to read line by line, and go storing in the variable that will later be used. So if you don’t do it this way, it will override your variable (in this case $var).

Browser other questions tagged

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