Print table data mysql php

一个人想着一个人 提交于 2019-12-20 05:49:11

问题


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.


回答1:


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))



回答2:


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



来源:https://stackoverflow.com/questions/3013825/print-table-data-mysql-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!