How to count the most common value in SQL? - php

At the moment I've got the following code:
$forummost = mysql_query("
SELECT door,
COUNT(door) AS doorCount
FROM forum_posts
GROUP BY door
ORDER BY COUNT(door)
DESC
");
$forummostc = mysql_num_rows($forummost);
$forummostf = mysql_fetch_assoc($forummost);
Can somebody explain me why mysql_num_rows($forummost) doesn't work?
Thanks in advance!

GROUP BY selects only the different values of that column in mysql. In your case, as pointed out, it selects as many rows as different door values are there.

mysql_num_rows counts the number of rows returned by the query. Your query is what is the count for each door so only one row for each door is returned.

try this, I tested, it works..
<?php
$link = mysql_connect('localhost','root','');
if (!$link)
{
die('Could not connect to MySQL: ' . mysql_error());
}
echo 'Connection OK'."</br>";
$forummost = mysql_query("
SELECT door,
COUNT(door) AS doorCount
FROM forum_posts
GROUP BY door
ORDER BY COUNT(door)
DESC
");
$forummostc = mysql_num_rows($forummost);
if ($forummostc == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($forummost)) {
echo $row["door"];
echo $row["doorCount"];
}
mysql_free_result($forummost);
mysql_close($link);
?>

Related

insert query not inputing 1 million results

I am having trouble cross computing and inserting the results from 2 different tables into another one,
table structure
2_o contains 210 results
4_e contains 5985 results
all_combinations should theoretically contain after cross computing the results 210 * 5985 =
1,256,850 results
my query is working thus my only problem is that its not reaching the result that it should 1,256,850 and it seems that its not finishing and cutting every time on a different total. no idea why. 1,247,102 or 1,153,550 etc...
<?php
$sql = mysql_connect("localhost", "root", "mysql");
if (!$sql) {
die("Could not connect: " . mysql_error());
}
mysql_select_db("numbers");
$result = mysql_query("INSERT INTO all_combinations (o1,o2,e1,e2,e3,e4) SELECT n2.o1, n2.o2, n4.e1, n4.e2, n4.e3, n4.e4 FROM 2_o AS n2, 4_e AS n4");
echo "done";
if (!$result) {
die("Could not input results. " . mysql_error());
}
?>

how to get the number of rows in a table that come after a row with a specific id?

how do i get the number of rows in an sql table that come after a row with a specific id with php? I want to get the number of rows that come after the row with an id of 6.
Select count(*) from TableName where ID > 6
The SQL for a query to count the rows with an ID greater than 6, assuming your table is named table and the ID column is named id will be:
SELECT count(*) FROM table WHERE id > 6;
To do this from PHP, you can modify the example in the docs to add your own query. The output could also be tweaked to return a scalar value.
<?php
// Connecting, selecting database
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
or die('Could not connect: ' . mysql_error());
echo 'Connected successfully';
mysql_select_db('my_database') or die('Could not select database');
// Performing SQL query
$query = 'SELECT count(*) FROM table WHERE id > 6';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
// Printing results in HTML
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
mysql_free_result($result);
// Closing connection
mysql_close($link);
?>

PHP update table data based on other table

I am trying to create a cron job that will select the sum of points from a transaction table.
Based on the Sum of the points and the employee id I must update the total point table.
I want to make sure that I am using the best method and that this will work.
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT ID, SUM(POINTS) as Points, FROM Transactions WHERE Status = 1 Group By ID";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
mysql_query("UPDATE Totals SET Points=" + $row["Points"] + "WHERE ID=" + $row["id"]);
}
mysql_free_result($result);
?>
You can still join tables (and subqueries) on UPDATE statements. Try this one,
UPDATE Totals a
INNER JOIN
(
SELECT ID, SUM(POINTS) as Points,
FROM Transactions
WHERE Status = 1
Group By ID
) b
ON a.ID = b.ID
SET a.Points = b.Points
Hope this helps.
example of using PDO Extension (Code Snippet).
<?php
$query = "UPDATE Totals a
INNER JOIN
(
SELECT ID, SUM(POINTS) as Points,
FROM Transactions
WHERE Status = ?
Group By ID
) b
ON a.ID = b.ID
SET a.Points = b.Points";
$iStatus = 1;
$stmt = $dbh->prepare($query);
$stmt->bindParam(1, $iStatus);
$stmt->execute();
?>
PDO Manual
PDO PreparedStatement
Why can't you just test the script out out before you run it via a cron job? I can't spot anything that's wrong with the syntax; but then again, I only gave it a quick glance and I don't know what your table structure is like.
If you're looking for the BEST way to do things, then you should looking into using mysqli or PDO instead of the mysql functions. That way, you can make use of prepared statements, which won't be as taxing on your DBMS if you're planning on running multiple queries inside a loop. Prepared statements don't require you to make separate round trips to the server, whereas the old mysql functions do.

Can't get results from mySQL query to display in PHP

I am very new to PHP and can't seem to use mySQL data at all from PHP. The SQL query I wrote works fine in phpMyAdmin when I run it in the SQL editor, but the most I am able to get from the code is the following from var_dump. Nothing else displays anything at all.
resource(3) of type (mysql result)
Any help at all would be greatly appreciated!!
<?php
ini_set(‘display_errors’,1);
error_reporting(E_ALL|E_STRICT);
$con = mysql_connect("localhost","XXXXXXXX","XXXXXXX");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("sharetrader", $con);
$sharelist = mysql_query("SELECT DISTINCT tblStocks.stockSymbol, tblShareData.lookupDate FROM tblStocks LEFT JOIN tblShareData ON tblShareData.tickerCode = tblStocks.stockSymbol ORDER BY tblShareData.lookupDate ASC LIMIT 0 , 30");
if (!$sharelist) {
die('Invalid query: ' . mysql_error());
}
var_dump($sharelist);
while ($row = mysql_fetch_array($sharelist)) {
echo $row['tblStocks.stockSymbol'];
}
mysql_close($con);
?>
I am very new to PHP
But you're making great progress - just missing some of the finer points.
try:
while ($row = mysql_fetch_array($sharelist)) {
var_dump($row);
}
...and it should be obvious what's happening.

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

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.

Categories