0

I'm having a problem trying to print some data of a table. I'm new at this php mysql stuff but I think my code is right. Here it is:

<html> <body> <h1>Lista de usuários</h1> <?php $host="localhost"; // Host name $username="root"; // Mysql username $password=""; // Mysql password $db_name="sabs"; // Database name $tbl_name="doador"; // Table name // Connect to server and select database. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $sql="SELECT * FROM $tbl_name"; $result=mysql_query($sql); while($rows = mysql_fetch_array($result)){ echo $row['id'] . " " .$row['nome'] . " " . $row['sobrenome'] . " " . $row['email'] . " " . $row['login'] . " " . $row['senha'] . " " . $row['idade'] . " ". $row['peso'] . " " . $row['fuma'] . " " . $row['sexo'] . " " . $row['doencas']; echo "<BR/>"; } mysql_close(); ?> </body> </html> 

All columns of the echo command exist in my table in the database. Don't get why it's not printing those values.

2 Answers 2

3

You assigned the received data as $rows, but you are trying to ouput the variable $row, which doesn't exist.

Change it like this:

while($row = mysql_fetch_array($result)) 
Sign up to request clarification or add additional context in comments.

Comments

1

Let me give 2 advises

  1. To discover such a mistake in the future, always turn error reporting level at max by adding error_reporting(E_ALL); in your scripts. In this case PHP will tell you that $row variable diesn't exist.

  2. Consider dividing your scripts into 2 parts: getting data part and displaying data part

like this:

<?php error_reporting(E_ALL); $host="localhost"; // Host name $username="root"; // Mysql username $password=""; // Mysql password $db_name="sabs"; // Database name $tbl_name="doador"; // Table name // Connect to server and select database. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $sql="SELECT * FROM $tbl_name"; $result=mysql_query($sql) or trigger_error(mysql_error().$sql); while($row = mysql_fetch_array($result)){ $DATA = $row[]; } mysql_close(); ?> <html> <body> <h1>Lista de usuários</h1> <table> <? foreach($DATA as $row): ?> <tr> <td><?=$row['id']?></td> <td><?=$row['nome']?></td> <td><?=$row['sobrenome']?></td> <td><?=$row['email']?></td> <td><?=$row['login']?></td> <td><?=$row['senha']?></td> <td><?=$row['idade']?></td> <td><?=$row['peso']?></td> <td><?=$row['fuma']?></td> <td><?=$row['sexo']?></td> <td><?=$row['doencas']?></td> </tr> <? endforeach ?> </table> </body> </html> 

Html part can be put into separate file to ease of operating.
Also note the trigger_error function which will help you to detect SQL errors

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.