Madison Scodelario
Madison Scodelario

Reputation: 97

Simple and effective way to echo the result of a query in PHP?

I'm new to MySQL and PHP and I m struggling to echo my queries (the results not the text!) I have searched for this but nothing seems to work properly, the best I managed to do was echoing the text of the query. I might have some fatal mistakes but here is my code:

<?php
$username = "root";
$password = "";
$hostname = "localhost"; 

//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) 
  or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";

$selected = mysql_select_db("atoma",$dbhandle) 
  or die("Could not select atoma");

$sql1 = mysql_query("SELECT (MAX(GRADE)) as maximum FROM thema3");
$r = mysql_fetch_array($sql1); // will return the result
echo $r['maximum'];

$sql2 = "SELECT COUNT(DISTINCT NAME) FROM thema2";
$sql1 = "SELECT AVG(GRADE) FROM thema3";

mysql_close($dbhandle);
?>

I get nothing as a result.

I have these 3 queries and all I want is just to print their results. I've written code for echoing only one of the 3 since the other 2 will be echoed as the first one I want to believe.

Upvotes: 0

Views: 5494

Answers (2)

Worvast
Worvast

Reputation: 279

A full example of W3Schools

<?php

// 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 "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();
?>

http://www.w3schools.com/php/php_mysql_select.asp

When you use max, avg, etc you pull only one result, so with the $result[0] you has the result you want

Edit: If you're new, maybe you come to see read this:

http://codular.com/php-mysqli

So A) would leave using an outdated way to call the database, and B) with this in principle bringing the first row you would have the result of AVG, MAX, etc. when only one row which returns you if you make this types of sentences ;)

Upvotes: 1

Tismon Varghese
Tismon Varghese

Reputation: 869

Your code seems incorrect because, the connection is mysqli and fetching is using mysql

$conn = new mysqli($servername, $username, $password, $dbname);

....

$sql1 = mysql_query("SELECT (MAX(GRADE)) as maximum FROM thema3"); 
$r = mysql_fetch_array($sql1); // will return the result

Upvotes: 1

Related Questions