我想从数据库中获取数据,并希望存储到数组中,并在将数据存储到数组后,我想访问数组的特定索引。 我是一个java开发人员需要在php中做这个(我不太了解)。 基本上,表中有250个字符串,我想将这250个字符串读入和数组,并希望访问某个特定的行。 例如:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
**$uname100 = $row[100]; // this is not getting assigned to $uname100 variable**
**echo $row[100]; // here this is not printing**
**echo $uname100; // not even this printing**
mysqli_close($con);
?>
请检查代码中的粗体部分并帮助我。我是php的新手,所以请不要对此感到恐慌。
还想做这样的事情:
$ctr=0;
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
$uname[$ctr++] = $row['FirstName']; // AND USING THIS OUTSIDE LOOP
}
echo $uname[90];
答案 0 :(得分:0)
使用数组构造
$counter=0;
$data = array();
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
$data[] = $row['FirstName'];
$counter++;
}
print_r($data);
答案 1 :(得分:0)
您无法访问while循环外的变量$ row [100]。 $ row也不包含索引100。 在while循环中它只包含$ row ['FirstName']或$ row ['LastName']
第二部分答案:
$uname = array();
$ctr=0;
while($row = mysqli_fetch_array($result)) {
....
....
$uname[$ctr++] = $row['FirstName']; // AND USING THIS OUTSIDE LOOP
}
if(isset($uname[90])) echo $uname[90];
答案 2 :(得分:0)
第一个解决方案
$counter=0;
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
$counter++;
$varName='uname'.$counter;
$$varName=$row['FirstName'];
}
echo echo $uname100;