从3个随机数据中选择4列来自PHP& MySQL的

时间:2012-08-26 20:50:58

标签: php mysql sql database

所以我正在使用RAND() LIMIT 3,但我在循环中使用它来获得3个随机行。

我需要在我的网站中的不同位置使用每个列。如何在不为每列运行不同查询的情况下获取数据?

我需要的数据不应该是有序的,所以它将是例如:

$Title, will be the title of the page.
$price, will be the price of the service/product.
$description, will be the description of the service/product.

显然,他们在php文件中并不是彼此接近的。

这两个答案听起来合乎逻辑,但我对mysql完全不熟悉,我无法使其正常工作。

这就是我在php文件中的内容:

<?php
mysql_connect("localhost", "test", "test") or die (mysql_error ());
mysql_select_db("test") or die(mysql_error());
$strSQL = "SELECT name FROM UserId ORDER BY RAND() LIMIT 3";
$rs = mysql_query($strSQL);
while($row = mysql_fetch_array($rs)) {
  echo $row['name'] . "<br />";
 }
mysql_close();
?>

它的作用是返回3行的随机“名称”列。 该表有'id','name'和'Age'。

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

只有在$_SESSION不存在时才将它们存储在$_SESSION中,并始终从// On every page that uses these values: session_start(); if (empty($_SESSION['rand_rows'])) { // DB connection code omitted... // This block will execute once per session only... // Get 3 random rows $strSQL = "SELECT name, id, age FROM UserId ORDER BY RAND() LIMIT 3"; $rs = mysql_query($strSQL); if ($rs) { // Fetch all 3 rows and store them in $_SESSION: while ($row = mysql_fetch_assoc($rs)) { $_SESSION['rand_rows'][] = $row; } } } // Later, get them $_SESSION // To get the name for example: foreach ($_SESSION['rand_rows'] as $r) { echo $r['name'] . "<br />"; } // Use the same looping pattern to get the id or age where you need them. 访问它们。

$_SESSION

目前还不清楚你是否真的需要这个来持续跨页面加载。如果您只在一个页面上需要这些行,并且可以在其他页面或后续页面加载中获得3个不同的行,则无需存储到// Array to hold all results $results = array(); while ($row = mysql_fetch_assoc($rs)) { $results[] = $row; } 中,而只需将它们存储到具有以下内容的数组中:

foreach

...并使用相同的$results模式迭代{{1}}。

答案 1 :(得分:2)

如果您将值放入变量中,例如$title$price$description,则会在同一文件中记住它们的值,即使在使用包含时也是如此。

如果您尝试将值保存在不同的页面上,有不同的方法可以实现此目的,但我可能会建议使用$_SESSION跨页面存储此类信息。

如果您按照第一个建议进行操作,但没有运气,我需要更多信息才能正确回答您的问题。一个小代码示例可以提供帮助。


编辑:

虽然@ michael-berkowski的答案完全正常,但你不一定要用$_SESSION来达到你想要的效果。既然你说你刚刚学习PHP,我就添加了一种不同的方法。虽然没有其他答案那么优雅,但它更快,我编辑了一些变量(这是一个好习惯,使用小写表名,变量相同):

<?php
//Insert DB-connection code
$sql = "SELECT `name` FROM `user` ORDER BY RAND() LIMIT 3";
$rs = mysql_query($sql);
//We should check, if there are actually 3 rows, before doing anything else.
if (mysql_num_rows($rs) == 3) {
   $title = mysql_result($rs,0,0);
   $price = mysql_result($rs,1,0);
   $description = mysql_result($rs,2,0);
}
echo("Title: $title <br/>Price: $price <br/>Description: $description");
?>

祝PHP学习好运。