Addition from MySQL query - php

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;

Related

How can I count entries in mySQL database faster?

I am counting the entries in my SQL database:
$sql = "SELECT * FROM files WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute([$id]);
$rowCount =$q->rowCount();
The result of $rowCount is 500000.
But to output this single number takes 5 seconds! Is it possible to get this result faster?
Use the COUNT() function https://dev.mysql.com/doc/refman/8.0/en/counting-rows.html:
$sql = "SELECT COUNT(*) FROM files WHERE id = ?";
Also ensure that 'id' is an indexed column:
https://dev.mysql.com/doc/refman/8.0/en/mysql-indexes.html
Replace * with a field(use auto-increment id) - This will reduce the time a bit.
Index that field. - If you use indexed field the query performance will increase.
SELECT * ..., then counting in PHP, requires shoveling all columns of all rows back to PHP. That's a lot of effort for very little gain.
SELECT COUNT(col) ... does the counting in by MySQL, but it must check for whether col is NULL. And it needs to get at the value of col for every row.
SELECT COUNT(*) ... counts the rows by whatever way is most efficient. This involves looking for the 'smallest' index (or the whole table, if no secondary indexes), and counting through it.
You must learn about INDEXes to get anywhere in databases! This is only one minor use for them.

Is there a more eloquent way of doing these MySQL queries?

I'm making 4 individual queries to a MySQL DB, all of which are identical except the WHERE parameters. 2 of which are:
$totalInvites = mysqli_num_rows(mysqli_query($con, "SELECT code FROM invites"));
$usedInvites = mysqli_num_rows(mysqli_query($con, "SELECT code FROM invites WHERE used IS NOT NULL"));
Is there a way of doing the $totalInvites query and from the returned table, do the WHERE call without doing another query?
If that's confusing, this is an example of what I mean:
$query = mysqli_query($con, "SELECT code FROM invites");
$totalInvites = mysqli_num_rows($query);
$usedInvites = mysqli_num_rows($query /*WHERE used IS NOT NULL*/);
I know that's not proper syntax but that's what I was trying say.
If you just want counts then retrieving the entire database and throwing out the results is not really a good idea. Instead jus task for a count:
SELECT COUNT(*) AS count, used
GROUP BY used
This will give you up to two rows, one count for those that are used and one that isn't presuming used has only NULL or a single non-null value.
Use as little SQL as possible:
SELECT if(used is null, 0, 1) AS used, code
FROM invites
And parse result in PHP according to what you need
SELECT
(SELECT code FROM invites) total
(SELECT code FROM invites WHERE used IS NOT NULL) used

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

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;

select and update mysql same query

I'm running a query to select an array of id's from one table, so that I can update another table with the data from the resulting dataset.
//db query result
$query = "SELECT image_id FROM jos_jxgallery_images ORDER BY jos_jxgallery_images.image_id DESC LIMIT 25";
$query_execute = mysql_query($query);
mysql_close($db_config);
while ($items = mysql_fetch_array($query_execute)) {
echo $items['image_id'];
echo '<br/>';
}
I think I need to do it in the while loop, I just have the echo there to see what's in items variable. That works ok. I think the thing to do is in the while loop..I'd like to replace the 'echoing' with an actual update SET query for my other table. Something like...
while ($items = mysql_fetch_array($query_execute)) {
$q = "UPDATE jx_gallery_images_ratings SET image_id ='".$items."";
mysql_query($q);
But the new table has no data. Is there just a better way to write this...maybe even as one query or something? Any help is appreciated.
EDIT: I should explain a little better. The table is empty, and I could go ahead and use an insert from one table to another just to get the id's there. However, after that...in a way it is somewhat a 'temp' table. But not really. Whatever ordering of image_id's I have created in my SELECT query from my first table (There are other rows to sort by other than image_id, like 'hits', for example)...so the second table needs to be updated with the same ordering of image_id's. Probably be running this several little snippet several times with a cron job. So, yeah, I'm trying to update the second table with the ordering of the SELECT query of the first table and just put the id's in my second table, again...according to the order of the first SELECT query.
If the table is empty, you should do an insert. You can do it in a single query like this:
INSERT INTO jx_gallery_images_ratings (image_id)
SELECT image_id FROM jos_jxgallery_images ORDER BY jos_jxgallery_images.image_id DESC LIMIT 25
Note that you probably wouldn't really need the ORDER BY, adn you could do it for all images at once by removing the LIMIT
Something like:
UPDATE tbl_updateme SET row_to_update = (SELECT row_you_need from tbl_target WHERE tbl_updateme.comparison_row = tbl_target.comparison_row)
INSERT INTO jx_gallery_images_ratings (image_id) (SELECT image_id FROM jos_jxgallery_images ORDER BY jos_jxgallery_images.image_id DESC LIMIT 25)
Or
Easy way is create trigger that updates table after selection with Dynamic SQL

SQLite3 equivalent to mysql_num_rows

What's the equivalent in SQLite3 to mysql_num_rows?
I know SQLite had a similar function call. What I'm doing in PHP is doing a for while fetching an array from the query and counting a variable but I don't like it very much.
You have a changes method that will offer the num rows/affected rows functionality for update/delete methods. For select type queries, you can count the result set or effectively make a second request that will count the result of your previous query (will cost more time to your application).
For a "select users where firstname = 'john'" this should look something like this:
SELECT count(*) FROM ( select users where firstname = 'john' ) as tmp;
But it will cost you an extra query and i'm pretty sure that counting the returned result set will be more efficient.
What about the SQL-query called COUNT?

Categories