Looked all over and couldn't find a way to do this.
I want to count the amount of results from a query that's being looped.
for example...
If I have 5 pokemon, and 2 of them are Pikachus, it will display 4 pokemon but with a 2 next to the pikachu, I want to count the number of different pokemon you own not including the secound Pikachu.
this is what I have so far.
<div class="reg-box3" style="width:100%; margin:5px;">
<?php
$result = mysql_query("SELECT *, COUNT(*) number FROM user_pokemon WHERE belongsto='". $_SESSION{'username'}."'AND (slot='0') GROUP BY pokemon ORDER BY pokemon");
while($row = mysql_fetch_array($result))
{
$sql2 = "SELECT * FROM pokemon WHERE name='".$row['pokemon']."'";
$result2 = mysql_query($sql2) or die(mysql_error());
$battle_get2 = mysql_fetch_array($result2);
?>
<div style="width: 24.5%; float: left;padding:.1%; ">
<?php
$idd= mysql_real_escape_string($row['id']);
$iddd = strip_tags($idd);
?>
You are missing AS from your query before number. If you add it, the desired count will be stored in the $result['number'] variable.
By the way you might find mysql_num_rows() easier in this case. Just call it on your MySQL resource, and it returns the number of rows fetched.
Edit: using mysql_num_rows is this simple: $count = mysql_num_rows($result);
<?php
$result = mysql_query(
<<<SQL
SELECT
`t2`.`name` AS `name`,
COUNT(*) AS `count`
FROM `user_pokemon` AS `t1`
JOIN `pokemon` AS `t2` ON (`t1`.`pokemon` = `t2`.`name`)
WHERE
`t1`.`belongsto` = '{$_SESSION{'username'}}'
AND `t1`.`slot` = 0
GROUP BY `name`
ORDER BY `name`
SQL
);
while($row = mysql_fetch_array($result)){
var_dump($row);
}
?>
No guarantees it works as I don't know your table structure and not sure if I got it right from your queries.
PS: Don't count records with mysql_num_rows(). It requires transferring data from the server while, if you do it directly in MySQL, you get the maximum of performance with the most ease of use.
Related
I am trying to retrieve the last ID from the database and increment it by one. My problem is that I am not able to retrieve it in a particular category. For instance, I have categories with a string value of A, B and C. The category with a string value of A will return only id starting from 1 as 10001, 10002 and the last ID to be retrieved is 10002 plus 1 so that the ID to be displayed is 10003.
Category "B" will return 20002 and category "C" will return 30002.
Here is my code:
<?php
$con = mysql_connect("server","username","password","db_name") or die (mysql_error());
mysql_select_db($con, 'db_name');
$sql = "Select `id` from `tbl_violation` WHERE `category` = 'A' ORDER BY `category` DESC LIMIT 1";
$result = mysql_query ($sql,$con);
while($row = mysql_fetch_array($result, $con))
{
$i = $row['id'];
$i++;
echo "DLR - " .$i;
}
?>
The error is this:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in ...
Notice: Undefined variable: i in ...
First I must say again... Stay away from mysql_connect() and all other mysql_* functions. If you want a simple fix, just replace it with mysqli_ functions and make sure you escape ALL user provided input. A bit of reading But I would recommend to look into PDO.
That out of the way, your MYSQL problem is easy. You want to GROUP the elements so all the rows with same category column are groupped together and then select the maximum for each group. Your SQL would then be:
SELECT category, MAX(id) AS highest_id FROM tbl_violation GROUP BY category;
see this fiddle I made with a similar table.
You can then access the results you get from mysqli_query function the same way you do now...
while($row = mysqli_fetch_array($result, $con))
{
$i = $row['highest_id'];
$i++;
$category = $row['category'];
echo "$category - $i";
}
You can use SELECT MAX to get the highest id. I am assuming that id is not unique. If so, remove the WHERE statement from the query. Try the following.
<?php
$con = mysql_connect("server","username","password","db_name") or die (mysql_error());
mysql_select_db("database");
$sql = "Select MAX(`id`) from `tbl_violation` WHERE `category` = 'A";
$result = mysql_query ($sql,$con);
while($row = mysql_fetch_array($result))
{
$i = $row['id'];
echo "DLR - " .$i++;
}
?>
Also I would like to add that I agree with flynorc. Use PDO or mysqli.
Use
ORDER BY `id` DESC
Instead of
ORDER BY `category` DESC
Trying to get PHP to read my MYSQL db for transactions, divide them by "category" and print the total for each category.
Using a similar structure as the code below, how can I make it do all of the below for each category number. In my db, categories are a number 1-10.
Any help would be much appreciated!
<?php
$result = mysql_query("SELECT SUM(amount) AS value_sum FROM TRANSACTIONS where category=2")
or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
echo "<div class='col1'>";
echo round ($row['value_sum'], 2);
echo "</div>";
}
?>
$result = mysql_query("SELECT SUM(amount) AS value_sum
FROM TRANSACTIONS
GROUP BY category");
Now you have a row per category.
I have this code:
<?php
$data = mysql_query("SELECT id FROM board") or die(mysql_error());
while($info = mysql_fetch_assoc( $data ))
{
Print " ".$info['id']." ";
myOtherQuery($info['id']);
}
function myOtherQuery($id) {
$result = mysql_query("SELECT COUNT(is_following_board_id) FROM follow WHERE is_following_board_id='$id'");
$c = mysql_result($result, 0);
}
?>
It lists all ID's with a number beside it, defined as $c above in the second query.
For simplicity I have remove the HTML of the code but it aligns in a table.
I'm trying to ORDER BY $c, but don't know how to do it. Since it is defined AFTER the select query: $data = mysql_query("SELECT id FROM board")
It errors if I add: $data = mysql_query("SELECT id FROM board ORDER BY '$c'")
Is there anything I can add to the bottom of the code to make this order by work?
You want to do this in one query, by aggregating the results:
select is_following_board_id, sum(is_following_board_id) as cnt
from follow
group by is_following_board_id
order by cnt desc;
Your approach was to fetch the result and then fetch the count. Rather inefficient, because SQL is designed for this type of query.
I have this code that I've been working on and when I run it I get the first result 10 times (it used to repeat infinitely until I added the if statement). It's supposed to return the first 10 results. I've looked at a couple other similar questions but none of the solutions on those worked here. Can anyone see what I'm missing?
<?php
$link = mysql_connect('XXXXXXXXX.com', 'XXXXXX', 'XXXXX');
$db = mysql_select_db('a1007515_troop1', $link);
$i = 1;
while($row = mysql_fetch_array(mysql_query('SELECT * FROM `posts` ORDER BY `pid` DESC LIMIT 10;')))
{
$authinfo = mysql_fetch_array(mysql_query('SELECT * FROM `users` WHERE `id` = '.$row['aid'].' LIMIT 1'));
echo '
<div class="content">
<h1 class="title">'.$row['title'].'</h1>
<span class="authinfo">This post was made by '.$authinfo['name'].'<i>('.$authinfo['username'].')</i> on '.$row['date'].'.</span>
<p class="txt">'.$row['content'].'</p>
</div>';
if ($i == 10) { break; }
++ $i;
}
mysql_close($link);
?>
Maybe try simplifying things, try and stick to doing one thing per line, rather than trying to compress it.
Calling mysql_query in the while will repeat that query every time the while loop is run, rather than fetch the next result. Running another mysql query while iterating through the results of another one can also cause problems.
$link = mysql_connect('mysqlwebhost', 'user', 'pass');
$db = mysql_select_db('dbname', $link);
$result = mysql_query('SELECT * FROM `posts` p, `users` u WHERE u.id = p.aid ORDER BY `pid` DESC LIMIT 0,10;');
while ($row = mysql_fetch_assoc($result)) {
echo '
<div class="content">
<h1 class="title">'.$row['title'].'</h1>
<span class="authinfo">This post was made by '.$row['name'].'<i>('.$row['username'].')</i> on '.$row['date'].'.</span>
<p class="txt">'.$row['content'].'</p>
</div>';
}
mysql_close($link);
You may also wish to avoid using mysql_* functions as they have been deprecated. Have a look at either mysqli or PDO.
The problem is that you execute the SQL statement again each time you test the while() condition:
while($row = mysql_fetch_array(mysql_query('SELECT * FROM `posts` ORDER BY `pid` DESC LIMIT 10;')))
{
...
}
The above code will execute this function every time the while() is evaluated:
mysql_query('SELECT * FROM `posts` ORDER BY `pid` DESC LIMIT 10;')
Instead use:
$stmt = mysql_query(...) or die(mysql_error());
while($row = mysql_fetch_array($stmt)) {
...
}
Next you should use a join. You are following a pattern that "over queries" the database.
You only need the following SQL and a single loop:
SELECT u.*
FROM `posts` p
JOIN `users` u
ON u.id = p.aid
ORDER BY `pid` DESC
LIMIT 0,10;
I have a MySQL database containing a user's country and whether they are an individual or an organisation. The field names are 'country' and 'type'.
Using PHP, I'd like to 'count' the number of countries, the number of individuals and the number of organisations in the database and then display the numbers in the following example format:
<p>So far, <strong>500</strong> individuals and <strong>210</strong> organisations from <strong>40</strong> countries have registered their support.</p>
I am currently listing the total number of records using the below code if this helps:
<?php
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name", $link);
$result = mysql_query("SELECT * FROM table_name", $link);
$num_rows = mysql_num_rows($result);
echo " $num_rows\n ";
?>
My PHP / MySQL skills are very limited so I'm really struggling with this one.
Many thanks in advance!
Ben
To get the number of countries:
SELECT COUNT(DISTINCT country) AS NumCountries FROM tableName
To get the number of individuals, or the number of organisations:
SELECT COUNT(*) AS NumIndividuals FROM tableName WHERE type = 'individual'
SELECT COUNT(*) AS NumOrganisations FROM tableName WHERE type = 'organisation'
What you are looking for is a count based on a grouping. Try something like this:
$sql = "SELECT type, count(*) as cnt FROM users GROUP BY type";
$result = mysql_query($sql);
$counts = array();
while ($row = mysql_fetch_assoc($result)) {
$counts[$row['type']] = $row['cnt'];
}
This will give you an array like
Array (
'individual' => 500,
'organization' => 210
)
For counting the countries, use the first statement as posted by Hammerite.
EDIT: added a verbose example for counting the countries
$sql = "SELECT COUNT(DISTINCT country) AS NumCountries FROM users";
$result = mysql_query($sql);
$number_of_countries = 0;
if ($row = mysql_fetch_assoc($result)) {
$number_of_countries = $row['NumCountries'];
}
This altogether you can then print out:
printf('<p>So far, <strong>%d</strong> individuals and <strong>%d</strong> '.
'organisations from <strong>%d</strong> countries have registered '.
'their support.</p>', $counts['individual'], $counts['organization'],
$number_of_countries);
The answer is to retrieve the answer by using the COUNT(*) function in SQL:
SELECT COUNT(*) AS individual_count FROM user WHERE type = 'individual';
SELECT COUNT(*) AS organization_count FROM user WHERE type = 'organization';
SELECT COUNT(*) AS country_count FROM user GROUP BY country;
The last will group your query set by the country name, and will result in one row for each country. Using COUNT on this result set will give the count of distinct coutries.
You can then fetch this value by using mysql_fetch_assoc on your $result from mysql_query, and the answer will be contained in 'invididual_count', 'organization_count' and 'country_count' for each query.
Thank you for all of your help with this (especially Cassy).
I think it's worthwhile displaying the full code in case anybody else comes across a similar requirement in the future:
<?php
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name", $link);
$sql = "SELECT type, COUNT(*) as cnt FROM table_name GROUP BY type";
$result = mysql_query($sql);
$counts = array();
while ($row = mysql_fetch_assoc($result)) {
$counts[$row['type']] = $row['cnt'];
}
$sql = "SELECT COUNT(DISTINCT country) AS NumCountries FROM table_name";
$result = mysql_query($sql);
$number_of_countries = 0;
if ($row = mysql_fetch_assoc($result)) {
$number_of_countries = $row['NumCountries'];
}
printf('<p><strong>So far, <em class="count">%d</em> individuals and <em class="count">%d</em> organisations from <em class="count">%d</em> countries have registered their support.', $counts['Individual'], $counts['Organisation'], $number_of_countries); ?>
If you're just looking for the number of rows returned try this:
$result = mysql_db_query($db, $query);
$num_rows = mysql_num_rows($result);
Another option would be to execute a separate query with the mysql count function and use the result from that.