SQL query doesn't give any results in PHP - php

I am using the following query:
$query = "SELECT (SELECT count(*) FROM survey_ptw WHERE erfh= '0') AS F01,
(SELECT count(*) FROM survey_ptw WHERE erfh='10') AS F02,
(SELECT count(*) FROM survey_ptw WHERE erfh='50') AS F03";
$result = mysql_query($query);
print sprintf('Erf: <table><tr><td>none</td><td>%s</td></tr><tr><td>more</td><td>%s</td></tr></table>', $F01,$F02);
When I'm doing the above query in phpMyAdmin, it displays the variables nicely with the correct result values. Doing the same in PHP however, no results are displayed (empty strings)!
mysql_errno() and mysql_error() don't return errors. The DB has been open and selected further up in the code.
Any idea what's going on?

Because you aren't doing anything with the results.
From the documentation for mysql_query():
The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.
So, to retrieve the results, you can use a while loop as below:
while ($row = mysql_fetch_assoc($result)) {
# code...
}

check $res=mysql_fetch_assoc($result); then print_r(); to check the result. it will work.
$query = "SELECT (SELECT count(*) FROM survey_ptw WHERE erfh= '0') AS F01,
(SELECT count(*) FROM survey_ptw WHERE erfh='10') AS F02,
(SELECT count(*) FROM survey_ptw WHERE erfh='50') AS F03";
$result = mysql_query($query);
$res=mysql_fetch_assoc($result);
$res=$res[0];
sprintf('Erf: <table><tr><td>none</td><td>%s</td></tr><tr><td>more</td><td>%s</td></tr></table>', $res['F01'],$res['F02']);

Related

Why does mysqli_num_rows always return 1 when using SQL AVG() function?

I am developing a voting system and am experiencing an incompatibility problem between the SELECT AVG function and mysqli_num_rows.
When using AVG(), mysqli_num_rows always returns the number 1. However, I need the real number of rows for my if statement. How can I do that?
$consulta_nota_geral = "SELECT * , avg(comp1) as competencia1 , avg(comp2) as competencia2 , avg(comp3) as competencia3 , avg(comp4) as competencia4 , avg(comp5) as competencia5 FROM votos WHERE topic_id = '$topic_id'";
$consulta_nota_geral_conect = mysqli_query($conn,$consulta_nota_geral) or die (mysqli_error($conn));
if(mysqli_num_rows($consulta_nota_geral_conect) > 0) {
//other code here
}
I assume by incompatibility you mean that mysqli_num_rows() returns 1. It is because AVG() groups the rows into one and then computes the average.
If you want to get the real number of rows, you can use COUNT(*).
So, your query would be:
SELECT COUNT(*) as number_of_rows, avg(comp1) as competencia1 , avg(comp2) as competencia2 , avg(comp3) as competencia3 , avg(comp4) as competencia4 , avg(comp5) as competencia5 FROM votos WHERE topic_id = '$topic_id'
Then, you would use mysqli_fetch_row() or mysqli_fetch_assoc() to get the data.
$consulta_nota_geral = "SELECT COUNT(*) as number_of_rows, avg(comp1) as competencia1 , avg(comp2) as competencia2 , avg(comp3) as competencia3 , avg(comp4) as competencia4 , avg(comp5) as competencia5 FROM votos WHERE topic_id = '$topic_id'";
$consulta_nota_geral_conect = mysqli_query($conn,$consulta_nota_geral) or die (mysqli_error($conn));
$data = mysqli_fetch_assoc($consulta_nota_geral_conect);
if($data["number_of_rows"] > 0) {
//your code
}
The sql returns one row because it's using aggregate functions (avg). If you add a count(*) to the select, it will return that with the sql results.

How to count returned rows [duplicate]

I am using count function to get the number of rows buffered in a resultset.
But it always returns count as one even if resultset is empty.
Please see the code below:
$dbhandle = new SQLite3("sqlitedb_111.db");
$selQuery1 = "SELECT id,dbname,tabname,fieldname FROM scan_results ORDER BY id ASC LIMIT 0,10";
$resQuery1 = $dbhandle->query($selQuery1);
print count($resQuery1);
What am I doing wrong and how can I fix this?
As per your comment if you just want to return the count of records you could wrap your query in a SELECT COUNT(*) and change $dbhandle->query to $dbhandle->querySingle. This will work with or without LIMIT.
$dbhandle = new SQLite3("sqlitedb_111.db");
$selQuery1 = "SELECT COUNT(*) FROM (SELECT id,dbname,tabname,fieldname FROM scan_results ORDER BY id ASC LIMIT 0,10)";
$resQuery1 = $dbhandle->querySingle($selQuery1);
print count($resQuery1);
Result is an array. find the size of the array.
$dbhandle = new SQLite3("sqlitedb_111.db");
$selQuery1 = "SELECT id,dbname,tabname,fieldname FROM scan_results ORDER BY id ASC LIMIT 0,10";
$resQuery1 = $dbhandle->query($selQuery1);
$noofrows=sizeof($resQuery1);
echo $noofrows;
SQLite is an embedded database, i.e., there is no client/server communication overhead.
Therefore, it can return the results dynamically; there is only a single row buffered at any time.
To get the number of result rows, you either have to step through the results, or execute something like SELECT COUNT(*) FROM (original query).
Call numRows() on the result set.
From http://php.net/manual/en/function.sqlite-num-rows.php
<?php
$db = new SQLiteDatabase('mysqlitedb');
$result = $db->query("SELECT * FROM mytable WHERE name='John Doe'");
$rows = $result->numRows();
echo "Number of rows: $rows";
?>

Count number of rows buffered in sqlite result set

I am using count function to get the number of rows buffered in a resultset.
But it always returns count as one even if resultset is empty.
Please see the code below:
$dbhandle = new SQLite3("sqlitedb_111.db");
$selQuery1 = "SELECT id,dbname,tabname,fieldname FROM scan_results ORDER BY id ASC LIMIT 0,10";
$resQuery1 = $dbhandle->query($selQuery1);
print count($resQuery1);
What am I doing wrong and how can I fix this?
As per your comment if you just want to return the count of records you could wrap your query in a SELECT COUNT(*) and change $dbhandle->query to $dbhandle->querySingle. This will work with or without LIMIT.
$dbhandle = new SQLite3("sqlitedb_111.db");
$selQuery1 = "SELECT COUNT(*) FROM (SELECT id,dbname,tabname,fieldname FROM scan_results ORDER BY id ASC LIMIT 0,10)";
$resQuery1 = $dbhandle->querySingle($selQuery1);
print count($resQuery1);
Result is an array. find the size of the array.
$dbhandle = new SQLite3("sqlitedb_111.db");
$selQuery1 = "SELECT id,dbname,tabname,fieldname FROM scan_results ORDER BY id ASC LIMIT 0,10";
$resQuery1 = $dbhandle->query($selQuery1);
$noofrows=sizeof($resQuery1);
echo $noofrows;
SQLite is an embedded database, i.e., there is no client/server communication overhead.
Therefore, it can return the results dynamically; there is only a single row buffered at any time.
To get the number of result rows, you either have to step through the results, or execute something like SELECT COUNT(*) FROM (original query).
Call numRows() on the result set.
From http://php.net/manual/en/function.sqlite-num-rows.php
<?php
$db = new SQLiteDatabase('mysqlitedb');
$result = $db->query("SELECT * FROM mytable WHERE name='John Doe'");
$rows = $result->numRows();
echo "Number of rows: $rows";
?>

Get earliest year from multiple tables

I have a couple tables where there is a same field added. What I want to do is get the earliest year from all these records.
Tables:
comics | movies | tv | tv_episodes
Code So Far (Doesn't Work):
function getStartYear() {
include("config.php");
$query = "SELECT DATE_FORMAT(added, '%Y') as `added` FROM (comics,movies,tv,tv_episodes) ORDER BY `added` DESC LIMIT 1";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
return $row['added'];
}
}
Error Returned:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in E:\xampp\htdocs\mydb\functions\common.php on line 94
What would be the most efficient way to do this?
UPDATE
So going by Andrew's answer the new query looks like:
function getStartYear() {
include("config.php");
$query = "SELECT MIN(y) FROM (
SELECT MIN(YEAR(added)) AS y FROM comics
UNION SELECT MIN(YEAR(added)) AS y FROM movies
UNION SELECT MIN(YEAR(added)) AS y FROM tv
UNION SELECT MIN(YEAR(added)) AS y FROM tv_episodes
) AS t1";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
$finalanswer = mysql_fetch_array($result);
return $finalanswer['t1']; // <-- Line 96
}else{
echo mysql_error();
}
}
New Message:
Notice: Undefined index: t1 in E:\xampp\htdocs\mydb\functions\common.php on line 96
Could retrieve it through SQL using a UNION sub-query:
SELECT MIN(y) FROM (
SELECT MIN(YEAR(added)) AS y FROM table1
UNION SELECT MIN(YEAR(added)) AS y FROM table2
...
) AS t1;
First you should be checking to make sure your SQL statement actually returns the desired data. Run the script itself in some sort of SQL viewer (or phpMySQL), or
echo mysql_error();
just to be sure you don't have an invalid SQL statement.
The invalid resource error you're getting indicates to me that the "$result" of your mysql_query function is not a valid resource.
So:
if (!$result = mysql_query($query))
echo mysql_error();
if you do have an error in your query, diagnose and fix and go from there...
As it stands right now, you're doing a "return" from the middle of a loop, which means you're returning the first object found in the result set.
I would consider instead of "looping", do this:
if (mysql_num_rows($result) > 0)
{
$finalanswer = mysql_fetch_array($result);
return $finalanswer['added'];
}
else
echo mysql_error();
error trapping is kind of a nice thing to get in the habit of. :)

SQL Join Statement

I have a simple mysql query which is as following:
SELECT DISTINCT(node.nid) AS nid,
node_counter.totalcount AS node_counter_totalcount,
node.title AS node_title,
node_data_field_dep.field_dep_value AS node_data_field_dep_field_dep_value,
node.type AS node_type,
node.vid AS node_vid,
node_data_field_type.field_type_value AS node_data_field_type_field_type_value
FROM node node
LEFT JOIN node_counter node_counter ON node.nid = node_counter.nid
LEFT JOIN content_field_dep node_data_field_dep ON node.vid = node_data_field_dep.vid
LEFT JOIN content_type_project node_data_field_type ON node.vid = node_data_field_type.vid
WHERE (node.type in ('project')) AND (node.status <> 0)
GROUP BY nid
ORDER BY node_counter_totalcount DESC
so i execute the following statements:
$result = mysql_query($query);
where $query is the above SQL query.
Usually, I use mysql_fetch_array($result) or mysql_fetch_row($result) to access the data, but these are not working now and instead giving some error. Is there any other way to use them. I want to print the data selected in a formatted manner.(Say, a table)
It means your query is not executed, there is some error in it or maybe in the connection.
You can find out what the error is using mysql_error() like this:
$result = mysql_query($myquery) or die(mysql_error());
or you can use
$row = mysql_num_rows($result);
echo($row);
If it returns 1 or higher it means your query is returning results.

Categories