I am doing the coding in PHP 5.2.17
I want to calculate the number of users whose value for the column named vote is 1
There are 5 things to vote for
when a user votes of a image, the id of the image gets added to the vote (in the above case 1)
So I want to display the statistics i.e. the number of people that voted for images separately.
i.e. the value of the vote should be shown just next to the corresponding image.
help me with the MySQL code and PHP
I tried all types of combinations with count and couldn't get the required result!
this is my latest try
$q = mysqli_query("SELECT count(vote) as Users_who_voted_count FROM data WHERE vote='2'");
$res = mysql_fetch_assoc($q);
echo $res['Users_who_voted_count'];
window.jQuery
First:
do NOT mix mysqli and mysql functions!
Look into the documentation of mysqli and try again.
Second:
Your mysql query should look like this:
SELECT count(*) as Users_who_voted_count,vote FROM data WHERE vote = '2' GROUP BY vote
Related
I'm sure I've done this in the past, but it's a few years ago and I don't remember how it's done and the online tutorials aren't helping.
I have a MySQL database. It has 1 table in it called 'data'. In the 'data' table, there are about 15,000 rows, and 31 columns. I need to extract the data from only 1 of these rows, based on a lookup referencing the string in column 1. When the mysql query finds the correct row, I need every single item read into variables that I can show on my page.
I believe this line is the problem:
$sql = "SELECT Mark,Manufacturer,Model FROM data";
Could someone please let me know what it needs to be changed to, to get the desired result? TIA! :)
you can set options of select query
$sql = "SELECT Mark,Manufacturer,Model FROM data WHERE Model (or manufacturer,mark) = 'some text'";
As my colleges have Explained "where' is your friend!
So you can always query as follows :
Select * from Data
Where column_1 = 'Your Desired String'
Alternatively you could use
Select Discinct Limit 1 Mark,Manufacturer,Model FROM data
Order By Mark Asc
I have a chart script. To know usage I have made a mysql column named first_load. When user visits the page it draws default pie chart. So, if user load the chart by default one entry gets inserted Yes. If use enters his/her preferred data and draw the chart then query inserted No. If I would like to check how many times users loaded the chart for the first time and with user's data. Is it possible to do it in one query? Instead of selecting the table first_load where = yes and no separately and counting the row?
My intention in here to reduce the query.
I can't figure out anything except two different queries
$YesData="Yes";
$NoData="No";
$yesquerys= sprintf("SELECT first_load from 'analytics' where first_load='%s'",$mysqli_real_escape_string($conn,$YesData));
$noquerys= sprintf("SELECT first_load from 'analytics' where first_load='%s'",$mysqli_real_escape_string($conn,$NoData));
I found the answer MySQL: Count occurrences of distinct values I didn't know if we can count occurrences.
So, it would be
SELECT first_load,COUNT(*) as count FROM `analytics` GROUP BY first_load ORDER BY count DESC
How to limit mysql rows to select newest 50 rows and have a next button such that next 50 rows are selected without knowing the exact number of rows?
I mean there may be an increment in number of rows in table. Well I will explain it clearly: I was developing a web app as my project on document management system using php mysql html. Everything is done set but while retrieving the documents I mean there may be thousands of documents.
All the documents whatever in my info table are retrieving at a time in home page which was not looking good. So I would like to add pages on such that only newest 50 documents are placed in first page next 50 are in second and so on.
But how come I know the exact number of rows every time and I cannot change the code every time a new document added so... numrows may not be useful I think...
Help me out please...
What you are looking for is called pagination, and the easiest way to implement a simple pagination is using LIMIT x , y in your SQL queries.
You don't really need the total ammount of rows you have, you just need two numbers:
The ammount of elemments you have already queried, so you know where you have to continue the next query.
The ammount of elements you want to list each query (for example 50, as you suggested).
Let's say you want to query the first 50 elements, you should insert at the end of your query LIMIT 0,50, after that you'll need to store somewhere the fact that you have already queried 50 elements, so the next time you change the limit to LIMIT 50,50 (starting from element number 50 and query the 50 following elements).
The order depends on the fields you are making when the entries are inserted. Normally you can update your table and add the field created TIMESTAMP DEFAULT CURRENT_TIMESTAMP and then just use ORDER BY created, because from now on your entries will store the exact time they were created in order to look for the most recent ones (If you have an AUTO_INCREMENT id you can look for the greater values aswell).
This could be an example of this system using php and MySQL:
$page = 1;
if(!empty($_GET['page'])) {
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
if(false === $page) {
$page = 1;
}
}
// set the number of items to display per page
$items_per_page = 50;
// build query
$offset = ($page - 1) * $items_per_page;
$sql = "SELECT * FROM your_table LIMIT " . $offset . "," . $items_per_page;
I found this post really useful when I first try to make this pagination system, so I recommend you to check it out (is the source of the example aswell).
Hope this helped you and sorry I coudn't provide you a better example since I don't have your code.
Search for pagination using php & mysql. That may become handy with your problem.
To limit a mysql query to fetch 50 rows use LIMIT keyword. You may need to find & store the last row id(50th row) so that you can continue with 51th to 100th rows in the next page.
Post what you have done with your code. Please refer to whathaveyoutried[dot]com
check this example from another post https://stackoverflow.com/a/2616715/6257039, you could make and orber by id, or creation_date desc in your query
I have a web page where people are able to post a single number between 0 and 10.
There is like a lotto single number generation once daily. I want my PHP script to check on the the posted numbers of all the users and assign a score of +1 or -1 to the relative winners (or losers).
The problem is that once I query the DB for the list of the winning users, I want to update their "score" field (in "users" table). I was thinking of a loop like this (pseudocode)
foreach winner{
update score +1
}
but this would mean that if there are 100 winners, then there will be 100 queries. Is there a way to do some sort of batch inserting with one single query?
Thanks in advance.
I'll assume you are using a database, with sql, and suggest that would probably want to do something like
UPDATE `table` SET `score`=`score`+1 WHERE `number`=3;
and the corresponding -1 for losers (strange, can't see a reason to -1 them).
Without more details though, I can't be of further help.
You didn't specify how the numbers were stored. If there is a huge number of people posting, a good option is to use a database to store their numbers.
You can have for example a table called lotto with three fields: posted_number, score and email. Create an (non-unique!) index on the posted_number field.
create table lotto (posted_number integer(1) unsigned, score integer, email varchar(255), index(posted_number));
To update their score you can execute two queries:
update lotto set score = score+1 where posted_number = <randomly drawn number here>
update lotto set score = score-1 where posted_number = <randomly drawn number here>
Let's just assume we have a datatable named posts and users.
Obviously, users contain the data of the gambler (with a convenient id field and points for the number of points they have), and posts contain the post_id ID field for the row, user_id, which is the ID of the user and value, the posted number itself.
Now you only need to implement the following SQL queries into your script:
UPDATE users INNER JOIN posts ON users.id = posts.user_id SET users.points = (users.points + 1)
WHERE posts.value = 0;
Where 0 at the end is to be replaced with the randomly drawn number.
What will this query do? With the INNER JOIN construct, it will create a link between the two tables. Automatically, if posts.value matches our number, it will link posts.user_id to users.id, knowing which user has to get his/her points modified. If someone gambled 0, and his ID (posts.user_id) is 8170, the points field will update for the user having user.id = 8170.
If you alter the query to make it (users.points - 1) and WHERE posts.value != 0, you will get the non-winners having one point deducted. It can be tweaked as much as you want.
Just be careful! After each daily draw, the posts table needs to be truncated or archived.
Another option would be storing the timestamp (time() in PHP) of the user betting the number, and when executing, checking against the stored timestamp... whether it is in between the beginning and the end of the current day or not.
Just a tip: you can use graphical database software (like Microsoft Access or LibreOffice Base) to have your JOINs and such simulated on a graphical display. It makes modelling such questions a lot easier for beginners. If you don't want desktop-installed software, trying out an installation of phpMyAdmin is another solution too.
Edit:
Non-relational databases
If you are to use non-relational databases, you will first need to fetch all the winner IDs with:
SELECT user_id FROM posts WHERE value=0;
This will give you a result of multiple rows. Now, you will need to go through this result, one-by-one, and executing the following query:
UPDATE users SET points=(users.points + 1) WHERE id=1;
(0 is the drawn winning number, 1 is the concurrent id of the user to update.)
Without using the relation capabilities of MySQL, but using a MySQL database, the script would look like this:
<?php
$number = 0; // This is the winning number we have drawn
$result = mysql_query("SELECT user_id FROM posts WHERE number=" .$number);
while ( $row = mysql_fetch_assoc($result) )
{
$curpoints_result = mysql_query("SELECT points FROM users WHERE user_id=" .$row['user_id']);
$current_points = mysql_fetch_assoc($curpoints_results);
mysql_query("UPDATE users SET points=" .($current_points['points'] + 1). " WHERE user_id=" .$row['user_id']);
}
?>
The while construct make this loop to run until every row of the result (list of winners) is updated.
Oh and: I know MySQL is a relational database, but it is just what it is: an example.
I'm wondering what is command for database query that is querying data forward or back between rows? Just like forward and back button. Can someone give me an example? Thanks.
For examp:
$sql_xxxx = mysql_query("SELECT * FROM xxxx WHERE id='$xxx'") or die (mysql_error());
$row_xxxx = mysql_fetch_array($sql_xxxx);
Now I need the two same query but for one forward and in the other backward the data.
Since you tagged PHP and MySQL I think I can guess what you are trying to do;
Usually you can control this with the ID of a record in MySQL, for example:
SELECT * FROM MYTABLE WHERE ID = 1;
In PHP, you can construct dynamic queries to get different results while just changing the value of a variable.
Lets say we now want to take the same query and make it dynamic:
$id = 1;
$query = "SELECT * FROM MYTABLE WHERE ID = $id ";
as long as you execute this query, it will give you the row with ID = 1 , cause now it is taking the value from the $id variable.
If you want the next row, then you execute the same query but now $id must have the next value.
$id = 2;
Having a "NEXT" and "BACK" button can be matter of just adding or substracting 1 to the $id variable.
Still, this is only an example. In most of the cases you should not play with id's like that cause you should not assume that all id's exist, remember that "DELETE" exist;
So you can try to execute better a little query to find the next value like this:
to go foward:
$query= "SELECT MIN(ID) FROM MYTABLE WHERE ID > $id"
// This will get you for sure the closest id next to the current one
and to go back:
$query= "SELECT MAX(ID) FROM MYTABLE WHERE ID < $id"
I hope this helps,
Regards
You can specify a LIMIT in your query, which results in a specific number of rows. For instance, when you end your query with LIMIT 100, 10, you will get 10 results starting at row 100.
This way, you can build prev/next buttons, that when clicked, retrieve the previous or next page of results.
But in most other cases, you will just query everything you need and run through the result set. You do this by querying the result, and fetching each next row of the result.
If you use the LIMIT keyword, the database will happily return a "page" of data, for example;
SELECT * FROM posts ORDER BY post_time LIMIT 40,20; -- will return rows 41-60.
You can make use of that from PHP by just setting the first LIMIT number to page number * page size and the second number to page size (with page number being 0 for the first page). In the example, the page size would be 20 and the page number would be 2 (the third page) and the results will be all the posts from the third page.
There's nothing more to it from the database side, you'll just have to make good use of it from PHP.
if i'm understanding the question correctly, it sounds like you're trying to implement pagination in your queries and you would utilize the 'limit' clause, like so:
SELECT * FROM `your_table` LIMIT 5, 5
This will show records 6, 7, 8, 9, and 10
here's more documentation