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...\nSorry!";
}
} 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.
mysqli::query
See the mysqli::result documentation for more information on how to process your query results.
Related
The below code works perfectly and gives me the "id" "firstname" and "lastname". What I want is to use a loop to echo all the field values in the result row without having to quote each column name like
$row["id"]
below is the working code
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["id"]. " - Name: ". $row["firstname"]. " " .
$row["lastname"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
any thoughts please
This should work..
while($row = $result->fetch_array()) {
$i=0;
while($i<count($row)){
echo $row[$i];
$i++;
}
}
just use a foreach loop inside while like this
foreach($row as $key=>$value){
echo "<br> $key: ". $value. "<br>";
}
If I understand what you want to do is automate the output of the name of each column with its value (independent of the number of columns you get).
So do it like this :
if ($result->num_rows > 0) {
foreach($result->fetch_assoc() as $row) { // browse each records
foreach($row as $col => $value) { // browse each columns on a record
echo "<br>$col: $value<br>";
}
}
}
else {
echo "no result";
}
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 6 years ago.
So I'm new to mysqli. All of the examples I find online seem to be the old (procedural) way of doing things. Can someone tell me why my code isn't working below? My db is 'templatedb'. My Table is 'template'. I have one entry in my table, but I'm receiving no output with my echo. I'm not getting any errors with my code.
<div id="templateSelector">
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$db = "templatedb";
//connect
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$database = mysqli_connect($hostname, $username, $password, $db);
if(!$database){
die("Could not connect to the database");
}
if ($database->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
} else {
$sql = "SELECT * FROM template";
if (!$result = $database->query($sql)) {
die('There was an error running the query [' . $db->error . ']');
} else {
echo "<label>Select Template</label>";
echo "<select name='templates'>";
while ($row = $result->fetch_assoc()) {
echo "hello";
echo $row['template_name'];
// echo "<option value='" . $row['template'] . "'>" . $row['template'] . "</option>";
}
echo "</select>";
}
}
?>
Try doing the following, worked for me
<div id="templateSelector">
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$db = "templatedb";
$mysqli = mysqli_connect($hostname, $username, $password, $db);
if($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
} else {
$sql = "SELECT * FROM template";
$result = mysqli_query($mysqli, $sql);
if(!$result = $mysqli->query($sql)) {
die('There was an error running the query [' . $db->error . ']');
} else {
echo "<label>Select Template</label>\n";
echo "<select name='templates'>\n";
while($row = $result->fetch_assoc()) {
echo "<option>id = " . $row['id'] . "</option>\n";
}
echo "</select>";
}
}
?>
</div>
Make sure your DATABASE is called templatedb and the table it is in is called template and there is a row called id. I know that sounds trivial, but spelling mistakes will break your code.
I am trying to output the results of an SQL query as a table on a page on my website. I have found a few solutions online but I can't get any of them to work properly. Right now I copied and pasted a bit of code to just output the first two columns but I can't figure out how to get every column in a table. I am new to PHP and web development in general so any help would be appreciated.
My PHP:
<?php
SESSION_START() ;
$servername = "localhost";
$username = "MY USERNAME";
$password = "MY PASSSWORD";
$dbname = "MY DATABASE NAME";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//$_session['userid'] = $userlogged;
$sql = "SELECT * FROM `climbs` WHERE `userlogged` = '" . $_SESSION['userid'] . "'";
$result = mysqli_query($conn,$sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["climb-id"]. "</td><td>" . $row["climbname"]. " " . $row["cragname"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
mysqli_close($conn);
?>
check with var_dump :
some like that:
$result = mysqli_query($conn,$sql);
var_dump($result);
if ($result->num_rows > 0) {
maybe the query it's wrong.
I am making a simple page to test a database connection. When I tried accessing it from my browser, it says:
Server error
The website encountered an error while retrieving http://localhost:8888/blah/blah/test.php. It may be down for maintenance or configured incorrectly.
Here are some suggestions:
Reload this webpage later. HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.
All I am doing is connecting to a database and displaying the tables. Here is what I have so far as the PHP code:
<?php
// Get Variables
$dbname = $_GET["dbname"];
$dbusername = $_GET["dbusername"];
$dbpass = $_GET["dbpass"];
$dbhost = $_GET["dbhost"];
$connection = mysql_connect("$dbhost","$dbusername","$dbpass");
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}
else
{
echo "Connected";
$dbcheck = mysql_select_db("$dbname");
if (!$dbcheck) {
echo mysql_error();
}else{
echo "<p>Successfully connected to the database '" . $database . "'</p>\n";
// Check tables
$sql = "SHOW TABLES FROM `$database`";
$result = mysql_query($sql);
if (mysql_num_rows($result) > 0) {
echo "<p>Available tables:</p>\n";
echo "<pre>\n";
while ($row = mysql_fetch_row($result)) {
echo "{$row[0]}\n";
}
echo "</pre>\n";
} else {
echo "<p>The database '" . $database . "' contains no tables.</p>\n";
echo mysql_error();
}
}
// some code
mysql_close($con);
?>
My error in the WAMP Apache logs is:
[03-Feb-2013 22:47:37 UTC] PHP Parse error: syntax error, unexpected end of file in /Applications/MAMP/htdocs/coursemanager/default/verify1.php on line 52
What would a unexpected end of file be?
It means you forgot to close the last }
<?php
// Get Variables
$dbname = $_GET["dbname"];
$dbusername = $_GET["dbusername"];
$dbpass = $_GET["dbpass"];
$dbhost = $_GET["dbhost"];
$connection = mysql_connect("$dbhost","$dbusername","$dbpass");
if (!$connection) {
die('Could not connect: ' . mysql_error());
} else {
echo "Connected";
$dbcheck = mysql_select_db("$dbname");
if (!$dbcheck) {
echo mysql_error();
} else {
echo "<p>Successfully connected to the database '" . $database . "'</p>\n";
// Check tables
$sql = "SHOW TABLES FROM `$database`";
$result = mysql_query($sql);
if (mysql_num_rows($result) > 0) {
echo "<p>Available tables:</p>\n";
echo "<pre>\n";
while ($row = mysql_fetch_row($result)) {
echo "{$row[0]}\n";
}
echo "</pre>\n";
} else {
echo "<p>The database '" . $database . "' contains no tables.</p>\n";
echo mysql_error();
}
}
// some code
mysql_close($con);
}
I have spent the better part of three days on this problem. I've tried several solutions that I've found on this site but with little success. What I'm trying to do is use a PHP variable to play a youtube video in an iframe. I'm also trying to run two MySQL queries with the same input. Here is my code as it sits right now. At this moment when it runs I get the table that I'm wanting, though I still need to format it. But the iframe isn't even showing up. A previous solution I tried would pull up the iframe but inside would be an error where I was basically passing the sql query to the iframe.
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "purpletrainer";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";
$trainingid = $_POST["trainingid"];
$sql = "SELECT * FROM purpletrainer.trainingcontent WHERE trainingid = '$trainingid';";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>Training ID</th><th>Title</th><th>Training URL</th><th>Training Quiz URL</th></tr>";
// output data of each row
while ($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["trainingid"] . "</td><td>" . $row["trainingtitle"] . "</td><td>" . $row["trainingurl"] . "</td><td>" . $row["trainingquizurl"] . "</td></tr>";
}
echo "</table>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "purpletrainer";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$videosql = "SELECT trainingurl FROM purpletrainer.trainingcontent WHERE trainingid = '$trainingid';";
$videoresult = $conn->query($videosql);
if ($videoresult->num_rows > 0) {
while ($videourl = $videoresult->fetch_assoc()) {
}
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
<div class="col-md-6">
<iframe width="420" height="315" src= '<?php echo htmlspecialchars($videourl); ?>' frameborder="0" allowfullscreen></iframe>
</div>
It's common practice not to use the variable $videourl outside of the while loop. (Put your iframe within the while loop).
sidenote: fetch_assoc() will create an array. It should be $videourl['trainingurl'];
Here's an example:
<?php
if ($videoresult->num_rows > 0)
{
while($videourl = $videoresult->fetch_assoc()){
?>
<div class="col-md-6">
<iframe width="420" height="315" src= '<?= $videourl['trainingurl']; ?>' frameborder="0" allowfullscreen></iframe>
</div>
<?php
}
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
edit for clarity and future readers
Note that the <?= $variable ?> opening tag has only been properly supported since php 5.4+. When not using this version, maintain the usage of <?php echo $variable; ?>