Get the Largest Number in a mySQL Database in PHP - php

I have a SQL Database that has a column like this:
ID
-----
0352
5432
4382
3520
30593
3992
295
What I want to do is search through that column, find the largest number (30593) and store it in a variable.
This database has other columns, the example above is for demonstration only.
e.g.
$largestNumber = GET LARGEST NUMBER FROM ID
How would I do that in PHP / MySQL

In PHP, we do it like this:
$rowSQL = mysql_query( "SELECT MAX( ID ) AS max FROM `tableName`;" );
$row = mysql_fetch_array( $rowSQL );
$largestNumber = $row['max'];

I believe SELECT max(id) FROM table will work.

SELECT MAX(ID) FROM TABLE
Execute the statement and assign it to your variable.

Try This Query
"SELECT MAX(Price) AS HighestPrice FROM Products";

You can do a single query to figure this out:
http://www.tutorialspoint.com/mysql/mysql-max-function.htm
MySql has it's own Max function that will return the highest value in the specified column.

Use MAX(ID) to get the largest value

Related

One query for every number in row

If I have a database with a field called items with '1,2,3,7,15,25,64,346' in it.
Is there a function to use the commas as a separator and take each number and start a new query and get info for that id? Like a foreach but in sql?
I can see it so clear but cannot put it in words...
You can use this query,
SELECT * FROM TABLE_NAME WHERE COLUMN_NAME in (1,2,3,7,15,25,64,346);
Yes, there is. You can use command IN
mysql_query( 'SELECT * FROM `table` WHERE `id` IN ( 1,2,3,4,5 );' );
WHERE - IN
$row = '1,2,3,7,15,25,64,346'; // $row = $field['value']
$arr = explode(',',$row);
foreach($arr as $a) {
// write your query
}
You can use the query SELECT * FROM table_name WHERE id IN ( 1,2,3,4,5 ) to find data having id's.
No need to separate the values. This will give you the desired result.
There is so way to do a "SQL foreach". Do it using PhP
Also, having such fields means your database is not normalized. You should give a look at relational database normalization, otherwise the bigger your database will be, the bigger your problems will be.
It seems you want data like this where 'source' is table having the column
SELECT target.* FROM target
LEFT JOIN source ON FIND_IN_SET(target.id, source.ids_row)

Can`t MAX() function be used with mysqli?

I can not find a proper answer to this question. I have a very simple code for making a query in mysql to select the row with the maximum value in a determined column (called popularity) from a table (called comments). Every row has a column named comment_id
here is the code:
$connect_error = 'Sorry, try again, there was a connection error';
$con = mysqli_connect('localhost','user_name','password') or die($connect_error);
mysqli_select_db($con, 'database') or die($connect_error);
$result = mysqli_query($con, "SELECT MAX(`popularity`) FROM `comments`");
while ($row = mysqli_fetch_assoc($result)) {
$most_popular = $row['comment_id'];
}
echo "most popular is: $most_popular";
mysqli_free_result($result);
mysqli_close($con);
the screen does not show a proper result. Can someone give me an advice in this regard?
Thank you
You are looking to display the comment_id field, but you don't have that in your SELECT query. You are only selecting the max popularity value, and nothing else.
Try this for your query:
SELECT comment_id FROM comments ORDER BY popularity DESC LIMIT 1
This is sorting your comments by popularity, and then just picking the top one.
Of course you can easily change that to select more columns or even a SELECT * if you want to be able to display other values in this record.
To select the row with max 'popularity' column use this query;
$result = mysqli_query($con, "SELECT * FROM `comments` ORDER BY `popularity` DESC LIMIT 1");
In case you want all sorted by popularity remove the LIMIT 1...
You need
SELECT MAX(`popularity`) AS comment_id FROM `comments`
This will give the column the correct name for the associated array.
You are trying to read the result from a column named comment_id when the result from your query will be named MAX(popularity)
Run this query in mysql "SELECT MAX(popularity) FROM comments" first.The output of this gives you the index to use with $row[index] ie first row which in this case the index will be popularity else just change $row[content_id] to $row[popularity]

MySQL add values from all rows

How would I add up all the integers in the column, _view_count_, on my table, 'videos', then echo it to display on my page?
For example:
if row id 1 has view_count == 328
and
if row id 2 has view_count == 271
How would I make MySQL add those together and echo it out?
You can use MySQL's SUM() and your SQL query would look something similar to:
SELECT SUM(view_count) FROM videos;
To query and echo the value, if you're using mysqli methods in your PHP code, you can use:
$result = $mysqli->query('SELECT SUM(view_count) AS sum FROM videos;');
$row = $result->fetch_assoc($result);
echo $row['sum'];
Assuming you have a $mysqli object defined your code should look like:
$query = "SELECT Sum(view_count) as mySum FROM videos";
$result = $mysqli->query($query);
$row = $result->fetch_assoc($result);
echo $row['mySum'];
SELECT SUM(view_count) FROM videos
Assuming you have a COLUMN id, you can use SUM together with IN, like so:
SELECT SUM(view_count) FROM videos WHERE id in (1,2)

PHP MySQL - Find Row ID

I have a table called "participants" that has 3 fields:
prt_id
prt_event_id
prt_participant_id
What I have is a select query with a where condition on event_id. The query returns let's say 20 rows (20 different participants). What I would like to do is to be able to figure out the row number for a given participant (prt_id).
SELECT *
FROM participants
WHERE prt_id = someinteger
While you can't specifically find a row ID using MySQL, you could do something like the following:
$conn = new mysqli(/*dbinfo*/);
$res = $conn->query("SELECT prt_id FROM participants");
$rowids = array(); $currid = 1;
while ($row = $res->fetch_object()) { // this is using the mysqli library
$rowids[$row->prt_id] = $currid;
$currid++;
}
This would give you an array of ids associated with prt_id.
You could do something like:
<?php
$counter = 1; // Start at one for first entry
$res = mysql_query("SELECT * FROM participants WHERE prt_id = 12");
while( $array = mysql_fetch_assoc($res) )
{
// Do something with the counter, store it into array with details
$counter++;
}
?>
This should do what you want inside MySQL (ie assign a rownum in the order of prt_id), but the performance will be dependent on the number of rows in the table so it's not optimal.
SELECT * FROM (
SELECT #tmp:=#tmp+1 rownum, p.*
FROM (SELECT #tmp:=0) z, participants p
ORDER BY prt_id
) participants
WHERE prt_id = 36;
Demo here.
Edit: This "doh level" rewrite uses an simple index range instead of a table scan, so should be much faster (provided prt_id is a PRIMARY KEY)
SELECT *, COUNT(p2.prt_id) ROWNUM
FROM participants p1
JOIN participants p2
ON p1.prt_id >= p2.prt_id
WHERE p1.prt_id=36;
Demo here.
you could just add an index column in your database, set it as int, primary key and auto increment. then when retrieving the row you retrieve the index number.
RowID is a feature of Oracle: http://docs.oracle.com/cd/B19306_01/server.102/b14200/pseudocolumns008.htm.
MySQL does not have something like that, you can basically emulate that by assign number to an array inside php as you retrieve each row, but that doesn't guarantee you the same number next time you retrieve that results. You probably have to settle for using one of the primary IDs

Faster way to know the total number of rows in MySQL database?

If I need to know the total number of rows in a table of database I do something like this:
$query = "SELECT * FROM tablename WHERE link='1';";
$result = mysql_query($query);
$count = mysql_num_rows($result);
Updated: I made a mistake, above is my actual way. I apologize to all
So you see the total number of data is recovered scanning through the entire database.
Is there a better way?
$query = "SELECT COUNT(*) FROM tablename WHERE link = '1'";
$result = mysql_query($query);
$count = mysql_result($result, 0);
This means you aren't transferring all your data between the database and PHP, which is obviously a huge waste of time and resources.
For what it's worth, your code wouldn't actually count the number of rows - it'd give you 2x the number of columns, as you're counting the number of items in an array representing a single row (and mysql_fetch_array gives you two entries in the array per column - one numerical and one for the column name)
SELECT COUNT(*) FROM tablename WHERE link='1';
You could just do :
SELECT count(*) FROM tablename;
for your query. The result will be a single column containing the number of rows.
If I need to know the total number of rows in a table of database
Maybe I'm missing something here but if you just want to get the total number of rows in a table you don't need a WHERE condition. Just do this:
SELECT COUNT(*) FROM tablename
With the WHERE condition you will only be counting the number of rows that meet this condition.
use below code
$qry=SHOW TABLES FROM 'database_name';
$res=mysql_query($qry);
$output=array();
$i=0;
while($row=mysql_fetch_array($res,MYSQL_NUM)){
++$i;
$sql=SELECT COUNT(*) FROM $row[0];
$output[$i]=mysql_query($sql);
}
$totalRows=array_sum($ouptput);
echo $totalRows;
http://php.net/manual/en/function.mysql-num-rows.php You need this i think.
If you are going to use the following SQL statement:
SELECT COUNT(*) FROM tablename WHERE link='1';
Make sure you have an index on the 'link' column

Categories