问题描述:

I have created a simple MYSQL database to store user information (id, FirstName, LastName)

and filled it with 3 names:

id | FirstName | LastName

1 | Sam | Heyman

2 | Ben | Eliott

3 | Al | Readman

When I try and display the contents of the database in a table on my page, I get the correct number of rows but the cells are void.

User id | First Name | Last Name

| |

| |

| |

If I do

var_dump($rows)

I get the following:

array(6) { [0]=> string(1) "1" ["id"]=> string(1) "1" [1]=> string(3) "Sam" ["FirstName"]=> string(3) "Sam" [2]=> string(6) "Heyman" ["LastName"]=> string(6) "Heyman" }

array(6) { [0]=> string(1) "2" ["id"]=> string(1) "2" [1]=> string(3) "Ben" ["FirstName"]=> string(3) "Ben" [2]=> string(6) "Eliott" ["LastName"]=> string(6) "Eliott" }

array(6) { [0]=> string(1) "3" ["id"]=> string(1) "3" [1]=> string(8) "Alastair" ["FirstName"]=> string(8) "Alastair" [2]=> string(7) "Readman" ["LastName"]=> string(7) "Readman" }

So why are my cells empty? I have done many databases before and have never had this problem before. Having spent 3 hrs looking on google, I've given up.

This is the code:

<?php

// Connect to server and select database.

$dbcnx = @mysql_connect('server','user','pw');

mysql_query('SET NAMES utf8;');

mysql_select_db('db', $dbcnx);

// Fetch all the users from the database

$users = @mysql_query('SELECT * FROM registered_users');

?>

<table width="400" border="1" cellspacing="0" cellpadding="3" style="color:red;">

<tr>

<th>User ID</th>

<th>First name</th>

<th>Last name</th>

</tr>

<?php

// Start looping through the rows in mysql database.

while($rows=mysql_fetch_array($users)){

var_dump($rows);

echo"<br />";

?>

<tr>

<td><? echo $rows['id']; ?></td>

<td><? echo $rows['FirstName']; ?></td>

<td><? echo $rows['LastName']; ?></td>

</tr>

<?php

// close while loop

}

?>

</table>

<?php

// close MySQL connection

mysql_close();

?>

网友答案:

Change

<td><? echo $rows['id']; ?></td>
<td><? echo $rows['FirstName']; ?></td>
<td><? echo $rows['LastName']; ?></td>

to either

<td><?php echo $rows['id']; ?></td>
<td><?php echo $rows['FirstName']; ?></td>
<td><?php echo $rows['LastName']; ?></td>

or

<td><?= $rows['id']; ?></td>
<td><?= $rows['FirstName']; ?></td>
<td><?= $rows['LastName']; ?></td>
相关阅读:
Top