返回每行新div中的mysql数据

时间:2013-07-31 18:56:00

标签: php mysql

我创建了以下内容,但它没有正确显示数据,我希望数据库中每行数据都有一个新div。

<?php
include_once '\inc\header.php';

$db_server = mysql_connect($db_hostname, $db_username, $db_password);

if (!$db_server) die("Unable to connect to MySQL: ". mysql_error());

mysql_select_db($db_database)
or die ("Unable to select database: " . mysql_error());

$query = "select * from deal";
$result = mysql_query($query);

if (!$result) die ("Database access failed: " . mysql_error());
?>

<body class="metrouicss" onload="prettyPrint()" style="zoom: 1;">
<div id="container">

<?php
foreach($result as $tile)
    {?>
        <div class="item tile double bg-color-red">
                <?php echo $tile['name']?>
        </div>
    <?php }?>
</div>


<?php 
mysql_close ($db_server);
?>

`

4 个答案:

答案 0 :(得分:3)

    <?php
include_once '\inc\header.php';

$db_server = mysql_connect($db_hostname, $db_username, $db_password);

if (!$db_server) die("Unable to connect to MySQL: ". mysql_error());

mysql_select_db($db_database)
or die ("Unable to select database: " . mysql_error());

$query = "select * from deal";
$result = mysql_query($query);

if (!$result) die ("Database access failed: " . mysql_error());
?>

<body class="metrouicss" onload="prettyPrint()" style="zoom: 1;">
<div id="container">

 <?php
while($row = mysql_fetch_array($result))
    {?>
        <div class="item tile double bg-color-red">
                <?php echo $row['name']?>
        </div>
    <?php }?>
</div>


<?php 
mysql_close ($db_server);
?>

试试吧!

答案 1 :(得分:0)

mysql_query()返回结果句柄。它不是一个可以循环的数组,这意味着

foreach($result as $tile) {

错了。它应该是

while ($tile = mysql_fetch_assoc($result)) {

代替。

答案 2 :(得分:0)

添加$result = mysql_fetch_array($result);
低于if (!$result) die ("Database access failed: " . mysql_error());

Mysql查询返回一个mysql资源对象。您需要一些其他功能,例如mysql_fetch_array来执行某些操作。

答案 3 :(得分:0)

我会考虑转移到MySQLiPDO。无论如何,另一种方式(使用你的mysql)将在while循环条件下使用$row = mysql_fetch_assoc($result)

<?php
include_once '\inc\header.php';

$db_server = mysql_connect($db_hostname, $db_username, $db_password);

if (!$db_server) die("Unable to connect to MySQL: ". mysql_error());

mysql_select_db($db_database)
or die ("Unable to select database: " . mysql_error());

$query = "select * from deal";
$result = mysql_query($query);

if (!$result) die ("Database access failed: " . mysql_error());
?>

<body class="metrouicss" onload="prettyPrint()" style="zoom: 1;">
<div id="container">

<?php
while($row = mysql_fetch_assoc($result))
    {?>
        <div class="item tile double bg-color-red">
                <?php echo $row['name']?>
        </div>
    <?php }?>
</div>


<?php 
mysql_close ($db_server);
?>