I have a row in my mySQL database called "status". In that row i got three different values, either "S", "R" or "L".
Whats the easiest way to count and output the number of occurrences of each value with php?
Thanks!
You can get the counts as separate rows with:
SELECT status, COUNT(*) as count
FROM yourTable
GROUP BY status
You can get them in a single row with:
SELECT SUM(status = 'S') AS s, SUM(status = 'L') AS l, SUM(status = 'R') as r
FROM yourTable
After this, you can read a single row of results:
$row = $pdo->fetch(PDO::FETCH_ASSOC);
$s_count = $row['s'];
$l_count = $row['l'];
$r_count = $row['r'];
It's hard to tell without a full look at your database, but the basic structure is this (assuming you have another row called id)
Edit: to demonstrate in php
$dbc = new mysqli($host, $username, $password, $dbname);
$query = $dbc->query("select id, count(status) as status_count
where status = 'S'
group by id");
$query->fetch_assoc();
$row = $query->fetch_assoc();
echo $row['status_count'];
OR if you have more than one row do it like this:
while ($row = $query->fetch_assoc()) {
echo $row['status_count'];
}
The better way its to use a mysql query using COUNT
You can count all the raws
SELECT COUNT(*) FROM DATABASE
or one raw
SELECT COUNT(colum_name) FROM DATABASE
To be more easy you can give it a variable name like this:
SELECT COUNT (Colum_name) as name FROM DATABASE
So an example,after you connect to your database
Use this:
$ query = mysql_query ('SELECT COUNT (R) as R FROM status');
$ result = mysql_fetch_array ($ query);
Echo $ result ['R']
Hope this will help you !
Related
Can I retrieve 2 different (opposite) results from a single mysql query?
Instead of doing something like this in 2 separate queries:
$sql = "SELECT my_column FROM my_table WHERE id = 1";
/*if num_rows > 0, echo rows from $sql*/
$sql2 = "SELECT my_column FROM my_table WHERE id <> 1";
/*if num_rows > 0, echo rows from $sql2*/
Is it possible to do that in a single query?
Just asking to make sure, in case there's a better method out there to do my queries more efficiently.
If you want all the values in one query, you will need a way to distinguish the results from each other. Thus you need to select the id column as well. For ease of processing, you can also ORDER BY id <> 1 (which will be 0 for id=1, 1 otherwise), which will give you all the results for id = 1 first, followed by all the results for id <> 1:
SELECT id, my_column
FROM my_table
ORDER BY id <> 1
In terms of using this in PHP, you could do something like (assuming mysqli with a connection $conn):
$id_to_find = 4;
$last_id = 0;
$sql = "SELECT id, my_column FROM my_table ORDER BY id <> $id_to_find";
$result = $conn->query($sql) or die($conn->error);
while ($row = $result->fetch_assoc()) {
if ($row['id'] == $id_to_find) {
// do something
}
else {
if ($last_id == $id_to_find) {
// output distinguishing line
}
// do something else
}
$last_id = $row['id'];
}
Because of the ORDER BY clause, this would do all the somethings before all the something elses which would have the same effect as performing the two queries sequentially.
If you want all values from my_table, you may want to try just the
SELECT my_column FROM my_table
This will give all the values where id = 1 and id <> 1.
my MYSQL Database looks like this:
short -- idnumber--position
abc.......8765...........4
def........7453...........1
abc.......7398...........5
def........7542...........2
I have the idnumber and want to Update all with the the same 'short' as the idnumber. Update should be Position-1.
i have idnumber: 8765 its position should be 3 and position of id 7398 should be 4
How do i do it correctly? My Code dont work and i got no echo
<?php
$pdo = new PDO('mysql:host=localhost;dbname=testdb1', 'root', '');
$idV = $_GET['id'];
$statement = $pdo->prepare("UPDATE idtabelle SET position = position-1 WHERE short IN
(SELECT short FROM idtabelle WHERE idnumber = :idV)");
$statement->bindParam(':idV', $idV);
$statement->execute();
while ($row = $statement->fetch(PDO::FETCH_ASSOC))
{
echo $row['short'];
};
?>
try this. you can give a start id.
UPDATE idtabelle
SET position = position -1
WHERE idnumber = 8765
AND position > 2
ORDER BY position ASC;
You're attempting to fetch a row result from an UPDATE statement which doesn't return rows. (Your SELECT subquery is returning it's rows only to the UPDATE query -- the UPDATE result is the only thing returned to you.)
What you should be doing is something like:
...
$statement->bindParam(':idV', $idV);
if ($statement->execute())
echo $statement->rowCount() . " rows updated";
else
echo "Update failed with error: " .print_r($statement->errorInfo(), TRUE);
...
If you need to get the value of "short" in addition to updating, then you should probably do it as two queries instead - a SELECT to get "short", and an UPDATE to update the rows after.
If i try to run your query on sqlfiddle.com i get the error: "You can't specify target table 'idtabelle' for update in FROM clause".
But you can wrap your subquery into another subquery (derived table):
UPDATE idtabelle
SET position = position-1
WHERE short IN (SELECT short FROM (
SELECT short
FROM idtabelle
WHERE idnumber = :idV
) temp);
http://sqlfiddle.com/#!9/7d88a/1
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
I am using a script that has a different way of doing a mySQL query to what I am used to. It starts with:
$query = $db->query("SELECT * etc ..... ");
then
while ($result = $db->fetchArray($query)) {
with variables shown as $result['a'], $result['b']. etc.
All I want to do is count the rows that are selected by the query, but mysql_num_rows doesn't work on $result.
What can I use instead?
You can use the count function to count the rows
$query = $db->query("SELECT count(*) as count from (SELECT * etc ..... ) as sq ");
$result = $db->fetchArray($query);
echo $result['count'];
You can change the query to:
SELECT count(*) as cnt etc .....
Then read the results back from the query.
How would I add up all the integers in the column, _view_count_, on my table, 'videos', then echo it to display on my page?
For example:
if row id 1 has view_count == 328
and
if row id 2 has view_count == 271
How would I make MySQL add those together and echo it out?
You can use MySQL's SUM() and your SQL query would look something similar to:
SELECT SUM(view_count) FROM videos;
To query and echo the value, if you're using mysqli methods in your PHP code, you can use:
$result = $mysqli->query('SELECT SUM(view_count) AS sum FROM videos;');
$row = $result->fetch_assoc($result);
echo $row['sum'];
Assuming you have a $mysqli object defined your code should look like:
$query = "SELECT Sum(view_count) as mySum FROM videos";
$result = $mysqli->query($query);
$row = $result->fetch_assoc($result);
echo $row['mySum'];
SELECT SUM(view_count) FROM videos
Assuming you have a COLUMN id, you can use SUM together with IN, like so:
SELECT SUM(view_count) FROM videos WHERE id in (1,2)