how to show a SUM column in PHP - php

I have been trying to show a summaries of a column with the SUM() function in PHP.
I'm using $pointsummary= "SELECT SUM(points) FROM result WHERE id=$val"; to call my SUM function but i cant show it in my PHP. I've tried $test = mysqli_fetch_array($pointsummary); and then echo $test[0]; but it wont work.
When i do this i get:
mysqli_fetch_array() expects parameter 1 to be mysqli_result
What should i do?

Your error is caused by the fact that $pointsummary is a string and not a mysqli_result object. you need to use mysqli_query first and use what that returns. eg.
$resultObj = mysqli_query($con, $pointsummary); // <--- $con is what you got from mysqli_connect()
$resultArr = mysqli_fetch_array($resultObj);
Another note is that with SELECT SUM(points) FROM result i would suggest aliasing SUM(points) with a name you'll recognize so that instead of having to var_dump the key/values of the mysqli_fetch_array to find what the array key is for SUM(points) you'll know before hand.
to do this use AS. ie
SELECT SUM(points) AS `summary` FROM result

#Memor-X answer is good but I have a feeling that you have missed at least one step in the normal flow of event when querying a database in PHP using mysqli_
// create a query as a text string
$pointsummary = "SELECT SUM(points) as `tot_points`
FROM result
WHERE id=$val";
// issue the query to the MySQL Server for execution
// this should create a result set as long as the query is valid
$result = mysqli_query($con, $pointsummary);
// Check that the query had no errors
if ( ! $result ) {
echo mysqli_error($con);
exit;
}
// request the first row from the result set
// as we know this query will only return one row
// we dont need to do this in a loop
$row = mysqli_fetch_assoc($result);
echo $row['tot_points'];

Related

MySQL returned an empty result still showing 1 in count

I have a query which is to check data from two different tables everything is working fine though. When i paste the query in cPanel then result is showing like this
MySQL returned an empty result set (i.e. zero rows). (Query took 0.0005 sec)
but when i count the query in php it is returing 1 instead of 0 don't know why
Here is my Sql query
SELECT mobile, emailid
FROM tbl_users
WHERE mobile =9653878051
AND emailid = 'rawat#gmail.com'
GROUP BY mobile
UNION ALL SELECT mobile, email
FROM tbl_addusr
WHERE mobile =9653878051
AND email = 'rawat#gmail
.com'
LIMIT 0 , 30
and i am counting it like this i am storing the sql result in data variable
$result = mysql_num_rows($data);
echo count($result)>0?1:0;
and it is resulting 1 instead of 0
You do not need to count anything. mysql_num_rows gives you the number of rows.
Use like this:
$result = mysql_query($query);
echo mysql_num_rows($result);
1: Stop using mysql_* functions. Use mysqli or PDO instead.
2: Use SQL Count: http://www.w3schools.com/sql/sql_func_count.asp
Oh yes, just as advise: don't use variable names like $aaaaaa ... names like this one just say nothing about what the variable is and when you repopen the project in a few month you won't understand anything what you've done.
You are using the count() function of PHP, which from the manual states:
Returns the number of elements in array_or_countable. If the parameter is not an array or not an object with implemented Countable interface, 1 will be returned. There is one exception, if array_or_countable is NULL, 0 will be returned.
So on your case, it will return 1. Just remove the count() function and compare the value of $result itself in your ternary operator.
mysql_num_rows — Get number of rows in result not array
Description
int mysql_num_rows ( resource $result )
Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
Parameters
result
The result resource that is being evaluated. This result comes from a call to mysql_query().
Return Values
The number of rows in a result set on success or FALSE on failure.
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query(" SELECT mobile, emailid
FROM tbl_users
WHERE mobile =9653878051
AND emailid = 'rawat#gmail.com'
GROUP BY mobile
UNION ALL SELECT mobile, email
FROM tbl_addusr
WHERE mobile =9653878051
AND email = 'rawat#gmail
.com'
LIMIT 0 , 30", $link);
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
echo $num_rows>0?1:0;//compare like this
?>
check doc http://php.net/manual/en/function.mysql-num-rows.php and http://php.net/manual/en/function.count.php

Php PDO request for data from the sum of a derived table column

Here is an SQL query that I am attempting to use in some php PDO code:
SELECT SUM(credit_hours) AS hours FROM(SELECT Course_List.credit_hours FROM Program_Courses, Course_List
WHERE program_id= :pid and concentration_id= :conid
and fulfills_major=1 and Program_Courses.course_id = Course_List.course_id ) AS major_credits
When I run this query on my database in SQL Workbench I get a derived table with a single column named
"hour" and a single row with the value 76 in it.
Here is the php code I'm using to try to get this same data stored in a variable $major_hours:
$result = $conn->prepare("SELECT * FROM students WHERE username = :un");
$result->bindParam(':un',$user);
$result->execute();
$data = $result->fetch(PDO::FETCH_ASSOC); //returns an associated array where the indices are the column names
$program = $data['program_id'];
$concentration = $data['concentration_id'];
//get the total number of credit hours in the student's major/concentration
$result = $conn->prepare("SELECT SUM(credit_hours) AS hours FROM(
SELECT Course_List.credit_hours FROM Program_Courses, Course_List
WHERE program_id= :pid and concentration_id= :conid
and fulfills_major=1 and Program_Courses.course_id = Course_List.course_id
) AS major_credits");
$result->bindParam(':pid',$program);
$result->bindParam(':conid',$concentration);
$result->execute();
$major_hours = $result->fetchColumn();
I know that the variables $user, $program, and $concentration all have legitimate values because when I echo those to the page, I get the correct result. However, echoing $major_hours gives absolutely nothing. What am I doing wrong?
Use fetch as you may guess it fetches the next row from a result set
The fetch_style parameter determines how PDO returns the row, in your case FETCH_ASSOC would be a good one since it returns an array indexed by column name as returned in your result set.
$row = $result->fetch(PDO::FETCH_ASSOC);//row is an associative array
$major_hours = $row['hours']; //access the column name hour
echo $majors_hours; //will print the hour value from db
I have not used sql workbench, but you may want to use isnull() or coalesce() on your SUM(credit_hours) expression. I think that should result in $major_hours showing 0.
Use this
$major_hours = $result->fetch(PDO::FETCH_ASSOC);
echo $majors_hours['hours'];
There is 2 way to return a data from database. fetch(PDO::FETCH_ASSOC) and fetchAll(PDO::FETCH_ASSOC). Fetch only return 1 row from database .. but fetchAll will return all row from the database query you make.
And (PDO::FETCH_ASSOC) it means will return the data with an array.

sqlite3 - efficient way to count rows returned from SELECT statement in PHP without using COUNT()

I'm an SQL noob and learning how to use PDO. I'm doing a course which introduces basic user login functions. In an example of a login page, they check the username/password against a MySQL database. I edited their code slightly to be able to simultaneously check whether the user/pass combo exists and also grab the user's first name:
$sql = sprintf("SELECT firstname FROM users WHERE username='%s' AND password='%s'",
mysql_real_escape_string($_POST["username"]),
mysql_real_escape_string($_POST["password"]));
// execute query
$result = mysql_query($sql);
if (mysql_num_rows($result) == 1) {
$_SESSION["authenticated"] = true;
// get contents of "firstname" field from row 0 (our only row)
$firstname = mysql_result($result,0,"firstname");
if ($firstname != '')
$_SESSION["user"] = $firstname;
}
What I want to do is use SQLite instead and do the same thing. Searching around has only resulted in people saying you should use a SELECT COUNT(*) statement, but I don't want to have to use an extra query if it's possible. Since I'm SELECTing the firstname field, I should only get 1 row returned if the user exists and 0 if they don't. I want to be able to use that number to check if the login is correct.
So far I've got this:
$dsn = 'sqlite:../database/cs75.db';
$dbh = new PDO($dsn);
$sql = sprintf("SELECT firstname FROM users WHERE username='%s' AND password='%s'",
$_POST["username"],
$_POST["password"]);
// query the database and save the result in $result
$result = $dbh->query($sql);
// count number of rows
$rows = sqlite_num_rows($result);
if ($rows == 1) { ...
But this is returning Warning: sqlite_num_rows() expects parameter 1 to be resource, object given.
Is there a way I can do this efficiently like in MySQL, or do I have to use a second query?
EDIT:
I found this, not sure if it's the best way but it seems to work: How to get the number of rows grouped by column?
This code let me do it without the second query:
// query the database and save the result in $result
$result = $dbh->query($sql);
// count number of rows
$rows = $result->fetch(PDO::FETCH_NUM);
echo 'Found: ' . $rows[0];
$rows is an array so I can just count that to check if it's > 0.
Thanks to everyone who commented. I didn't know until now that there were 2 different approaches (procedural & object oriented) so that helped a lot.
Normally, you can use PDOStatement::rowCount(), however, SQLite v3 does not appear to provide rowcounts for queries.
You would need to seperately query the count(*), or create your own counting-query-function.
The documentation comments have an example of this
A bit late, but i tried this with SQLite3 successful:
$result = $db->query('SELECT * FROM table_xy');
$rows = $result->fetchAll();
echo count($rows);

How to get the result of a select count(*) query in PHP?

I have this query to use in PHP:
mysql_query("select count(*) from registeredUsers where email=".$_SESSION["username"]);
When I use echo to print out the result, nothing gets printed. What exactly is the return value from the above statement?
Your code doesn't include any fetch statement. And as another answer notes, you need single quotes around $_SESSION["username"].
$result = mysql_query("select count(*) from registeredUsers where email='{$_SESSION['username']}'");
// Verify it worked
if (!$result) echo mysql_error();
$row = mysql_fetch_row($result);
// Should show you an integer result.
print_r($row);
mysql_query returns a result resource. You can read the result with mysql_result
$res = mysql_query("select count(*) from registeredUsers where email='".mysql_real_escape_string($_SESSION["username"])."'");
echo mysql_result($res,0);
You need single quotes around the session variable in your query
$result = mysql_query("SELECT COUNT(*)
FROM registeredUsers
WHERE email = '".$_SESSION['username']."' ");
The count query will always return a value, which is 0 if no records are returned, or an integer above 0 if records match it.
It should at least be printing out 0, the query you posted means:
Get the number of records where the email address is equal to the session username
This might not make sense, do you mean to do where username = ".$_SESSION["username"] or something similar?
You may want to echo out the query itself to determine that it is returning what you expect.
mysql_query() returns a resource used to get information from the result set. Use a function such as mysql_fetch_array() to retrieve rows from the result set. In this case, there will only be one row.
It should give you the amount of registere users who have the email address that you provide as the parameter to this query. (Might be a check if the given email address is already registered for another user.)
If the email address is not yet registered, an empty field will be returned. (That might be the reason why nothing gets printed out in your case. Try it with an email address that you are certain of to be in the database.)
$resultemp = mysql_query("select count(*) AS count from registeredUsers where email='{$_SESSION['username']}'");
// Verify mySQL Query Rresult
if (!$resultemp) echo mysql_error();
// Convert mySQL Result for PHP
$counter=mysql_fetch_assoc($resultemp);
$counter=$counter['count'];
// Print Total Employees
echo $counter;
You need to use mysql_fetch_array() to return value in a user defined variable. Then have to print the returned value.
$result=mysql_query("select count(*) from registeredUsers where email='{$_SESSION['username']}'")
$COUNT_NUMBER=mysql_fetch_array($result);
echo "<br>1.Count=" .$COUNT_NUMBER[0];
Try casting it to string before echoing it. As an int, 0 will display as an empty string.

Why does this return Resource id #2? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How do i “echo” a “Resource id #6” from a MySql response in PHP?
I am new at php and SQL and I'm trying to make the php page list the numbers of enries in the table.
I'm using this code but it returns Resource id #2:
$rt=mysql_query("SELECT COUNT(*) FROM persons");
echo mysql_error();
echo "<h1>Number:</h1>".$rt;
Because you get a mysql ressource when you do a mysql_query().
Use something like mysql_fetch_assoc() to get the next row. It returns an array with the column names as indices. In your case it's probably COUNT(*).
Here's a fix and some minor improvements of your snippet:
$rt = mysql_query("SELECT COUNT(*) FROM persons") or die(mysql_error());
$row = mysql_fetch_row($rt);
if($row)
echo "<h1>Number:</h1>" . $row[0];
If you need to get all rows of the resultset use this snippet:
while($row = mysql_fetch_assoc($rt)) {
var_dump($row);
}
Try this:
$rt=mysql_query("SELECT COUNT(*) FROM persons");
echo mysql_error();
$count = mysql_result($rt, 0, 0);
echo $count;
In PHP, resources are returned from certain functions so that they can be passed to other related functions. Examples include database connections, database query results, file-handles, etc.
According to the documentation on mysql_query(), a SELECT query returns a resource. You can take that resource and pass it to a number of different functions. To retrieve a count of the rows, you can use mysql_num_rows(), to retrieve the results of the query, you can use either mysql_fetch_array(), mysql_fetch_assoc() or mysql_fetch_object().
A normal pattern for dealing with database results will look something like this:
$result = mysql_query("SELECT * FROM persons"); // run query against database
$count = mysql_num_rows($result); // retrieve a count of the rows in the previous query
while ($row = mysql_fetch_assoc($result)) { // loop through all the rows in the resultset
// use $row['column_name'] to access columns in your resultset
}
From your example above:
$result = mysql_query("SELECT COUNT(*) AS num FROM persons"); // run query against db
$row = mysql_fetch_assoc($result); // retrieve the 1 (and only) row
$count = $row['num']; // we needed to alias the COUNT(*) column as `num`
mysql_query() doesn't return a value, it returns a resource (see here in the manual).
The returned result resource should be passed to another function for dealing with result tables (like mysql_fetch_array() or mysql_fetch_assoc()), to access the returned data.
Example based on your initial code:
$rt=mysql_query("SELECT COUNT(*) FROM persons");
while($row = mysql_fetch_assoc($rt)) {
var_dump($row);
}
mysql_query returns a resource object. You need to fetch rows from it first (mysql_fetch_row).
Straight from PHP.net.......
"For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error."
From the documentation on mysql_query:
For SELECT, SHOW, DESCRIBE, EXPLAIN
and other statements returning
resultset, mysql_query() returns a
resource on success, or FALSE on
error.

Categories