这是我回复一个表的代码。任何人都可以告诉如何在同一个数据库中回显两个表?
<?php
include 'dbconfig.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM table1";
$result = $conn->query($sql);
if ($result->num_rows >0) {
// output data of each row
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "0 results";
}
echo $json;
$conn->close();
答案 0 :(得分:1)
你只发出一行,对吗?问题是您为每一行反复覆盖$json
。这应该更好:
<?php
// as before
$sql = "SELECT * FROM table1";
$result = $conn->query($sql);
$rows = array();
while($row[] = $result->fetch_assoc()) {
$rows[] = $row;
}
echo json_encode($rows);
答案 1 :(得分:0)
你似乎在询问2个表,所以我假设你想要运行另一个查询,然后回显一些json。
由于json正在被回应,我认为这可能是通过ajax调用,你无法回复两次。
如果这些假设是正确的,那些while循环中的行上几乎没有额外的处理,那么最直接的方法就是使用fetch_all()
和另一个查询:
<?php
include 'dbconfig.php';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Table1 query and fetch_all give an array back
$sql = "SELECT * FROM table1";
$result = $conn->query($sql);
$table1 = $result->fetch_all();
//Table2 and fetch_all give an array back
$sql = "SELECT * FROM table2";
$result = $conn->query($sql);
$table2 = $result->fetch_all();
//Send json of both in one line
echo $json_encode(array($table1,$table2));
//Check on other side if it is empty. That is more view related.
答案 2 :(得分:0)
<?php
include 'dbconfig.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM t1";
$sql_1 = "SELECT * FROM t2";
$result = $conn->query($sql);
$result_1 = $conn->query($sql_1);
if ($result->num_rows >0) {
// output data of each row
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
$a1 = rtrim($json , ']');
}
} else {
echo "0 results";
}
if ($result_1->num_rows >0) {
// output data of each row
while($row_1[] = $result_1->fetch_assoc()) {
$tem_1 = $row_1;
$json_1 = json_encode($tem_1);
$a2 = ltrim($json_1 , '[');
}
} else {
echo "0 results";
}
echo $a1 , ',' ;
echo $a2 ;
$conn->close();
?>