[英]Selecting 4 columns from 3 Random Data From PHP & MySQL
所以我使用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”。
非常感谢您的帮助!
仅将它们存储在$_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.
尚不清楚您是否真的需要在页面加载期间保持这种状态。 如果您仅在一个页面上需要这些行,而在其他页面或随后的页面加载中可以得到3个不同的行,则无需存储到$_SESSION
,只需将它们存储到一个数组中即可:
// Array to hold all results
$results = array();
while ($row = mysql_fetch_assoc($rs)) {
$results[] = $row;
}
...并使用相同的foreach
模式遍历$results
。
如果将值放入$title
, $price
和$description
等变量中,即使使用include,它们的值也会在同一文件中被记住。
如果您尝试在不同页面上保存值,则可以采用不同的方法来实现此目的,尽管我可能会建议使用$_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运气好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.