[英]SQL query not executing in php command line interface created by me
我已經為自己的目的制作了一個SQL命令行界面,並使用以下代碼進行了測試: input.php
<!DOCTYPE html>
<html>
<body>
'DESC'command under dev...
<form action="output.php" method="post">
<textarea name="query"></textarea>
<input type="submit">
</form>
</body>
</html>
output.php
<!DOCTYPE html>
<html>
<body>
<div>
<?php
$servername = "server_name"; //I do not wish to show my credentials
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = $_POST["query"];
$result = $conn->query($sql);
if ($result === TRUE) {
if (substr($sql, 0, 6) == "SELECT") {
//Initialize table
echo "<table class=\"table\">";
echo "<tr><th>ID</th><th>Username</th><th>Password</th><th>Email</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["username"]. "</td><td>" . $row["password"]. "</td><td>" . $row["email"] . "</td></tr>";
}
echo "</table>";
echo "<code>" . $result->num_rows . " rows selected</code>";
} elseif (substr($sql, 0,11) == "INSERT INTO") {
echo "Inserted. Command: $sql";
} elseif (substr($sql, 0, 6) == "DELETE") {
echo "Deleted. Command: $sql";
} elseif (substr($sql, 0, 6) == "UPDATE") {
echo "Updated. Command: $sql";
} else {
echo "Code under dev...\nSorry!";
}
} else {
echo "ERROR: " . $conn->error;
}
echo "<br>";
?>
</div>
</body>
</html>
我已經檢查了數據庫憑證; 他們都很好-沒有conn錯誤。 我之所以知道這一點,是因為我以前曾處理過包含一些數據的表。 現在,在輸入查詢時,除了留下消息“ ERROR:”,什么都沒有發生。 如有任何錯誤,請通知我。
當使用不影響行的SQL語句調用query()函數時,它僅返回TRUE。 在所有其他情況下,它將返回mysqli_result()類型的對象。
這會使if ($result === TRUE)
跳轉到else
並顯示錯誤。 實際上沒有錯誤,因為$ result可能包含一個結果對象。
嘗試通過添加echo $result->num_rows;
來確認這一點echo $result->num_rows;
到您的else
子句。
有關如何處理查詢結果的更多信息,請參見mysqli :: result文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.