[英]$row[''] in prepared statements PHP
我试图更改我的mysqli代码以使用准备好的语句。
由于某种原因,我无法正常使用$row['']
。 我用谷歌搜索了一段时间,但我不明白。 我的代码没有准备好的语句是这样的:
if($result = mysqli_query($con,"SELECT * FROM users")) {
echo "
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody>";
while($row = mysqli_fetch_array($result)) {
if($row['status'] == "1") {
echo '<tr class="active">';
} elseif($row['status'] == "2") {
echo '<tr class="success">';
} elseif($row['status'] == "0") {
echo '<tr class="danger">';
} else {
echo '<tr class="warning">';
}
etc...
到目前为止,这是我准备的语句:
$grab_user = $db->prepare("SELECT * FROM users");
if($grab_user->execute()) {
echo "
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody>";
while($grab_user->fetch()) {
$row = $grab_user->fetch_row();
if($row['status'] == "1") {
echo '<tr class="active">';
} elseif($row['status'] == "2") {
echo '<tr class="success">';
} elseif($row['status'] == "0") {
echo '<tr class="danger">';
} else {
echo '<tr class="warning">';
}
显然,它似乎不起作用。 我究竟做错了什么?
fetch_row
从结果集中获取一行数据,并将其作为枚举数组返回,其中每列存储在从0(零)开始的数组偏移量中 。
因此它应该类似于$row[0]
。 找出状态索引,然后使用适当的值。
如果需要使用列名进行访问,则需要使用fetch_assoc
。
像这样:
while($row=$grab_user->fetch_assoc()) {
if($row['status'] == "1") {
echo '<tr class="active">';
} elseif($row['status'] == "2") {
echo '<tr class="success">';
} elseif($row['status'] == "0") {
echo '<tr class="danger">';
} else {
echo '<tr class="warning">';
}
}
fetch_row
数字数组
fetch_assoc
关联数组
如果需要关联数组,则应使用fetch_assoc()
,而不要使用fetch_row()
,它返回一个数字数组。
另外,您不应在循环中同时调用fetch()
和fetch_assoc()
。 它们每个都将读取下一行,因此fetch_assoc()
将仅获得结果的每隔一行。 因此应该是:
while ($row = $grab_user->fetch_assoc()) {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.