I have made a SQL command line interface for my own purpose and testing with the following code: 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...
Sorry!";
}
} else {
echo "ERROR: " . $conn->error;
}
echo "<br>";
?>
</div>
</body>
</html>
I have checked the database credentials; they're all fine- no conn error. I know this because I worked with a table with some data before. Now, on entering a query, nothing happens except it leaves a message- 'ERROR: '. Please inform me of any errors.
The query() function only returns TRUE when called with a SQL-statement that doesn't affect rows. In all other cases it returns an object of the type mysqli_result().
That causes the if ($result === TRUE)
to jump to else
and display the error. In fact there was no error, as $result probably holds a result object.
Try to confirm this by adding echo $result->num_rows;
to your else
clause.
See the mysqli::result documentation for more information on how to process your query results.