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.
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
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.
I am trying to print the duplicate records of the table but only the single row is getting
echoed.However in mysql this query results all the duplicate records. Here is the query:
$q = mysql_query("SELECT * FROM add WHERE cust_id = '144' GROUP BY cust_id");
$r = mysql_fetch_array($q);
$s = mysql_num_rows($q);
while($s !=0)
{
echo $r;
$s=$s-1;
}
Whats wrong with the code?
$q = mysql_query("SELECT * FROM add WHERE cust_id = '144' GROUP BY cust_id");
while($r = mysql_fetch_array($q))
{
print_r($r);
}
You need to loop through the entire record set... you are only grabbing the first row:
$resultset = mysql_query("select * from add where cust_id = '144' group by cust_id");
while($row = mysql_fetch_assoc($resultset))
{
echo $row['column_name'];
}
Your SQL query will in practice only ever return 0 or 1 rows, due to the GROUP BY clause. Are you absolutely sure that that's the query you were executing in mysql?
well, if you want to get duplicate values, then this query will serve you well:
T = the table
f = the field to check for duplicates
id = the rows id
select id,f from T group by f having count(f)= 2;
or >2 if you want every value in f that occurs in more than one row.
having is like where but evaluated after group by.
Try the following:
$q = mysql_query("SELECT * FROM add WHERE cust_id = '144'");
while($r = mysql_fetch_array($q))
{
echo $r;
}
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.
What's the best way with PHP to read a single record from a MySQL database? E.g.:
SELECT id FROM games
I was trying to find an answer in the old questions, but had no luck.
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']
Using PDO you could do something like this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
echo $id;
}
You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT query, use a WHERE statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example)
Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
One more answer for object oriented style. Found this solution for me:
$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;
gives back just one id. Verify that your design ensures you got the right one.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
with mysqli
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
with Zend Framework
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
The easiest way is to use mysql_result.
I copied some of the code below from other answers to save time.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$num_rows = mysql_num_rows($result);
// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
$value = mysql_result($result, i, 'id');
echo 'Row ', i, ': ', $value, "\n";
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');
$db->set_charset('utf8mb4');
if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
$id = $row[0];
}
I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:
$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
echo mysql_result($r); // will output first ID
echo mysql_result($r, 1); // will ouput second ID
}
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
Better if SQL will be optimized with addion of LIMIT 1 in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)