我們怎樣才能一次選擇兩個表,並得到如何在一個SQL查詢中連接兩個SELECT語句?
<?php
$id= null;
@$id = $_REQUEST['id'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ID, name, gender, age, contact, village, town, id_proof, id_proof_no, reg_date
FROM milk_man_profile WHERE ID=$id
UNION
SELECT date, time, amount, particular FROM debit WHERE ID=$id";
$result = $conn->query($sql);
if (@$result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<h3 style='text-align: center; font-family: verdana;'>Profile Details</h3>";
echo "<form action='milk_edit_profile.html?id=$id' method='get'><div class='container'><div class='table-reponsive text-center'><table class='table table-bordered table-striped'>
<tr><th>ID:</th><td class='text-center'><input readonly style='text-align: center; border: 0px solid;' type='text' name='id' value='".$row['ID']."'></td></tr>
<tr><th>Name:</th><td>".$row['name']."</td></tr>
<tr><th>Reg. Date:</th><td>".$row['reg_date']."</td></tr>
<tr><th>Age (Reg. Date)</th><td>".$row['age']."</td></tr>
<tr><th>Gender:</th><td>".$row['gender']."</td></tr>
<tr><th>Contact No:</th><td>".$row['contact']."</td></tr>
<tr><th>Village:</th><td>".$row['village']."</td></tr>
<tr><th>Town:</th><td>".$row['town']."</td></tr>
<tr><th>".$row['id_proof']." No:</th><td>".$row['id_proof_no']."</td></tr>
<tr><td colspan='2' class='text-center'><button type='submit' class='btn btn-info'>Edit Details <span class='glyphicon glyphicon-edit'></span></button></td>
</tr></table></div></div></form><br/>
<div class='container'>
<div class='table-responsive'>
<table class='table table-bordered table-striped'>
<th class='text-center'><b>Date & Time</b></th>
<th class='text-center'><b>Type</b></th>
<th class='text-center'><b>Amount</b></th>
</table>
</div>
</div>
<div class='text-center'>
<form action='/milk_e_ledger/debit.html?'>
<input type='hidden' name='debiter_name' method='get' value='".$row['name']."'>
<input type='hidden' name='id' method='get' value='$id'>
<br/>
<button class='btn btn-danger'>Debit Money <span class='glyphicon glyphicon-usd'></span></button></form></div><br/>";
}
}
else {
echo("Error description: " . mysqli_error($conn));
}
$conn->close();
?>
然後我收到以下錯誤數據:
The used SELECT statements have a different number of column
我如何可以一次選擇兩個表中的信息? < ------------------->
首先,在http://bobby-tables.com瞭解SQL注入,並學習如何預防它們。你的代碼實際上對於注入是非常開放的,你的數據庫可能會在幾秒鐘內被黑客入侵,而不需要你係統的任何知識。當您在querys中使用來自POST/URL的輸入時,請使用始終準備好的語句。順便說一句,你要找的是'SQL JOIN'功能。谷歌爲它,有很多例子。 – Twinfriends
看起來你正在尋找'加入'不是'聯盟' – Jens
這聽起來像你正在嘗試使用JOIN從2個不同的表中收集數據。試用本教程以瞭解有關JOIN的基礎知識:https://www.w3schools.com/sql/sql_join.asp –