Display SQL query results in php - php

I'm tring to diplay results in php from sql database
MySQL statement is correct and does what i want in phpMyAdmin but for some reason my code breaks in the webpage
here is the code
require_once('db.php');
$sql="SELECT * FROM modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) ) FROM modul1open)
ORDER BY idM1O LIMIT 1"
$result = mysql_query($sql);
echo [$result];
and here is what i get
In general I need random number limited from min to max by the table id

You need to fetch the data from each row of the resultset obtained from the query. You can use mysql_fetch_array() for this.
// Process all rows
while($row = mysql_fetch_array($result)) {
echo $row['column_name']; // Print a single column data
echo print_r($row); // Print the entire row data
}
Change your code to this :
require_once('db.php');
$sql="SELECT * FROM modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) ) FROM modul1open)
ORDER BY idM1O LIMIT 1"
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo $row['fieldname'];
}

You need to do a while loop to get the result from the SQL query, like this:
require_once('db.php');
$sql="SELECT * FROM modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )
FROM modul1open) ORDER BY idM1O LIMIT 1";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
// If you want to display all results from the query at once:
print_r($row);
// If you want to display the results one by one
echo $row['column1'];
echo $row['column2']; // etc..
}
Also I would strongly recommend not using mysql_* since it's deprecated. Instead use the mysqli or PDO extension. You can read more about that here.

You cannot directly see the query result using mysql_query(). It just fires the query in mysql, nothing else.
For getting the result you have to add a lil things in your script like
require_once('db.php');
$sql="SELECT * FROM modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) ) FROM modul1open) ORDER BY idM1O LIMIT 1";
$result = mysql_query($sql);
//echo [$result];
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
print_r($row);
}
This will give you result.

Strangely, none of the while loops in the other answers worked for me, they did not throw an error, but their echo was empty. It worked when using foreach instead:
foreach($result as $row) {
//echo $row['column_name']; // Print a single column data
echo print_r($row); // Print the entire row data
}
Idea from: PDO looping through and printing fetchAll

I had to change
$result = mysql_query($sql);
to
$result = $conn->query($sql);
and then use the foreach (thanks to questionto42)
$result = $conn->query($sql);
foreach($result as $row) {
echo $row['column_name'];
}
Don't know if it matters but, I'm on a hosting company with:
Apache Version 2.4.51
PHP Version 7.3.33
MySQL Version 5.6.41-84.1

$query ="
SELECT
*
FROM
users
";
die($query);
In this case your query print on the browser copy this query and run on SQL Server.

Related

SQL SELECT * returns only one row

I'm designing a website and I wrote some webpage that display the list of users.
I used to do a
$query = SELECT * FROM `table_users` WHERE `id`='.$id.'
and then increment the ID with a "while" so I can grab all the users. But it's too slow now, and it glitches when there is a gap between IDs.
So I tried something like
$query = SELECT `name` FROM `tbl_user`ORDER BY `id`
and displaying the userlist with a
while ($i < sizeof(mysql_fetch_array(mysql_query($query)))){
<code to display an user>
$i++
}
But the mysql_fetch_array only returnes one user, the first one (the one with the littliest ID). I want it to return all users in an array. How do I do ?
Try This
$query = "SELECT `name` FROM `tbl_user` ORDER BY `id`";
$user_query = mysql_query($query);
$i=1;
while ($row = mysql_fetch_array($user_query)){
echo $i." : ".$row['name']."<br>";
$i++;
}
Try it like this:
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
//$row is the row which was just gathered
}
And please, use PDO or MySQLi instead of deprecated mysql.

Error displaying rows from MySQL tables

I am trying to get rows from a table when a condition is satisfied (status = 'no transit') but nothing shows up even when rows are supposed to show up (count is 1 and more).
if($query['num'] == 0){
echo "<p>No shopping orders on transit</p>";
}else{
$sql = "SELECT *, FORMAT(total, 0) AS total, FORMAT(grand_total, 0) AS grand_total FROM shipping_details WHERE status = 'no transit' ORDER BY order_id DESC";
foreach ($db->query($sql) AS $query){
echo" Show some results ";
$select = "SELECT * FROM shipping_order WHERE order_id = :order_id";
foreach ($db->query($select, array('order_id' => $query['order_id'])) AS $items){
echo"
Some results
";
//Foreach ends
}
}
}
You don't show enough that we can tell which codebase you use to connect to your DB (MySQLi, mysql_, or PDO), so the code below may need some tweaking.
The problem is basically that you never retrieve your database results. Instead you try to loop through the query execution itself.
Change
$sql = "SELECT *...";
foreach ($db->query($sql) AS $query)...
To
$sql = "SELECT *...";
$result = $db->query($sql); //execute the query
if(!$result) die($db->error); //exit and show error if query failed
//now we can fetch the results one at a time and loop through them
//this line may need to be adjusted if you're not using MySQLi
while($row = $result->fetch_assoc())...
Within the while loop, $row will contain the values from the DB record. Use print_r($row) to learn its shape.
It is not working, because you forgot to use prepare and execute methods from pdoStatemnt class.
See below:
$stmt = $db->prepare("SELECT * FROM shipping_order WHERE order_id = :order_id");
$stmt->execute(array('order_id' => $query['order_id']));
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)){
echo"
Some results
";
//Foreach ends
}

shuffle : Display only one row at the same time

How to display only one row at random at the same time from DB. Everything works fine, but all rows are displayed. thanks
<?php
$sql = "SELECT id,name FROM table ";
$rows = array();
$result = $objCon->query($sql);
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
shuffle($rows);
echo '<ol>';
foreach($rows as $row)
{
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
}
echo '</ol>';
?>
Change your SQL request:
SELECT id,name FROM table ORDER BY RAND() LIMIT 1;
You can do it using PHP:
....
shuffle($rows);
$randomRow = reset($rows);
....
But the better way is to change your SQL query:
$query = "SELECT id, name FROM table ORDER BY RAND() LIMIT 1;"
<?php
$sql = "
SELECT id, name
FROM table
ORDER BY RAND()
LIMIT 1 ";
$result = mysql_query($sql);
// As you are only return a single row you do you require the while()
$row = mysql_fetch_array($result);
echo '<ol>';
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
echo '</ol>';
?>
By adding an ORDER BY RAND() in your sql query you are asking MySQL to randomly order the results then at a LIMIT to restrict the number of rows you would like returned.
The example code is written based on selecting a single row. If you would like more, e.g. 5, you will need to add a while loop.

Field from database not displaying in browser

Can anyone tell me why I am not getting the result of displaying the title on the browser when using the following script:
$sql =mysql_query( "SELECT * FROM 'Tour' WHERE 'Tour_No.'=1 LIMIT 0, 30 ");
echo $sql Title;
my connection is successful, but my desired result is not happening.
$sql = mysql_query( "SELECT * FROM `Tour` WHERE `Tour_No.`=1 LIMIT 0, 30 ");
while($row = mysql_fetch_object($sql))
{
echo $row->Title;
echo '<br />';
}
Maybe you can check this link for more example using mysql_query and mysql_fetch_object :
mysql_query: http://php.net/manual/en/function.mysql-query.php
mysql_fetch_object: http://www.php.net/manual/en/function.mysql-fetch-object.php
Your Query is invalid (single quotes are not used for tables / columns):
$result = mysql_query("SELECT Title FROM Tour WHERE Tour_No = 1 LIMIT 1");
You have to fetch the results:
$row = mysql_fetch_assoc($result);
Output the title:
echo $row['Title'];
Table and field names can be put in backtics, not in single quotes.
SELECT * FROM `Tour` WHERE `Tour_No.`=1 LIMIT 0, 30 // correct
SELECT * FROM 'Tour' WHERE 'Tour_No.'=1 LIMIT 0, 30 // wrong
if your getting 30 results you will need to loop through $sql, try the following.
$sql = mysql_query("SELECT * FROM `Tour` WHERE `Tour_No.` = 1 LIMIT 0, 30 ");
while($row = mysql_fetch_array($sql))
{
echo $row['Title'];
}
From http://php.net/mysql_query:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error....
The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data."
Try this:
$sql =mysql_query( "SELECT * FROM 'Tour' WHERE 'Tour_No.'=1 LIMIT 0, 30 ");
$row = mysql_fetch_assoc($sql);
echo $row['Title'];
I'm not sure exactly what your columns are named, but that should get you on the right track.

How can I get the last ten rows in a Mysql database table?

I use this
$query = "SELECT * FROM info ORDER BY id DESC limit 10";
$result = #mysql_query( $query );
$row = mysql_fetch_array($result);
print_r($row);
but it gets just the last row
mysql_fetch_array does not fetch an array of rows.
It fetches an array of columns from a single row.
To get all rows, you have to run it in a loop:
$query = "SELECT * FROM info ORDER BY id DESC limit 10";
$result = #mysql_query( $query );
while ($row = mysql_fetch_array($result))
print_r($row);
The query is correct. If you seem to be only getting one row, it's a factor external to the query causing it: either you only have one row in the table, or your application logic is hosed so that it looks like you only have one row.
Edit: Yeah, now that you've posted your code, we can see that it's that your application logic is hosed. Try this:
$result = mysql_query($query);
$rows = array();
while($row = mysql_fetch_array($result))
$rows[] = $row;

Categories