MySQL add values from all rows - php

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)

Related

Assign Max() MySQL command to a variable in 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'];

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

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

Echo a selected id from MySQL table

I have this
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['id'];
}
This echo's all id's found in the table.
How can I choose to echo only a selected id.
Say the second id found on the table?
EDIT
I think I have confused people and myself aswell.
Let me try to explain again.
Using the above query I can echo all results found in the table with echo $row['id'];
However I do not want echo all results, just selected ones.
You guys have suggested I use limit or a Where clause.
If I do this I will be limited to just one record. This is not what I want.
I want to echo a selection of records.
Something likes this
echo $row['id'][5], $row['id'][6], $row['id'][6]
But obviously this is incorrect syntax and will not work but hopefully you get what I am trying to do.
Thanks
If you only want the second row then you could change your query to use offset and limit e.g.
SELECT id FROM table LIMIT 1, 1
You could also use a for loop instead of the while loop and then put in a conditional.
UPDATE
Just noticed comments above - you also need to sort the PHP bug by changing mysql_fetch_array to mysql_fetch_assoc.
UPDATE 2
Ok based on your update above you are looking to get all of the rows into an array which you can then iterate over.
You can just use mysql_fetch_array and then use $array[0]. For example:
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
$ids = array();
while($row = mysql_fetch_array($result)) {
$ids[] = $row[0];
}
From what I can gather from your questions you should not be selecting all records in the table if you wish to just use the Nth value, use:
SELECT id FROM table LIMIT N, 1
That will select the Nth value that was returned. Note: The first result is 0 so if you wish to get the second value the Nth value should be 1.
mysql_data_seek() let's you jump to a specific data-set(e.g. the 2.nd)
Example:
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
//get the 2nd id(counting starts at 0)
if(mysql_data_seek($result,1))
{
$row=mysql_fetch_assoc($result);
echo $row['id'];
}
OR:
use mysqli_result::fetch_all
It returns an array instead of a resultset, so you can handle it like an array and select single items directly (requires PHP5.3)

Categories