Assign Max() MySQL command to a variable in PHP - php

In my mySQL database, I insert an entry into the db, and then I need to get the number of that last insertion. I have it set to auto-increment. Using the query "SELECT MAX(ID) FROM TABLE;" works fine in the database, I just need to capture that number to a variable in PHP.
$rowSQL = mysqli_query($con, "SELECT MAX(ID) FROM TABLE");
$row = mysqli_fetch_assoc($rowSQL);
$largestUID = $row['max'];
echo $largestUID;
Thanks for the help!

Use the AS modifier in your query. This modifier gives your selected items an alias.
$rowSQL = mysqli_query($con, "SELECT MAX(ID) AS maxid FROM TABLE");
$row = mysqli_fetch_assoc($rowSQL);
$largestUID = $row['maxid'];
echo $largestUID;

Use an alias name for the calculated column
SELECT MAX(ID) as max_id FROM TABLE
$largestUID = $row['max_id'];

Related

Number of Rows in MySQL Query

I am using a script that has a different way of doing a mySQL query to what I am used to. It starts with:
$query = $db->query("SELECT * etc ..... ");
then
while ($result = $db->fetchArray($query)) {
with variables shown as $result['a'], $result['b']. etc.
All I want to do is count the rows that are selected by the query, but mysql_num_rows doesn't work on $result.
What can I use instead?
You can use the count function to count the rows
$query = $db->query("SELECT count(*) as count from (SELECT * etc ..... ) as sq ");
$result = $db->fetchArray($query);
echo $result['count'];
You can change the query to:
SELECT count(*) as cnt etc .....
Then read the results back from the query.

How to get max(id) of row data MySql

I want to get the maximum id of row data. In my table first column is id then firstname and etc.
this is the sql command I used to get the max(id) of row data.
<?PHP $maxid=$this->db->query("SELECT MAX(id) FROM `emplyee_personal_details`");
print_r( $maxid) ;?>
but it prints bunch of data as it is a array. But I need only the maximam id of row data for validation before data inserting and updating.
How to get the maxid. I use codeigniter framework.
Try this:
$maxid = $this->db->query('SELECT MAX(id) AS `maxid` FROM `emplyee_personal_details`')->row()->maxid;
UPDATE
This will work even if your table is empty (unlike my example above):
$maxid = 0;
$row = $this->db->query('SELECT MAX(id) AS `maxid` FROM `emplyee_personal_details`')->row();
if ($row) {
$maxid = $row->maxid;
}
The problem with using a raw query like "SELECT MAX(id) ..." is it is not abstract and may not work for every SQL engine. I think the active record way to do it is like this:
$this->db->select_max('id');
$query = $this->db->get('emplyee_personal_details');
// Produces: SELECT MAX(id) as age FROM emplyee_personal_details
See: http://ellislab.com/codeigniter/user-guide/database/active_record.html
SELECT id FROM table ORDER BY id DESC LIMIT 1
That will get you the highest id value, and when I read this, "it prints bunch of data as it is a array" I get the sense that what you really want is a part of that array. DB queries always return complex structures like arrays or objects. So if you wanted just the scalar value (the number as an integer) you might use something like this:
$maxid = (int)$maxid['id'];
or like this (if you have an object):
$maxid = (int)$maxid->id;
HTH, ~Ray
Try this,hope it helps,
return $this->db->select_max('id')
->get('your_table_name')
->row()->id;
public function getMaxCategoryId() {
$query = $this->db->query("SELECT category_id+1 AS maxid FROM " . DB_PREFIX . "category ORDER BY category_id DESC LIMIT 1");
return $query->row['maxid'];
}
error undefined index maxid
<?php`$qry = "select max(ID)+1 As ID from records";`
$result = $con->query($qry);
$row = $result->fetch_assoc();`echo "New ID To Enter = ".$row["ID"];?>
After Connection Just Write This Code It Will Work

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)

Get the Largest Number in a mySQL Database in 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

Can't access row with 'fieldName' using MAX() in PHP MYSQL

I have small PHP script which has
$query = "SELECT MAX(id) FROM `dbs`";
//query run
$row = mysql_fetch_array($result);
$val = $row[0];
Which runs fine, but I want to understand why i can't access the row with the fieldname, like if i have this
$query = "SELECT id FROM `dbs`";
i am able to use the folowing
$val = $row['id'];
but whenever i use this MAX() function, i have to change to
$val = $row[0];
to access the values
I have no clue about this. Any help would be appreciated. Thankss
You need to give it an alias:
<?php
$query = "SELECT MAX(id) AS `id` FROM `dbs`";
//query run
$row = mysql_fetch_array($result);
$val = $row['id'];
Edit:
To explain this it's probably best to show an example of a different query:
SELECT MAX(`id`) AS `maxId`, `id` FROM `dbs`
Using the above it will return as many rows are in the table, with 2 columns - id and maxId (although maxId will be the same in each row due to the nature of the function).
Without giving it an alias MYSQL doesn't know what to call it, so it won't have an associative name given to it when you return the results.
Hope that helps to explain it.
SELECT MAX(id) AS myFieldNameForMaxValue
FROM `dbs`
and then
$row = mysql_fetch_array($result);
$val = $row['myFieldNameForMaxValue'];
If you run this query on mysql commandline you'll see that the field name returned by mysql is MAX(id). Try running on phpmyadmin and you'll see the same. So if you try $row['MAX(id)'] it'll work. When using a mysql function, it gets added to the name, so use an alias, like other said here, and you're good to go: SELECT MAX(id) AS id FROM dbs. Also, never forget to use the ` chars, just in case you have some columns/tables with reserved names, likefrom`.

Categories