How to look at the result of a query - php

I have a SQL Query, although it is executing, but how should i verify if it is giving me the desired result.
For example: My query
$query3 = "SELECT COUNT(DISTINCT(uid)) AS `num`
FROM `user_info`
WHERE date(starttime)='2011-10-10'";
In the above query i am trying to count the number of distinct user ID's(uid) from the table named user-infowhere date is 2011-10-10.
How should i display the count which is calculated for the given date?.I need to know it and perform some further operations on it!

$query3 = "SELECT COUNT(DISTINCT uid) AS `num`
FROM `user_info`
WHERE date(starttime)='2011-10-10'";
$result = mysql_query($query3);
$row = mysql_fetch_array($result);
echo $row['num'];

Just do:
SELECT COUNT(DISTINCT uid) AS `num`
FROM `user_info`
WHERE date(starttime)='2011-10-10'
This SO post goes into some details about how count and count(distinct ...) work. With just count, there is a hidden/assumed function of count(all ... ) actually happening (it's just the default value). If you want to only count distinct things, switch it to the non-default and do the count(distinct ...) instead. I didn't know it existed for my first 6 months of writing sql or so...

You can set a variable sing the result...
SET #userVar=SELECT
COUNT(DISTINCT uid)
FROM
user_info
WHERE
DATE(starttime)='2011-10-10';
Then you can use that variable in your next operation or query.

Related

How to assign two SELECT queries results to single array variable($row)?

There are two queries with same fields names but different tables. I want fetch both select query's results in same array variable $result. I tried few things but nothing working for me. May b my bad day.
two table, need to be fetch in same variable $result.
$sql1="SELECT city,phone,name from table1 where city='NY'";
$result = $conn->query($sql1);
$sql2="SELECT city,phone,name from table2 where city='NY'";
$result = $conn->query($sql2);
I don't want $result lost $sql1 data after assigning same variable ($result) to second query. Please help
You can use UNION and along with that table record identifier to identify table records differently.
$sql1 = "(SELECT city,phone,name, 't1' ttype from table1 where city='NY')
UNION (SELECT city,phone,name,'t2' ttype from table2 where city='NY')";
$result = $conn->query($sql1);
Note: MySQL uses the DISTINCT clause as default when executing UNION queries if nothing is specified.
If you want duplicate records too, then use UNION ALL.
$sql1="SELECT city,phone,name from table1 where city='NY'
UNION
SELECT city,phone,name from table2 where city='NY'";
$result = $conn->query($sql1);

PHP MySQL combine multiple fetchcolumn into a single query

I've currently got a table with users and variable user status (1, 2, 3, 4, 5 etc). I am currently calculating the number of users in each status separately
$query = "SELECT COUNT(*) FROM users WHERE status = 1";
$result = $pdo->query($query);
$users1 = $result->fetchColumn();
$query = "SELECT COUNT(*) FROM users WHERE status = 2";
$result = $pdo->query($query);
$users2 = $result->fetchColumn();
etc
I could get a fetch, then loop through all the results and add each status but I was wondering if there is a better way to do it with a query?
You can use group by and get the list with the count
SELECT status, COUNT(*) as my_count FROM users group by status;
NB with this you can't use fetchColumn .. but fetchRow .and access by key
you jsut need to add status as group by
SELECT COUNT(*),status FROM users group by status

Add MySQL Count Column to PHP/HTML Table

I'm developing a website using HTML, PHP and MySQL to access a database. On one page I present a table with data from that database. This is some of the code I'm using:
$sql1 = "SELECT * FROM MyTable ORDER BY ID ASC";
$rs1 = mysqli_query($link,$sql1);
(...)
while($row1 = mysqli_fetch_assoc($rs1)) {
echo "<tr><td>".$row1['ID']."</td><td>".$row1['Field1']."</td><td></td><td>".$row1['Field2']."</td><td>".$row1['Field3']."</td></tr>\n" ;
}
Notice the empty <td></td>? That's because I want to have there the number of time a given ID appears on two other tables (there are foreign keys involved, obviously). I have sorted out the code I need for that:
$sql2 = "SELECT (SELECT COUNT(*) FROM MyTable2 WHERE ID2=$row1['ID'])+(SELECT COUNT(*) FROM MyTable3 WHERE ID2=$row1['ID']) AS total";
However, I'm struggling with figuring out a way to add this result to the other table. Any help?
try with this.. it inserts the total to an table after selecting the count.
"INSERT INTO total_table (total)
SELECT (SELECT COUNT(*) FROM MyTable2 WHERE ID2=$row1['ID'])+(SELECT COUNT(*) FROM MyTable3 WHERE ID2=$row1['ID']) AS total
WHERE cid = 2"

What columns do I select if I only want a count

I want to count the results in my table... but I am usually confronted with a decision, what column do I select? Should I select the primary key? Wild Card? What has the most performance? Does it matter? Below is an example of how I call it
// Wild Card, I feel like this is the worst one for performance?
$query = "SELECT * FROM table WHERE status = ?";
// Only selecting one column? Is there a better way
$query = "SELECT id FROM table WHERE status = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('i',$status);
$stmt->execute();
$stmt->store_result();
$returned_amount = $stmt->num_rows;
$stmt->free_result();
$stmt->close();
Well, if you want MySQL to handle the count, you can just do the following
$query = "SELECT COUNT(*) as count FROM `table` WHERE `field` = ?";
The as count part means that you can access the count as if it were a column.
You should SELECT COUNT(`id`) FROM `table` WHERE `status`=?, much more efficient ;)
If you are willing to count all the results of your query (ie: for pagination), you can use FOUND_ROWS() option:
In your main query you need to add SQL_CALC_FOUND_ROWS option just after SELECT and in second query you need to use FOUND_ROWS() function to get total number of rows.
SELECT SQL_CALC_FOUND_ROWS id FROM table WHERE status = 'something' LIMIT 10;
SELECT FOUND_ROWS();
More info in dev.mysql.com

Single mysqli query statement to get total number of rows and limit also

I want to fetch the total count of records in MySQL db table and also use the limit with this. For example, there are 100 rows and the limit I want to use let suppose is 10. I know how to do this using two queries but I want to do this in one go.
SELECT count(*) as total_rows FROM mytable; // gets the total count of rows
SELECT col1,col2 FROM mytable LIMIT 0, 10; // gets the 10 rows of col1,col2
I want to do this in one go. Any idea.
Thanks.
Here is the SQL Fiddle that demonstrates how the below works:
SELECT m.*,
(
SELECT COUNT(*)
FROM mytable AS sm
) AS TotalCount
FROM (
SELECT mt.col1, mt.col2
FROM mytable AS mt
LIMIT 0, 10
) AS m
Have a look at Shayan Husaini's answer on How to get the total row count with MySQLi
I have updated his original answer after trying it out myself. You have to add "SQL_CALC_FOUND_ROWS" after SELECT in your query and add a second query as shown in the code snippet below.
$sql1 = "SELECT SQL_CALC_FOUND_ROWS col1,col2 FROM mytable LIMIT 0, 10";
$sql2 = "SELECT FOUND_ROWS()";
$result1 = $conn->query($sql1);
$result2 = $conn->query($sql2);
$TotalRcount = $result2->fetch_row();
// I have added this next line to correct the answer
$TotalNumRows = $TotalRcount[0];
You can use $result1 to access your results as you normally would.

Categories