用PHP正确显示MySQL数据?

时间:2014-02-23 19:47:51

标签: php mysql

以下是我正在使用的当前代码:

<?php include('database.php'); ?>

<a href="http://local.mysite.com/<?php echo $service; ?>/<?php echo $city; ?>"><?php echo $city; ?> <?php echo $service; ?></a> - 
<a href="http://local.mysite.com/<?php echo $service; ?>/<?php echo $city; ?>"><?php echo $city; ?> <?php echo $service; ?></a> - 
<a href="http://local.mysite.com/<?php echo $service; ?>/<?php echo $city; ?>"><?php echo $city; ?> <?php echo $service; ?></a> - 
<a href="http://local.mysite.com/<?php echo $service; ?>/<?php echo $city; ?>"><?php echo $city; ?> <?php echo $service; ?></a> - 
<a href="http://local.mysite.com/<?php echo $service; ?>/<?php echo $city; ?>"><?php echo $city; ?> <?php echo $service; ?></a>

它显示了这个(带有超链接):

houston marketing services - houston marketing services - houston marketing services - houston marketing services - houston marketing services

问题是我希望为每个人展示不同的服务和城市。我需要做些什么才能显示5个不同名称的不同链接?

正在从数据库中提取$service$city

以下是数据库文件的代码:

<?php

mysql_connect("localhost", "database_user", "password") or die(mysql_error()); 
mysql_select_db("database_name") or die(mysql_error()); 

$cityquery = "SELECT * FROM cities ORDER BY RAND() LIMIT 1";
$cityresult = mysql_query($cityquery);
$cityrow = mysql_fetch_row($cityresult);
$city = $cityrow[0];

$servicequery = "SELECT * FROM services ORDER BY RAND() LIMIT 1";
$serviceresult = mysql_query($servicequery);
$servicerow = mysql_fetch_row($serviceresult);
$service = $servicerow[0];
?>

1 个答案:

答案 0 :(得分:0)

您不会在显示期间以任何方式修改变量。您应该获取它们并逐个显示行(database.php应该返回整个响应对象):

while($row = $result->fetch_object()) {
    $service = $row->service;
    $city = $row->city;
    echo "<a href=\"http://local.mysite.com/$service/$city\">$city $service</a>";
}

我假设您使用的是mysqli(因为不推荐使用mysql)。