PHP仅从DB返回一个值

时间:2013-11-09 18:45:48

标签: php mysql arrays

我有以下代码:

$getrand = "SELECT DISTINCT Name from Events Order BY Rand() Limit 1";
$result = mysqli_query($con,$getrand);
$data = mysqli_fetch_array($result);
echo "<div class = 'container'>Name: $data[0]</br>";
$gettags = "SELECT Tag From Events where Name = '$data[0]'";
$tagresult = mysqli_query($con, $gettags);
$tagdata = mysqli_fetch_array($tagresult);
echo "$tagdata[0], $tagdata[1]";

但是它只返回tagdata中的一个值。我的数据库看起来像:

ID |名称|标签

一个名称可以有多个标签(即每个名称有多行标签)

1 个答案:

答案 0 :(得分:1)

你需要像这样循环你的记录集......

$getrand = "SELECT DISTINCT Name from Events Order BY Rand() Limit 1";
$result = mysqli_query($con,$getrand);
$data = mysqli_fetch_array($result);
echo "<div class = 'container'>Name: $data[0]</br>";
$gettags = "SELECT Tag From Events where Name = '$data[0]'";
$tagresult = mysqli_query($con, $gettags);

while($tagdata = mysqli_fetch_array($tagresult)) // a while loop has been used here
{
echo $tagdata['Tag'];// 'tag' your column name (change it as per your requirement)
}