在php中使用PDO通过json_编码输出
我一直在尝试使用下面的代码从数据库输出数据,但发现很难在屏幕上显示获取的数据。在php中使用PDO触发选择。我应该如何解决此问题在php中使用PDO通过json_编码输出,php,Php,我一直在尝试使用下面的代码从数据库输出数据,但发现很难在屏幕上显示获取的数据。在php中使用PDO触发选择。我应该如何解决此问题 <?php include ("core.php"); $output = array('data' => array()); $sql = "SELECT categories_id, categories_name, categories_active, categories_status FROM categor
<?php
include ("core.php");
$output = array('data' => array());
$sql = "SELECT categories_id, categories_name, categories_active, categories_status FROM categories WHERE categories_status = ?";
$result = $connect->prepare($sql);
$result->execute([1]);
if($result->rowCount() > 0) {
// $row = $result->fetch_array();
$activeCategories = "";
while($row = $result->fetchAll()) {
$categoriesId = $row[0];
// active
if($row[2] == 1) {
// activate member
$activeCategories = "<label class='label label-success'>Available</label>";
} else {
// deactivate member
$activeCategories = "<label class='label label-danger'>Not Available</label>";
}
$button = '<!-- Single button -->
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Action <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a type="button" data-toggle="modal" id="editCategoriesModalBtn" data-target="#editCategoriesModal" onclick="editCategories('.$categoriesId.')"> <i class="glyphicon glyphicon-edit"></i> Edit</a></li>
<li><a type="button" data-toggle="modal" data-target="#removeCategoriesModal" id="removeCategoriesModalBtn" onclick="removeCategories('.$categoriesId.')"> <i class="glyphicon glyphicon-remove-sign"></i> Remove</a></li>
<li><a type="button" data-toggle="modal" data-target="#deleteCategoriesModal" id="deleteCategoriesModalBtn" onclick="deleteCategories('.$categoriesId.')"> <i class="glyphicon glyphicon-trash"></i> Delete</a></li>
</ul>
</div>';
$output['data'][] = array(
$row[1],
$activeCategories,
$button
);
} // /while
}// if num_rows
$connect = null;
echo json_encode($output);
?>
函数将获取所有行和列,而不仅仅是一行和一列。话虽如此,只需将变量$row
置于while
循环之外,以不同的方式调用它(比如,$rows
),然后使用类似于foreach($row作为$row的行)
的方法在循环中迭代。另外,现在,$行将不采用数字索引,而是使用SQL查询中所选内容的名称进行索引,如$row['categories\u id']
这应该可以解决在您得到的行上进行迭代的问题。还有一件事我不确定,那就是$result->execute([1])代码>,因为该函数接受参数,您只给它一个数字为1的1元素数组,尽管我真的不知道,因为我没有剩下的代码
我猜您正在尝试将JavaScript与AJAX结合使用,因为您正在打印编码的$output变量,所以您需要在开始时使用php://input
,您将获得AJAX发送的所有参数,并且在编码之前,使用函数头将内容类型设置为application/json
(“内容类型:application/json”)代码>不太清楚您想做什么。目前,您正在填充数组$output,然后在打印之前用JSON对其进行编码。你到底想做什么?打印HTML代码,使其显示在页面上?请将HTML代码设置为Categories Name Status Options
您尝试处理JSON并将其放入页面的代码在哪里?
<thead>
<tr>
<th>Categories Name</th>
<th>Status</th>
<th style="width:15%;">Options</th>
</tr>
</thead>
</table>```