Count how many rows that have a special value in a column - php

I'm trying to count how many rows that have the same value as a variable.
Then I wanna echo out the number that is calculated in the mysql query!
Is this possible?
Here is a image of my database:
http://img812.imageshack.us/img812/333/9jr1.png
Sorry for my bad English and if the question is hard to understand (new to this stuff)

Here it is from your old question
$query= "SELECT pic_name, count(pic_name) as count FROM hulebild_likes where pic_name='$bild_id'";
$likesf = mysqli_query($con, $query);
$row=mysqli_fetch_array($likesf);
echo $row['count'];

There are two different approaches here. If you're looking for a specific value and know it in advance, you can do something as simple as:
select count(*) as count from table where column = 'value';
Alternatively, if you're just looking for a count of duplicate values, you could go with something like:
select count(*) as count, column from table group by column;
That will give you two columns: your column of values and how many occurrences there are of each value.

Execute a SQL query like this:
SELECT COUNT(*) FROM yourtablename WHERE yourcolumnname = yourvariablevalue;

Related

Addition from MySQL query

I am trying to add this:
if (question_counter==10){
$query3 = "SELECT answer_points WHERE participation_id=".$participation_id;
$dbc->query($query3)
}
This is supposed to get all the answer_points where the participation_id = "something". This happens when I receive in my PHP function that question_counter has reached 10
I now want to perform an addition between all the results I receive in my query above so that I can find out a total score and store it as a variable.
How would I go about doing this efficiently?
I thought about writing queries for each answer where I get the participation_id and the question_counter to write the query, store each row result in a separate variable and add all those together. I think this is an overkill and dumb since I will have to write 10 queries to get each row's result.
Anyway this is my Table
You can use MySQL's SUM function.
SELECT SUM(columnName) AS totalScore FROM tableName WHERE id = 34;
Your query is not correct.
$query3 = "SELECT answer_points FROM table_name WHERE participation_id=".$participation_id;
^^^^^^^^^^^^^^^
from and table name
You have forgot from and table name in the query.
To get the sum of the column you need to use the SUM function of mysql.
Here is tutorial of SUM function in mysql.
You have to write query using SUM function
$query3 = "SELECT SUM(answer_points) AS answer_points
FROM TABLE_NAME
WHERE participation_id=".$participation_id;

Any way to select from MySQL table where a field ends in certain character/number?

I am hoping to run a mysql_query where I can select a row if a certain field ends in a number. For example:
<?php
$query = mysql_query("SELECT id FROM table WHERE [ID ENDS IN 0]");
$query = mysql_query("SELECT id FROM table WHERE [ID ENDS IN 1]");
$query = mysql_query("SELECT id FROM table WHERE [ID ENDS IN 2]");
$query = mysql_query("SELECT id FROM table WHERE [ID ENDS IN 3]");
//and so on...
?>
Is there a way to do this? Any help would be great. Thank you!
SELECT ...
WHERE somefield LIKE '%1'
SELECT id FROM table WHERE mod(id, 10) = 1
give it a go
SELECT id
FROM table
WHERE id LIKE '%0'
You can use regular expressions if you need to find if field is ending in a number or not as follows
SELECT id FROM table WHERE id REGEXP '[0-9]$'
Hope it helps...
You could do it with a cast and LIKE, but the performance is likely to be terrible for any non-trivial amount of data (I've not tested in your particular case, but in my experience, casting to string so you can use string operations really slows a query down).
A better way would be to use modulus.
For example, to get all the rows where the numerical field ends in a 4:
SELECT *
FROM table
WHERE MOD(column_of_interest, 10) = 4
Again, I've not benchmarked this, but it's probably going to perform better than casting would.
Of course, if the column type is already a string, then LIKE is the way to go, as using MOD on strings would also require a cast.
You can use LIKE and a wild card expression
it should be somthing like
SELECT id FROM table WHERE id REGEX '%0$'
SELECT id FROM table WHERE id REGEX '%1$'
and so on.
SELECT id FROM table WHERE id REGEXP '1[[:>:]]'

Select on empty table but still get column names

I want to do a SELECT on an empty table, but i still want to get a single record back with all the column names. I know there are other ways to get the column names from a table, but i want to know if it's possible with some sort of SELECT query.
I know this one works when i run it directly in MySQL:
SELECT * FROM cf_pagetree_elements WHERE 1=0;
But i'm using PHP + PDO (FETCH_CLASS). This just gives me an empty object back instead of an row with all the column names (with empty values). So for some reason that query doesn't work with PDO FETCH_CLASS.
$stmt = $this->db->prepare ( $sql );
$stmt->execute ( $bindings );
$result = $stmt->fetchAll ( \PDO::FETCH_CLASS, $class );
print_r($result); // Empty object... I need an object with column names
Anyone any idea if there's another method that i can try?
Adding on to what w00 answered, there's a solution that doesn't even need a dummy table
SELECT tbl.*
FROM (SELECT 1) AS ignore_me
LEFT JOIN your_table AS tbl
ON 1 = 1
LIMIT 1
In MySQL you can change WHERE 1 = 1 to just WHERE 1
To the other answers who posted about SHOW COLUMNS and the information scheme.
The OP clearly said: "I know there are other ways to get the column names from a table, but i want to know if it's possible with some sort of SELECT query."
Learn to read.
Anyway, to answer your question; No you can't. You cannot select a row from an empty table. Not even a row with empty values, from an empty table.
There is however a trick you can apply to do this.
Create an additional table called 'dummy' with just one column and one row in it:
Table: dummy
dummy_id: 1
That's all. Now you can do a select statement like this:
SELECT * FROM dummy LEFT OUTER JOIN your_table ON 1=1
This will always return one row. It does however contain the 'dummy_id' column too. You can however just ignore that ofcourse and do with the (empty) data what ever you like.
So again, this is just a trick to do it with a SELECT statement. There's no default way to get this done.
SHOW COLUMNS FROM cf_pagetree_elements;
This will give a result set explaining the table structure. You can quite easily parse the result with PHP.
Another method is to query the infomrmation schema table:
SELECT column_name FROM information_schema.columns WHERE table_name='cf_pagetree_elements';
Not really recommended though!
You could try:
SELECT * FROM information_schema.columns
WHERE table_name = "cf_pagetree_elements"
Not sure about your specific PHP+PDO approach (there may be complications), but that's the standard way to fetch column headings (field names).
this will list the columns of ANY query for PDO drivers that support getColumMeta. I am using this with SQL server and works fine even on very complex queries with aliased tables, sub-queries and unions. Gives me columns even when results are zero
<?php
// just an example of an empty query.
$query =$PDOdb->query("SELECT * from something where 1=0; ");
for ($i=0; $i<$query->columnCount(); $i++) {
echo $query->getColumnMeta($i)['name']."<br />";
}
?>
Even without PDO in the way, the database won't return the structure without at least one row. You could do this and ignore the data row:
SELECT * FROM cf_pagetree_elements LIMIT 1;
Or you could simply
DESC cf_pagetree_elements;
and deal with one row per field.
WHERE 1=0 does not work for me. It always returns empty set.
The latest PDO for SQLSVR definitely works with get column meta.
Simply set up your statement and use this to get an array of useful information:
$stmt->execute();
$meta= array();
foreach(range(0, $stmt->columnCount() - 1) as $column_index)
{
array_push($meta,$stmt->getColumnMeta($column_index));
}
Complete solution for Oracle or MySQL
for any or some columns (my goal is to get arbitrary columns exactly as they are in DB regardless of case)
for any table (w or w/o rows)
$qr = <<<SQL
SELECT $cols
FROM (SELECT NULL FROM DUAL)
LEFT JOIN $able t ON 1 = 0
SQL;
$columns = array_keys($con->query($qr)->fetchAll(PDO::FETCH_ASSOC)[0]);
if($cols === "*") {
array_shift($columns);
}
YOu could use MetaData with;
$cols = mysql_query("SHOW COLUMNS FROM $tableName", $conn);

Finding the sum of integers from multiple mysql rows in same column

Basically, I have a table for users and a column that stores an integer. I want to take all rows from that table and find the sum of them. The only way I can think to do this would be to loop through all the rows and add them together one by one. However, that seems quite inefficient and I'm sure there's a better way.
Anyone know of one?
SELECT sum(COLUMN_NAME) as total FROM TABLE_NAME
SELECT SUM(column) FROM Users;
Should work. Hope it helps!
Also, refer to http://www.w3schools.com/sql/sql_func_sum.asp.
select SUM(col_1) as sum from table_name GROUP BY col_2
SELECT SUM(column_name) as req_value FROM the_req_table;
It will directly give you the sum

Count rows from results of a "mysql_query"

If I have this:
$results = mysql_query("SELECT * FROM table_name WHERE id=$id");
is there then any way to check how many rows which have a field-value of "Private" or "Company" ?
I need to show the user how many "Private" and "Company" records where found, without making another query. (There is a column called 'ad_type' which contains either "private" or "company")
I already know the mysql_num_rows for counting all rows!
EDIT:
There are 500thousand records! So maybe an iteration through the result is slow, what do you think?
Thanks for all help :)
The above answers are great and all, but the currently checked answer will work very inefficiently should you be dealing with a large amount of data
Example of the above answer (via Gal)
$results = mysql_query("SELECT *,(SELECT COUNT(*) FROM table_name WHERE column=$value) count FROM table_name WHERE id=$id");
It's good and all, and it returns what you need but the obvious design flaw is that making your SQL server return the results then re-return them and look at just the count is very inefficient for large amounts of data.
Simply do this:
$results = mysql_query("SELECT * FROM table_name WHERE column=$value");
$num_rows = mysql_num_rows($result);
It will yield the same results and be much more efficient in the long run, additionally for larger amounts of data.
You can do something like:
$results = mysql_query("SELECT *,(SELECT COUNT(*) FROM table_name WHERE column=$value) count FROM table_name WHERE id=$id");
in order to fetch the number with sql.
If you don't want to change your query you could do a
$results = mysql_query("SELECT * FROM table_name WHERE id=$id");
$count = mysql_num_rows($results);
steps to get a count():
use mysql_query() to get count,
use mysql_fetch_array() to get the only 1 row
get the only one column of the row, this is the count,
here is an example, which check whether the email is already used:
// check whether email used
$check_email_sql = "select count(*) from users where email='$email'";
$row = mysql_fetch_array(mysql_query($check_email_sql));
$email_count = $row[0];
Iterate through the result set of rows and count the number of occurences of Private and Company in ad_type, respectively?
You can do
SELECT COUNT(*) FROM table_name WHERE id=$id GROUP BY fieldvalue HAVING fieldvalue = "Private"
SELECT COUNT(*) FROM table_name WHERE id=$id GROUP BY fieldvalue HAVING fieldvalue = "Company"
but that would be another query. But if you process the data anyway, you could simply sum up the number of "Private" and "Company" rows after doing the query.
In the case you don't have to get all results, use this.
SELECT ad_type, COUNT(*)
FROM table_name
WHERE (id=$id)
GROUP BY ad_type
HAVING ((ad_type = 'Private') OR (ad_type = 'Company'))
If you still have to fetch all the records where id = $id, it won't work. But executing such a query (once) before fetching the real data should be more efficient than using a subquery.
I guess this query would do the job:
SELECT ad_type, count(*) FROM table_name WHERE id=$id GROUP BY ad_type;
I don't see any reason so far to use HAVING, since you probably want to show the user an overview of all the ad_type's found in DB (at least you didn't mention that there are other values for ad_type then the two given).
I also strongly suggest NOT to use sub-queries; always try to use just one.
If there's one thing that will slow your query down, it's a subquery (or subqueries).
Good luck!
Iterate through the results of the query and keep a count of how many of each show up in local variables.

Categories