Error with fetch_assoc, how do I correct? echo does not return desired value

Asked

Viewed 222 times

1

I have following code I’m learning:

$mysqli = new mysqli('localhost', 'root', '', 'mydb');
$sql = "SELECT * FROM ordem_producao WHERE op_id = $id;";
$query = $mysqli->query($sql);
$resultado = $query->fetch_assoc($sql);

in the body of my html I have:

<?php echo $resultado['id']; ?>

on the page appears following error

PHP Warning: mysqli_result::fetch_assoc() expects Exactly 0 Parameters, 1 Given in E: home pages view view_op.php on line 9

line 9 is the code

$resultado = $query->fetch_assoc($sql);

What am I doing wrong??

Thank you

2 answers

1


You do not need parameters in fetch_assoc()
You can do it like this:

$mysqli = new mysqli('localhost', 'root', '', 'mydb');
$sql = "SELECT * FROM times WHERE id = $id;";
$query = $mysqli->query($sql);
while($row = $query->fetch_assoc()) {
    echo "id: " . $row["id"]. " - Nome: " . $row["nome"]. "<br>";
}

Just remove the parameter of fetch_assoc()

  • Thanks I’ll test it here. Thanks a lot

  • So it works but what’s inside the htmi appears blank

  • In this case no row was selected. Check the table name, Where condition, and the fields it is displaying.

  • I understand I’m going to put parts here to see what might be going wrong.

1

To associate the entire query result, you must use the method fetch_all:

$mysqli = new mysqli('localhost', 'root', '', 'mydb');
$sql = "SELECT * FROM ordem_producao WHERE op_id = $id;";
$query = $mysqli->query($sql);


//Retorna o resultado da query em um array associativo
$resultado = $query->fetch_all(MYSQLI_ASSOC);

//Retorna o resultado da query em um array numérico
$resultado = $query->fetch_all(MYSQLI_NUM);

//Retorna o resultado da query em um array com ambos os tipos(associativo e numérico)
$resultado = $query->fetch_all(MYSQLI_BOTH);
  • Thanks for your help, I’ll test it here

Browser other questions tagged

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