Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display SQL query results in 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

like image 970
user3052127 Avatar asked Nov 30 '13 13:11

user3052127


People also ask

How can I get SQL query results in PHP?

Show activity on this post. 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.

How can we get the data from the MySQL query result set in PHP?

Data can be fetched from MySQL tables by executing SQL SELECT statement through PHP function mysql_query. You have several options to fetch data from MySQL. The most frequently used option is to use function mysql_fetch_array(). This function returns row as an associative array, a numeric array, or both.


2 Answers

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']; 
}
like image 108
Aditya Vikas Devarapalli Avatar answered Sep 22 '22 05:09

Aditya Vikas Devarapalli


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.

like image 37
display-name-is-missing Avatar answered Sep 22 '22 05:09

display-name-is-missing