views:

78

answers:

2

Hi people, 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.

Thanks for the attention.

+2  A: 

You assigned the received data as $rows, but you are trying to oupput the vaeriable $row, which doesnt exist,

change this way

while($row = mysql_fetch_array($result))
marvin
A: 

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

Col. Shrapnel