How to display only one row at random at the same time from DB. Everything works fine, but all rows are displayed. thanks
<?php
$sql = "SELECT id,name FROM table ";
$rows = array();
$result = $objCon->query($sql);
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
shuffle($rows);
echo '<ol>';
foreach($rows as $row)
{
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
}
echo '</ol>';
?>
Change your SQL request:
SELECT id,name FROM table ORDER BY RAND() LIMIT 1;
You can do it using PHP:
....
shuffle($rows);
$randomRow = reset($rows);
....
But the better way is to change your SQL query:
$query = "SELECT id, name FROM table ORDER BY RAND() LIMIT 1;"
<?php
$sql = "
SELECT id, name
FROM table
ORDER BY RAND()
LIMIT 1 ";
$result = mysql_query($sql);
// As you are only return a single row you do you require the while()
$row = mysql_fetch_array($result);
echo '<ol>';
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
echo '</ol>';
?>
By adding an ORDER BY RAND() in your sql query you are asking MySQL to randomly order the results then at a LIMIT to restrict the number of rows you would like returned.
The example code is written based on selecting a single row. If you would like more, e.g. 5, you will need to add a while loop.
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.
I'm trying to get my highcharts chart working and I'm almost there.. I just have one little problem: I need that the value will be the total count of the records at the same day but I'm kinda confused with my code now and the chart is totally messed up..
Here is the code that pulls the data:
<?php
header("Content-type: text/json");
include('../includes/config.php');
$tablename = "analytics";
$result = mysql_query("SELECT COUNT(*) AS count FROM $tablename");
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$sql = "SELECT id, date FROM $tablename ORDER BY date";
$result = mysql_query( $sql ) or die("Couldn't execute query.".mysql_error());
$i=0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$row['id'] = (int) $row['id'];
$rows[$i] = array(strtotime($row['date'])*1000, $row['id']);
$i++;
}
echo json_encode($rows);
?>
If it will help here is my database values:
insert into `analytics`(`id`,`user`,`item`,`ip`,`country`,`date`) values
(10,1,1,'127.0.0.1','','2011-12-17 06:41:51'),
(11,1,1,'127.0.0.1','','2011-12-17 06:42:23'),
(12,1,1,'127.0.0.1','','2011-12-17 06:43:07'),
(13,1,1,'127.0.0.1','','2011-12-17 06:44:19'),
(14,1,1,'127.0.0.1','','2011-12-17 06:44:21'),
(15,1,1,'127.0.0.1','','2011-12-17 06:44:22'),
(16,1,1,'127.0.0.1','','2011-12-17 06:44:49'),
(17,1,1,'127.0.0.1','','2011-12-17 06:46:59'),
(18,1,1,'127.0.0.1','','2011-12-17 06:47:20'),
(19,1,1,'127.0.0.1','','2011-12-17 06:47:35'),
(20,1,1,'127.0.0.1','','2011-12-17 06:47:42'),
(21,1,1,'127.0.0.1','','2011-12-17 06:48:07'),
(22,1,1,'127.0.0.1','','2011-12-17 06:48:14'),
(23,1,1,'127.0.0.1','','2011-12-17 06:48:29'),
(24,1,1,'127.0.0.1','','2011-12-18 06:49:10'),
(25,1,1,'127.0.0.1','','2011-12-19 07:05:45'),
(26,1,1,'127.0.0.1','','2011-12-20 08:11:32'),
(27,1,1,'127.0.0.1','','2011-12-21 08:26:45'),
(28,1,1,'127.0.0.1','','2011-12-17 08:44:34');
And here is the final result:
I totally lost my self here, can someone help?
EDIT: did what #ajreal said and here is the output:
This is the query to get count for each date
SELECT date, COUNT(*) AS count
FROM $tablename
GROUP BY date;
You can use this query to replace your first query.
And to a loop (like your second query), set $total += $row["count"] to get a grand total like your original first query does
I am trying to dsiplay data from 2 different tables from my mysql database using a while loop.
Currently I can display the data from 1 table and limit the results to 3. I then want to display the first 5 records from another table. If I join the tables I can only display the same number of items from both using LIMIT?
I am using a while loop to display the content from a table called item, using the following code;
$query");
$result2 = #mysql_query($query, $connection)
or die ("Unable to perform query$query");
<?php
while($row= mysql_fetch_array($result))
{
?>
<?php echo $row['item'] ?>
<?php
}
?>
If I start another loop for the data from the next table called movie, however the data is not displayed using the following code;
<?php
while($row= mysql_fetch_array($result2))
{
?>
<?php echo $row['title'] ?>
<?php
}
?>
What is the best way to display the data from the 2 tables?
Many Thanks
I don't know if you forgot to paste a bit of code, but this should work:
<?php
$query = "select * from item order by date, time asc limit 0,3";
$result = mysql_query($query);
while($row= mysql_fetch_array($result))
{
echo $row['item'];
}
$query2 = "select * from movie limit 0,5";
$result2 = mysql_query($query2);
while($row= mysql_fetch_array($result2))
{
echo $row['movie'];
}
?>
You may be able to do it with one SQL Query too:
SELECT i.item, m.movie
FROM (SELECT * FROM item ORDER BY date, time ASC LIMIT 0,3) i,
(SELECT * FROM movie limit 0,5) m
Then in php:
<?php
while($row= mysql_fetch_array($result))
{
echo $row['item'];
echo $row['movie'];
}
?>
But that depends on how you want to format the output.
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.