php/mysql posting COUNT(*) FROM Poll total yes/no - php

I'm trying to count the yes and no votes so that I can just post the total yes/no for my website. This is should be easy, but I must be missing something somewhere since I don't get a return result. At least no php error. My total vores
$result = mysql_query("SELECT * FROM Poll");
$votes_Poll = mysql_num_rows($result);
$vote_yes = mysql_query("SELECT vote, COUNT(*) FROM Poll GROUP BY yes");
$vote_no = mysql_query("SELECT vote, COUNT(*) FROM Poll GROUP BY no");
// Display the results
echo $votes_Poll;
echo "<br>";
echo $vote_yes;
echo "<br>";
echo $vote_no;
thanks in advance

That's because you're echoing out a query object. Each of your queries should be...
$vote_yes = mysql_query("SELECT COUNT(*) AS total FROM Poll WHERE vote = 'yes' ");
$row = mysql_fetch_object($vote_yes);
echo $row->total; //echoes out the number of yes votes

You are misunderstanding how GROUP BY works. You do not use it to select an answer, it is used to select a field, by which aggregate functions are grouped.
If you use:
SELECT `vote`, COUNT(*) FROM Poll GROUP BY `vote`
Then this will return two results, each with two values, the vote (yes or no) and the count for that vote.
$handle = mysql_query("SELECT `vote`, COUNT(*) AS `count` FROM Poll GROUP BY `vote` ORDER BY `vote` DESC");
if ($handle) {
$results = mysql_fetch_assoc($handle);
echo ($results[0]['count'] + $results[1]['count']) . "<br>" . $results[0]['count'] . "<br>" . $results[1]['count'];
}
NB. Using the ORDER BY vote DESC part, that forces the order to yes then no (reverse alphabetical) and then you do not have to check which row is which.

Related

How to mysqli_fetch_row while using mysqli_multi_query

I'm trying to get the latest info about some specific person, and I'm using a query like
SELECT * FROM Table WHERE Name LIKE 'Peter' ORDER BY ID DESC LIMIT 1
and
SELECT * FROM Table WHERE Name LIKE 'Mary' ORDER BY ID DESC LIMIT 1
because in the Table each day will insert new data for different person at the instant of updating it (for record reference), so I would like to print out a few persons latest info by "ORDER BY ID DESC LIMIT 1"
I have tried to print it out with "mysqli_multi_query" and "mysqli_fetch_row"
like
$con=mysqli_connect($localhost,$username,$password,'Table');
$sql = "SELECT * FROM Table WHERE Name LIKE 'Peter' ORDER BY ID
DESC LIMIT 1 ";
$sql .= "SELECT * FROM Table WHERE Name LIKE 'Mary' ORDER BY ID
DESC LIMIT 1";
// Execute multi query
if (mysqli_multi_query($con,$sql))
{
do
{
// Store first result set
if ($result=mysqli_store_result($con)) {
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
echo '<tr>'; // printing table row
echo '<td>'.$row[0].'</td>';
echo '<td>'.$row[1].'</td>';
echo '<td>'.$row[2].'</td>';
echo '<td>'.$row[3].'</td>';
echo '<td>'.$row[4].'</td>';
echo '<td>'.$row[5].'</td>';
echo '<td>'.$row[6].'</td>';
echo '<td>'.$row[7].'</td>';
echo '<td>'.$row[8].'</td>';
echo '<td>'.$row[9].'</td>';
echo '<td>'.$row[10].'</td>';
echo '<td>'.$row[11].'</td>';
echo '<td>'.$row[12].'</td>';
echo '<td>'.$row[13].'</td>';
echo '<td>'.$row[14].'</td>';
echo'</tr>'; // closing table row
}
// Free result set
mysqli_free_result($result);
}
}
while (mysqli_next_result($con));
}
mysqli_close($con);
?>
In the result page , it doesn't show any error message , but no results are printed.
The individual queries were tested.
Please advise, much thanks
Is there another way to keep the query simple, so there is no need to use mysqli_multi_query?
Best practice indicates that you should always endeavor to make the fewest number of calls to the database for any task.
For this reason, a JOIN query is appropriate.
SELECT A.* FROM test A INNER JOIN (SELECT name, MAX(id) AS id FROM test GROUP BY name) B ON A.name=B.name AND A.id=B.id WHERE A.name IN ('Peter','Mary')
This will return the desired rows in one query in a single resultset which can then be iterated and displayed.
Here is an sqlfiddle demo: http://sqlfiddle.com/#!9/2ff063/3
P.s. Don't use LIKE when you are searching for non-variable values. I mean, only use it when _ or % are logically required.
This should work for you:
$con = mysqli_connect($localhost,$username,$password,'Table');
// Make a simple function
function personInfo($con, $sql)
{
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
echo '<table>
<tr>';
for($i=0; $i < count($row); $i++) echo '<td>'.$row[$i].'</td>';
echo '</tr>
</table>';
}
}
}
$sql1 = "SELECT * FROM Table WHERE Name='Peter' ORDER BY ID DESC LIMIT 1 ";
$sql2 = "SELECT * FROM Table WHERE Name='Mary' ORDER BY ID DESC LIMIT 1";
// Simply call the function
personInfo($con, $sql1);
personInfo($con, $sql2);

How can i simplify this php mysql count code and reduce queries?

I have database with 8 different product category for download.
pic, app, ebo, tem, des, cod, mus, cat
I'd like to count clients total downloaded products and total downloads of each product category.
Maximum daily limit downloads for category product is 3.
When user log in should see how many downloads remain.
Here is working code
$query = "SELECT COUNT(*) as sum FROM service_downloads where client_id like '$client'";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result))
{
echo "You have downloaded". $row['sum'] ." products.";
echo "<br />";
}
$query = "SELECT COUNT(*) as sum FROM service_downloads where client_id like '$client' and product like 'pic'";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result))
{
echo "". $row['sum'] ." downloaded pictures";
$leftovers = 3 - $row['sum'];
echo " $leftovers pictures remain for download";
echo "<br />";
}
$query = "SELECT COUNT(*) as sum FROM service_downloads where client_id like '$client' and product like 'app'";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result))
{
echo "". $row['sum'] ."downloaded applications";
$leftovers = 3 - $row['sum'];
echo " $leftovers applications remain for download.";
echo "<br />";
}
$query = "SELECT CO.... This procedure repeat eight times for different product category.
result
You have downloaded 12 products.
3 downloaded pictures 0 pictures remain for download.
1 downloaded applications 2 applications remain for download.
3 downl.......
You could use a GROUP BY statement to group your results.
SELECT COUNT(`Product`) AS `Sum`, `Product`
FROM `service_downloads`
WHERE `client_id` = '<client_id>'
GROUP BY `Product`
Then you can use one while statement to loop through each product:
// Print out result
while($row = mysql_fetch_array($result))
{
echo "". $row['Sum'] ."downloaded " . $row['Product'];
$leftovers = 3 - $row['Sum'];
echo " $leftovers " . $row['Product'] . " remain for download.";
echo "<br />";
}
$query = "SELECT COUNT(*) as sum,product FROM service_downloads where client_id like '$client' GROUP BY product";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result))
{
echo "You have downloaded". $row['sum'] ." ".$row['product'];
echo "<br />";
}
This should work
You should breakdown the quantity of downloads per category in one query:
SELECT product,COUNT(*)
FROM service_downloads
WHERE client_id like '$client';
I also don't think you need to use LIKE; you probably want to use =
You can get a single result set with all the sums in it with this query.
SELECT COUNT(*) as sum, product
FROM service_downloads
WHERE client_id = '$client'
AND PRODUCT IN ('pic', 'app', 'abc', 'def', 'ghi')
GROUP BY product WITH ROLLUP
ORDER BY product NULLS FIRST
This will give you one row for each specific product and a summary (rollup) row with a NULL value in the product column.
If this query takes a long time create an index on (client, product) and it should go pretty fast.
If you are showing this data frequently, which is what it sounds like, then you should have a separate table that represents those SUMs and is index by CLIENT_ID.
You can then increment/decrement that value each time you add a new entry.
For example, when you add a new row to service_downloads with an entry in 'pic' for CLIENT_ID 1, then you would also increment this shortcut table:
UPDATE service_counts SET pic=pic+1 WHERE client_id=1;

how to count the total comment

I want to count the total comment/post posted on my page. i have a table in my database named test. within table i have a column named comment, where every post is been stored. the problem am having is to echo out the total number of comment and keep updating as viewers keep on posting there comment and i tried using this code
<?php
$handle = mysql_query("SELECT `comment`, COUNT(*) AS `count`
FROM test GROUP BY `comment` ");
if ($handle) {
$results = mysql_fetch_assoc($handle);
echo ($results[0]['count'] + $results[1]['count']);
}
?>
but it keep on echoing out 0. pls help me out.
Try this:
list($count) = mysql_fetch_row(mysql_query("select count(*) from `test`"));
echo $count;
Alternatively, if you are already running a query to get some comments, you can try this:
$sql = mysql_query("select sql_calc_found_rows * from `test` order by `id` desc limit 10");
// ^ Get the 10 most recent comments
list($count) = mysql_fetch_row(mysql_query("select found_rows()"));
// this avoids having to run the entire query again, great for efficiency!
while($comment = mysql_fetch_assoc($sql)) var_dump($comment); // just an example

Getting extra data in MYSQL count query

Hi all i've had help from bluefleet (BF) with a mysql query which i've now put in a php file, the query works fine but i find i need to get extra data as well as the count, so what i need is when a match is found i need to look up the username in table tview3.
Whichever table the ip match is found there will be a column called UID, in the table tview3 there will also be a column called USERNAME, what i'd like to do is get the username(s) for the matches and then use them in a text file.
I have to state i'm a complete newbie at this, all help is appreciated
$myquery= "select sum(total)
from
(
SELECT count(*) as total
FROM " .TABLE_PREFIX."tview v
where v.ipaddress = '$ips'
union all
SELECT count(*) as total
FROM " .TABLE_PREFIX."tview2 v1
where v1.ipaddress = '$ips'
union all
SELECT count(*) as total
FROM " .TABLE_PREFIX."tview3 v3
where v3.ipaddress = '$ips'
) src";
$result = mysql_query($myquery);
$rowCount = mysql_num_rows($result);
If($rowCount !=0){
echo "NOT EMPTY";
}else{
echo "EMPTY";
}
mysql_free_result($result);
$UAM = strtoupper($_SERVER['HTTP_USER_AGENT']);
$ips = strtoupper($_SERVER['REMOTE_ADDR']);
$fp = fopen("logtext.txt", "a");
$DateOfRequest = date('m-d-Y H:i:s');
fwrite($fp, "$DateOfRequest . \nMatched Member: . $username . \nWith User Agent: . $UAM . \n\nIP: . $ips . \n\n");
So i'd like to populate a variable $username with the username(s) where the matches were found.
Regards,
Silo
Change:
SELECT count(*) as total
to
SELECT count(*) as total, username
Then you could do something like:
$row = mysql_fetch_array($query);
$username = $row['username'];
Hope that helps. Also check out this question for a bit more detail: How do I find the most common result in a column in my MySQL table

How to print or echo rows when using COUNT(*) and SUM()

I generated the below query for php using PHP-MYADMIN,
My question is how to print the 30 rows it generates? when i use "see quote" it just errors out.
i am trying to echo the rows with search term and count in < div >< /div > tags each in its own.
Facebook 38 searches
Another Feed 25 searches
Timeline 18 searches
and so on to row 30.
$result=mysql_query($sql)
$sql = 'SELECT COUNT(*) AS `Rows`, `search`, SUM(searched) FROM `af_timeline_search` GROUP BY `search` ORDER BY SUM(searched) DESC LIMIT 0, 30 ';
/* top searches */
$sqlthis = mysql_query('SELECT COUNT(*) AS `Rows`, `search` FROM `af_timeline_search` GROUP BY `search` ORDER BY `Rows` DESC');
$num=mysql_num_rows($sqlthis);
$arrS = mysql_fetch_array($sqlthis);
$i=0;
while ($i < $num){
echo 'Search '.$arrS[$i].'';
$i++;
}
Screen Shot of Query in PHPmyadmin.
I think the best you can do is to take a look at this: mysql-fetch-array
There you'll find the answer on how to loop over that array :)
$result = mysql_query("SELECT * FROM YOURDATABASE");
while($row = mysql_fetch_array($result))
{
echo $row['search'] . " " . $row['somenumber'];
echo " searches";
}
mysql_close($con);
I have found the solution to this. Thank you all for your guidance. :-) "you all rock"
$sql = "SELECT COUNT(*) AS Rows, search, SUM(searched) FROM anotherfeed.af_timeline_search GROUP BY search ORDER BY SUM(searched) DESC";
$result=mysql_query($sql) or die ('Error! yo.');
$row = mysql_fetch_array($result);
echo '<pre>';
print_r($row);
echo '</pre>';
/* top searches with loop */
$sql = "SELECT COUNT(*) AS Rows, search, SUM(searched) FROM anotherfeed.af_timeline_search GROUP BY search ORDER BY SUM(searched) DESC LIMIT 0, 20";
$result=mysql_query($sql) or die ('Error! yo.');
while($row = mysql_fetch_array($result))
{
echo ' (';
echo urldecode($row['search']) . " " . $row['SUM(searched)'] . "";
echo ') ';
}
I am able to print the array, hopefully i can get the loop down with a while statement. Feel free to add a loop if you have or know one that is better... Thank You.

Categories