How can I combine two MySQL rows as one and count results? - php

Basically, I have a database with 10 exam types. Each type has two parts, and is updated as pass or fail. I need to list the total count of exams that have not been completed (both parts passed).
I've tried this and it returns the count if either part shows pass, not both.
$query = sprintf(
"SELECT * FROM candidate_exams
WHERE gID='1' AND canID='%d' AND exResult='y'
GROUP BY gEID",
(int) $canID
);
$result = $con->query($query);
$rowCount = 10 - mysqli_num_rows($result);
'gID' is an identifier that tracks what group these 10 exams come from,
'canID' is a candidate identifier,
'gEID' is an exam type.

SELECT COUNT(*) FROM tabele WHERE type_a = 'fail' OR type_b = 'fail'
something like this?
It would help a lot to see your table structure to be able to answer this question properly.

Related

How do I count unique rows in php pdo?

Here's my usual way of counting rows...
$query = "SELECT * FROM users";
$stmt = $db->prepare($query);
$stmt->execute();
$count = $stmt->rowCount();
This will count all rows, even if I use a WHERE clause, it'll still count every row that meets that condition. However, let's say I have a table, we'll call it tokensEarned (that's my actual table name). I have the following data...
user_id = 1,2,4,5,8,8,2,4,3,7,6,2 (those are actual rows in my table - clearly, user 1 has 1 entry, 2 has three entries, etc.) In all, I have 12 entries. But I don't want my query to count 12. I want my query to count each user_id one time. In this example, my count should display 8.
Any help on this? I can further explain if you have any specific questions or clarification you need. I would appreciate it. Thank You.
The following query will yield the distinct user count:
$query = "SELECT COUNT(DISTINCT user_id) AS cnt FROM users";
$stmt = $db->prepare($query);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo "distinct user count: " . $row['cnt'];
It isn't possible to get all records and the distinct count in a single query.
Whether you use the query above or you return all the actual distinct rows really depends on whether you need the full records. If all you need are the counts, then it is wasteful to return the data in the records, and what I gave above is probably the best option. If you do need the data, then selecting all distinct rows might make more sense.
You can use distinct in mysql to select only unique fields in your table.
$query = "SELECT distinct user_id FROM users";
$stmt = $db->prepare($query);
$stmt->execute();
$count = $stmt->rowCount();
Change your query to the following, this way you only shows the unique user_id:
$query = "SELECT DISTINCT user_id FROM users";

Count rows, or keep int field for counting?

When I want to find out how many shoes Alfred has, I always count the rows in the table "usershoes" where the userid matches Alfred's
But since I switched to PDO, and select row count is not simple or bulletproof/consistent, I'm reconsidering my methods
Maybe I should instead keep an int field "shoes" directly in table "users", keep number of shoes there, and then increase/decrease that number for that user along the way? Feels not right..
If anyone has a solid method for simple row counting on an existing select query, without extra query, let me know
Try something like this
SELECT COUNT(*) FROM usershoes
WHERE userid="theIdOfTheUser";
I could not get count(fetchColumn()) or fetchColumn() to work correctly (outputted 1 when 0 was the real number)
So now I'm using this, and it works:
$sql = 'SELECT COUNT(*) as numrows, shoecolor FROM usershoes WHERE userid = ?'
$STH = $conn->prepare($sql);
$STH->execute(array($someuseridvar));
And then:
$row = $STH->fetch();
if ($row['numrows'] > 0) {
// at least one row was found, do something
}
With MySQL, you can use FOUND_ROWS():
$db = new PDO(DSN...);
$db->setAttribute(array(PDO::MYSQL_USE_BUFFERED_QUERY=>TRUE));
$rs = $db->query('SELECT SQL_CALC_FOUND_ROWS * FROM table LIMIT 5,15');
$rs1 = $db->query('SELECT FOUND_ROWS()');
$rowCount = (int) $rs1->fetchColumn();
$rowCount will contain the total number of rows, not 15.
Taken from:
http://php.net/manual/en/pdostatement.rowcount.php#83586

Find out how often a value is between 2 dates in mysql

Hi with the follow code I request what dates are all in my database without duplicates.
Then I save it to an array. In the array I also need an other value.
The value I need is how much users are in one day in the database without duplicates.
For Example the array must later lookslike 23.07.2013 - 10, 24.07.2013 - 50 (users).
I search for several hours but I don't find a good mysql query.
$query = "SELECT id, user, timestamp FROM stat WHERE timestamp BETWEEN '$datum1' AND '$datum2' GROUP BY timestamp";
$result = mysql_query($query,$db);
while($row = mysql_fetch_assoc($result))
{
mysql_num_rows($result);
$dataset1[] = array(strtotime($row['timestamp']),$number_of_users_on_this_day);
}
Try:
$query = "SELECT id, user, COUNT(*) as count FROM stat WHERE timestamp BETWEEN '$datum1' AND '$datum2' GROUP BY timestamp";
This will return the number of entries in the value 'count'
if you want distinct data, in place of * use
COUNT(DISTINCT id)
with whatever field you want to be unique in place of 'id'

A mySQL count query to return a numeric value?

I have a database set up with a few hundred customers in, all of them are unique. However, some customers are linked together, if they are part of a family. E.g.
I have a family ID that links these customers, e.g. Mrs A. Jones is customer number 005 and Mr B.Jones is customer number 017 and as they are related, I have assigned them family ID 001.
I've searched online, but no where seems to be that useful at providing me with any assistance into how I could do some sort of mySQL count to echo the number of people WHERE familyID = 001.
Also, is there any way, I could return both seperate customer records, given the mySQL search criteria of familyID = 001.
Many thanks,
Tom.
EDIT: Realised I'd put passenger instead of customers, my bad! Also, the names are made up for obvious DPA reasons :)
You want the COUNT() function
SELECT count(*) AS count FROM customers WHERE familyID="001"
You can replace the * with a column name, makes it a little faster.
$sql='SELECT count(familyID) AS count FROM customers WHERE familyID="001"';
Here you can get number of customers of familyID= 001
But where is this passenger came from? what is the relation with customer?
If it is about customer not passenger then
$sql='SELECT * FROM customers WHERE familyID="001"';
$query=mysql_query($sql);
$count=mysql_num_rows($query);
while($fetch_arr=mysql_fetch_array($query)){
$familyName=$fetch_arr['name'];
echo $familyName;
}
You can get all records from * and from $count u can get number of customers
You can use the count Function in such cases .it can be used as.
Select count(*) form TABLE NAME where familyID = "001"
If you want the unique records as well as the count use this, with the OVER function:
SELECT customers.id,
customers.additional_columns,
count(1) OVER (PARTITION BY familyID) AS count
FROM customers
You can do something like
$result = mysql_query("SELECT * FROM families where familyID='001'", $link);
$num_rows = mysql_num_rows($result);
source
For your first question, this will do
$result = #mysql_query("SELECT * FROM tbl_name WHERE familyID = '001'");
echo mysql_num_rows($result); //This line should display the count

Look at array and count true or false from duplicate values

I have a table in SQL, where users can answer many times (the same users and different users). I want to count how many true or false values there are.
For example, like user 1 has 5 rows in my table, 3 times true, and 2 times false and user 9 has got 10 true and 1 false like that but I would not know what user numbers.
I would like output like
User 1 - 5x True 1x False, User 4 1x True 3x False etc. But I would not know what user and the user list can grow.
there is a simple (not recommended) solution using a loop:
$resultq = mysql_query('select value, user_id from answers');
$answers_per_user = array(); // positive answers per user
$totals_per_user = array(); // total answers per user
while($result = mysql_fetch_assoc($resultq)){
if($result['answer'])
$answers_per_user[$result['user_id']] += $result['answer']; // increment positive answer counter for user
$totals_per_user[$result['user_id']]++;
}
you would have an array holding positive answers per user and total answers per users which you can then use to calculate negative answers
the recommended solution is to use a group by sql statement that gives you all the calculated information.
$result = mysql_query('select sum(value) as positivecount, count(*) as total, user_id from answers group by user_id');
while($data = mysql_fetch_assoc($result)){
// $data will hold positivecount,total, and user_id giving you all the data you need for calculating negative answer values.
}
// alternatively, use a query like this for counting the answers that were 'beans':
// select sum(if(value = "beans", 1, 0)) as answered_beans, count(*) as total, user_id from answers group by user_id
see: http://dev.mysql.com/tech-resources/articles/wizard/page3.html
The most elegant solution for this problem is to actually have two SQL tables; one with one row for each user (userID, username, etc.) and one for each vote, wich could be multiple per user.
The following example will echo some information about the data.
<?php
$sqlusers = mysql_query("SELECT userid FROM user_table")//This line grabs all users from the database.
$users = mysql_fetch_array($sqlusers);//This line creates an array containing all users.
foreach($users as $key=>$currentuser){
$sqlvotes = mysql_query("SELECT userid, vote FROM vote_table WHERE userid = $currentuser[userid]");
$votes = mysql_fetch_array($sqlvotes);//obtain an array of votes the current user has submitted
$votefrequency = array_count_values($votes)//counts the amount of trues and falses in the $votes array, and returns an array with the [true] and [false] indexes containing their respective frequency.
echo "user ".$userid." has voted ".$votefrequency[true]." times true and ".$votefrequency[false]." times false/n";
echo "average vote:". (($votefrequency[true] - $votefrequency[false] > 0) ? "true" : "false" );
}

Categories