这里已经存在相似个问题,但没有一个完全适合我的情况。基本上,我想用来自MYSQL数据库的相同数据填充可变数量的选择菜单。原因是我希望用户能够添加行以同时提交多个选择。
为了避免进行登录->为选择菜单的每个实例读取MYSQL,我创建了一个数组,该数组将在必要时用于填充菜单。问题在于它仅适用于第一实例。换句话说,PHP会在第一次读取后以某种方式删除存储在数组中的值。
如果这个问题很简单,我很抱歉,我对PHP还是很陌生。
到目前为止,这是我的代码:
访问MYSQL并定义变量“结果”:
<?php
$servername = "localhost";
$username = "sonch_PUBLIC";
$password = "sonch_PUBLIC";
$dbname = "sonch_MAIN";
date_default_timezone_set('Europe/Zurich');
$date = date('Y-m-d');
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//START SEARCH BY VENUE
$sql = "SELECT Name, City FROM Venue ORDER BY City";
$result = $conn->query($sql);
$conn->close();
?>
采用第一个实例:
<select style="width:138px; text-align:center">
<option selected>CHOOSE VENUE</option>';
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<option>" . $row["Name"] . " - " . $row["City"] . "</option>";
}
}
?>
</select>
到目前为止很好....但是当我想用相同的代码填充后续菜单时,即重复以下操作:
<select style="width:138px; text-align:center">
<option selected>CHOOSE VENUE</option>';
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<option>" . $row["Name"] . " - " . $row["City"] . "</option>";
}
}
?>
</select>
...他们是空的。
建议?
答案 0 :(得分:5)
您的第一个while
循环:
while($row = $result->fetch_assoc()) {
echo "<option>" . $row["Name"] . " - " . $row["City"] . "</option>";
}
从结果集中读取所有数据。因此,当您执行第二篇时,没有什么可阅读的。要解决此问题,您需要使用mysqli::data_seek
重设数据指针。因此,在随后的while
循环之前,添加以下行:
$result->data_seek(0);
data_seek
将结果集读取指针移动到指定的行号。在这种情况下,我们将其移回第0行或结果集的开头。完成之后,您可以再次完整读取结果集
答案 1 :(得分:0)
您不会创建要使用多次的数组。您只是在处理结果集。使用完结果集后,它就完成了。按照您自己的建议进行操作,并将结果集处理到一个数组中,然后重用该数组
<?php
$servername = "localhost";
$username = "sonch_PUBLIC";
$password = "sonch_PUBLIC";
$dbname = "sonch_MAIN";
date_default_timezone_set('Europe/Zurich');
$date = date('Y-m-d');
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//START SEARCH BY VENUE
$sql = "SELECT Name, City FROM Venue ORDER BY City";
$result = $conn->query($sql);
// If you have the MySQL Native Driver installed
//$allRows = $result->fetch_all();
// if you dont have the MySQL Native Driver installed you will have to do this
$allRows = array();
while ($row = $result->fetch_assoc() ) {
$allRows[] = $row;
}
$conn->close();
?>
第一例
<select style="width:138px; text-align:center">
<option selected>CHOOSE VENUE</option>';
<?php
foreach ($allRows as $row) {
echo "<option>" . $row["Name"] . " - " . $row["City"] . "</option>";
}
?>
</select>
重复使用该数组的次数