所以我使用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行的随机"name"列。该表具有"id"、"name"answers"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;
}
并且使用相同的CCD_ 5模式在CCD_。
如果将值放入变量中,如$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好运。