gpt4 book ai didi

php - 从 PHP 和 MySQL 的 3 个随机数据中选择 4 列

转载 作者:搜寻专家 更新时间:2023-10-30 20:05:18 25 4
gpt4 key购买 nike

所以我使用的是 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

关于php - 从 PHP 和 MySQL 的 3 个随机数据中选择 4 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12133808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com