The max value in a column with php - php

I have a MySql table "MyTable" with the column "order"
order
-----
3
4
2
1
I want to get the highest number. The sql statement works well inside MySql:
SELECT MAX(order) FROM MyTable"
But I do not know how to use it with php and echo it? Something like:
$result = mysqli_query($con, "SELECT MAX(order) FROM MyTable");

$result = mysqli_query($con, "SELECT MAX(order) FROM MyTable");
$row = mysqli_fetch_array($result);
echo $row[0];

If you don't provide an alias to a MySQL function it will be shown as you've written it:
$row = mysqli_fetch_array($result);
echo $row['MAX(order)'];
What you can do is write something like:
$result = mysqli_query($con, "SELECT MAX(order) as 'max' FROM MyTable");
$row = mysqli_fetch_array($result);
echo $row['max'];
Which is using an alias.
Hope this helps!

Alternatively you can use ORDER BY DESC and Limit result to 1 this way you can easily get the maximum of an column .
$result=$con->query("SELECT order FROM MyTable ORDER BY order DESC LIMIT 1");
$row=mysqli_fetch_array($result);
echo $row['order'];
Or using MAX
$result = mysqli_query($con, "SELECT MAX(order) FROM MyTable");
$row=mysqli_fetch_array($result);
echo $row[0];

This tutorial is directly from tizag, using the MySql Max function
MySQL Aggregate Functions - MAX()
// Make a MySQL Connection
$query = "SELECT type, MAX(price) FROM products GROUP BY type";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "The most expensive ". $row['type']. " is $" .$row['MAX(price)'];
echo "<br />";
}

Here's my answer:
$host = "localhost";
$username = "your_username";
$password = "your_password";
$db_name = "your_db_name";
$connection = mysql_connect($host, $username, $password) or die ("Error:: [1]");
mysql_select_db($db_name, $connection) or die ("Error:: [2]");
$query = "SELECT `order` FROM `MyTable` order by `order` desc";
$res = mysql_query($query, $connection);
$row = mysql_fetch_array($res);
print $row[0];
With this query , you always have the highest value of the give column.

Related

PHP: use an array in a select where condition [duplicate]

This question already has answers here:
Passing an array to a query using a WHERE clause
(17 answers)
Closed 11 months ago.
I'm trying to query a MySQL database using an array but I'm having trouble!
I have a table called clients, I want to be able to select 'name' from all rows whose 'sector' column is equal to $sectorlink.
I then want to put all the names into an array so I can perform my next query: select all rows from another table whose 'client' column is equal to one of the names returned from the first query. I'm doing something wrong because it returns a fatal SQL error. I'm getting confused with all the variables!
$sectorlink and $connection are the only variables that are defined outside of this code
Any suggestions?
$query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'";
$clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR);
while($row = mysql_fetch_array($clientresult)){
foreach($row AS $key => $value){$temp[] = '"'.$value.'"';}
$thelist = implode(",",$temp);
$query = "SELECT count(*) FROM studies WHERE client IN ($row) ORDER BY (date) desc";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
}
The second query should use $thelist not $row, and it should be outside of the while loop. The foreach loop is unnecessary when processing a single row. You can access the name in $row with a simple $row[0]. Something like this (untested):
$query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'";
$clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR);
while($row = mysql_fetch_array($clientresult)){
$temp[] = '"'.$row[0].'"';
}
$thelist = implode(",",$temp);
$query = "SELECT count(*) FROM studies WHERE client IN ($thelist) ORDER BY (date) desc";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
Caution: Please be aware that your code is highly vulnerable to SQL injection attacks. It's fine for testing or internal development but if this code is going to be running the Fort Knox web site you're going to want to fix it up quite a bit. Just an FYI. :-)
Try This:
$query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'";
$clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR);
while($row = mysql_fetch_array($clientresult)){
$client = $row['name'];
$query = "SELECT * FROM studies WHERE client='$client' ORDER BY date DESC";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
/* echo results here */
}
Couple of things. First you have an unnecessary loop there. Try:
while (list($name) = mysql_fetch_row($clientresult)) {
$temp[] = $name;
}
To build your temporary array.
Second, the parts of the IN clause are strings, so when you implode, you'll need to enclose each value in quotes:
$thelist = "'". implode("','", $temp) . "'";
Lastly, in your query you are passing $row to the IN clause, you should be passing $thelist:
$query = "SELECT count(*) FROM studies WHERE client IN ($thelist) ORDER BY date desc";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
So altogether:
$query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'";
$clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR);
while (list($name) = mysql_fetch_row($clientresult)) {
$temp[] = $name;
}
$thelist = "'". implode("','", $temp) . "'";
$query = "SELECT count(*) FROM studies WHERE client IN ($thelist) ORDER BY date desc";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
I expect you'd be better off doing this in one query with a join:
$query = "SELECT COUNT(*) FROM `studies` INNER JOIN `clients` on studies.client = clients.name WHERE clients.sector = '$sectorlink' ORDER BY studies.date DESC";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);

PHP and MYSQLi list names and count instances from a table [duplicate]

I am able to get both the value and row of the mysql query result.
But I am struggling to get the single output of a query. e.g.:
$result = mysql_query("SELECT COUNT(*) FROM Students;");
I need the result to display. But I am not getting the result.
I have tried with the following methods:
mysql_fetch_assoc()
mysql_free_result()
mysql_fetch_row()
But I didn't succeed to display (get) the actual value.
You need to alias the aggregate using the as keyword in order to call it from mysql_fetch_assoc
$result=mysql_query("SELECT count(*) as total from Students");
$data=mysql_fetch_assoc($result);
echo $data['total'];
If you only need the value:
$result = mysql_query("SELECT count(*) from Students;");
echo mysql_result($result, 0);
$result = mysql_query("SELECT COUNT(*) AS `count` FROM `Students`");
$row = mysql_fetch_assoc($result);
$count = $row['count'];
Try this code.
Please start using PDO.
mysql_* is deprecated as of PHP 5.5.0 and will be removed entirely in 7. Let's make it easier to upgrade and start using it now.
$dbh = new \PDO($dsn, $user, $password);
$sth = $dbh->prepare('SELECT count(*) as total from Students');
$sth->execute();
print_r($sth->fetchColumn());
here is the code for showing no of rows in the table with PHP
$sql="select count(*) as total from student_table";
$result=mysqli_query($con,$sql);
$data=mysqli_fetch_assoc($result);
echo $data['total'];
$num_result = mysql_query("SELECT count(*) as total_count from Students ") or exit(mysql_error());
$row = mysql_fetch_object($num_result);
echo $row->total_count;
You can as well use this and upgrade to mysqli_ (stop using mysql_* extension...)
$result = mysqli_query($conn, "SELECT COUNT(*) AS `count` FROM `Students`");
$row = mysqli_fetch_array($result);
$count = $row['count'];
echo $count;
With mysql v5.7.20, here is how I was able to get the row count from a table using PHP v7.0.22:
$query = "select count(*) from bigtable";
$qresult = mysqli_query($this->conn, $query);
$row = mysqli_fetch_assoc($qresult);
$count = $row["count(*)"];
echo $count;
The third line will return a structure that looks like this:
array(1) {
["count(*)"]=>string(4) "1570"
}
In which case the ending echo statement will return:
1570
For mysqli users, the code will look like this:
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
$result = $mysqli->query("SELECT COUNT(*) AS Students_count FROM Students")->fetch_array();
var_dump($result['Students_count']);
or:
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
$result = $mysqli->query("SELECT COUNT(*) FROM Students")->fetch_array();
var_dump($result[0]);
$db = new PDO('mysql:host=localhost;dbname=java_db', 'root', 'pass');
$Sql = "SELECT count(*) as `total` FROM users";
$stmt = $db->query($Sql);
$stmt->execute();
$total = $stmt->fetch(PDO::FETCH_ASSOC);
print '<pre>';
print_r($total);
print '</pre>';
Result:
You need to alias the aggregate using the as keyword in order to call it from mysqli_fetch_assoc
$result=mysqli_query($conn,"SELECT count(*) as total from Students");
$data=mysqli_fetch_assoc($result);
echo $data['total'];
$howmanyuser_query=$conn->query('SELECT COUNT(uno) FROM userentry;');
$howmanyuser=$howmanyuser_query->fetch_array(MYSQLI_NUM);
echo $howmanyuser[0];
after the so many hours excellent :)

MySQL AVG function returning 0

I'm using the code below to query the database.
mysql_query ("SELECT * FROM _$symbol ORDER BY date DESC;");
$_10day = mysql_query ("SELECT AVG(close) FROM _$symbol limit 10;");
$_21day = mysql_query ("SELECT AVG(close) FROM _$symbol limit 21;");
$_50day = mysql_query ("SELECT AVG(close) FROM _$symbol limit 50;");
echo "$_10day\n";
echo "$_21day\n";
echo "$_50day\n";
mysql_query ("INSERT INTO _$symbol(_10day) VALUE ('$_10day');");
echo mysql_errno($sql) . ": " . mysql_error($sql). "\n";
I need to get the average of close from the database, and I'm using the AVG()function, then insert the return value into the database. The queries work in mysql however they do not work through the script. It does enter a value into the database, but it always enters 0. What am I doing wrong?
EDIT--solution found
$get10 = mysql_query ("SELECT AVG( close ) AS CloseAverage from ( SELECT close FROM _$symbol ORDER BY date DESC limit 10 ) sub1 ;");
$row = mysql_fetch_assoc($get10);
$_10day = $row['CloseAverage'];
if (!mysql_query ("UPDATE _$symbol SET _10day = $_10day, _21day = $_21day, _50day = $_50day, _100day = $_100day, _120day = $_120day, _150day = $_150day, _200day = $_200day, _240day = $_240day, _20dayVol = $_20dayVol, _50dayVol = $_50dayVol where date = '$date';"))
{
echo "Update query failed";
}
I was querying it incorrectly apparently it needed to be selected as a sub query, solution is above, it is working now.
Here's an example on how to manage multiple result-rows:
function connect()
{
$db = mysql_connect("localhost","username","password") or die("your error msg");
mysql_select_db("database_name");
return $db;
}
$db = connect();
$query = "SELECT value1 FROM my_table";
$result = mysql_query($query, $db);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
// This one will loop through the data in your output//
$outputValue = $row['value1'];
}
For inserting data:
// Continued from the state above //
$query = "INSERT INTO table_name (column1) VALUES (value1)";
$result = mysql_query($query, $db) or die(mysql_error());
$_10day is a mysql result, not a value. You can't just put a result into a query string and expect it to work.
You need to get the result data first, eg;
while($row = mysql_fetch_assoc($_10day)) {
$10day = $row['AVG(close)'];
}
Then you can execute your insert query;
mysql_query ("INSERT INTO _$symbol (_10day) VALUES ('$10day')");
Hope this helps.

MySQL run query inside a query

I have a query that gets 5 lines of data like this example below
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
}
I want to run a query inside each results like this below
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) )
{
$title = $row['title'];
} else {
$title = "No Title";
}
echo "$ref - $tile";
}
but for some reason it's only display the first line when I add the query inside it. I can seem to make it run all 5 queries.
SELECT
t1.ref,
t1.user,
t1.id,
t2.domain,
t2.title
FROM
table AS t1
LEFT JOIN anothertable AS t2 ON
t2.domain = t1.ref
LIMIT
0, 5
The problem is that inside the while-cycle you use the same variable $result, which then gets overridden. Use another variable name for the $result in the while cycle.
You change the value of your $query in your while loop.
Change the variable name to something different.
Ex:
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$qry = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$rslt = mysql_query($qry) or die(mysql_error());
if (mysql_num_rows($rslt) )
{
$title = $row['title'];
} else {
$title = "No Title";
}
echo "$ref - $tile";
}
Use the following :
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query_domain = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$result_domain = mysql_query($query_domain) or die(mysql_error());
if (mysql_num_rows($result_domain) )
{
$row_domain = mysql_fetch_row($result_domain);
$title = $row_domain['title'];
} else {
$title = "No Title";
}
echo "$ref - $title";
}
This is a logical problem. It happens that way, because you are same variable names outside and inside the loop.
Explanation:
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
// Now $results hold the result of the first query
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
//Using same $query does not affect that much
$query = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
//But here you are overriding the previous result set of first query with a new result set
$result = mysql_query($query) or die(mysql_error());
//^ Due to this, next time the loop continues, the $result on whose basis it would loop will already be modified
//..............
Solution 1:
Avoid using same variable names for inner result set
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$sub_result = mysql_query($query) or die(mysql_error());
// ^ Change this variable so that it does not overrides previous result set
Solution 2:
Avoid the double query situation. Use joins to get the data in one query call. (Note: You should always try to optimize your query so that you will minimize the number of your queries on the server.)
SELECT
ref,user,id
FROM
table t
INNER JOIN
anothertable t2 on t.ref t2.domain
LIMIT 0, 5
Learn about SQL joins:
SELECT table.ref, table.user, table.id, anothertable.title
FROM table LEFT JOIN anothertable ON anothertable.domain = table.ref
LIMIT 5
You're changing the value of $result in your loop. Change your second query to use a different variable.
it is not give proper result because you have used same name twice, use different name like this edit.
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query1 = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$result1 = mysql_query($query1) or die(mysql_error());
if (mysql_num_rows($result1) )
{
$title = $row['title'];
} else {
$title = "No Title";
}
echo "$ref - $tile";
}

select count(*) from table of mysql in php

I am able to get both the value and row of the mysql query result.
But I am struggling to get the single output of a query. e.g.:
$result = mysql_query("SELECT COUNT(*) FROM Students;");
I need the result to display. But I am not getting the result.
I have tried with the following methods:
mysql_fetch_assoc()
mysql_free_result()
mysql_fetch_row()
But I didn't succeed to display (get) the actual value.
You need to alias the aggregate using the as keyword in order to call it from mysql_fetch_assoc
$result=mysql_query("SELECT count(*) as total from Students");
$data=mysql_fetch_assoc($result);
echo $data['total'];
If you only need the value:
$result = mysql_query("SELECT count(*) from Students;");
echo mysql_result($result, 0);
$result = mysql_query("SELECT COUNT(*) AS `count` FROM `Students`");
$row = mysql_fetch_assoc($result);
$count = $row['count'];
Try this code.
Please start using PDO.
mysql_* is deprecated as of PHP 5.5.0 and will be removed entirely in 7. Let's make it easier to upgrade and start using it now.
$dbh = new \PDO($dsn, $user, $password);
$sth = $dbh->prepare('SELECT count(*) as total from Students');
$sth->execute();
print_r($sth->fetchColumn());
here is the code for showing no of rows in the table with PHP
$sql="select count(*) as total from student_table";
$result=mysqli_query($con,$sql);
$data=mysqli_fetch_assoc($result);
echo $data['total'];
$num_result = mysql_query("SELECT count(*) as total_count from Students ") or exit(mysql_error());
$row = mysql_fetch_object($num_result);
echo $row->total_count;
You can as well use this and upgrade to mysqli_ (stop using mysql_* extension...)
$result = mysqli_query($conn, "SELECT COUNT(*) AS `count` FROM `Students`");
$row = mysqli_fetch_array($result);
$count = $row['count'];
echo $count;
With mysql v5.7.20, here is how I was able to get the row count from a table using PHP v7.0.22:
$query = "select count(*) from bigtable";
$qresult = mysqli_query($this->conn, $query);
$row = mysqli_fetch_assoc($qresult);
$count = $row["count(*)"];
echo $count;
The third line will return a structure that looks like this:
array(1) {
["count(*)"]=>string(4) "1570"
}
In which case the ending echo statement will return:
1570
For mysqli users, the code will look like this:
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
$result = $mysqli->query("SELECT COUNT(*) AS Students_count FROM Students")->fetch_array();
var_dump($result['Students_count']);
or:
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
$result = $mysqli->query("SELECT COUNT(*) FROM Students")->fetch_array();
var_dump($result[0]);
$db = new PDO('mysql:host=localhost;dbname=java_db', 'root', 'pass');
$Sql = "SELECT count(*) as `total` FROM users";
$stmt = $db->query($Sql);
$stmt->execute();
$total = $stmt->fetch(PDO::FETCH_ASSOC);
print '<pre>';
print_r($total);
print '</pre>';
Result:
You need to alias the aggregate using the as keyword in order to call it from mysqli_fetch_assoc
$result=mysqli_query($conn,"SELECT count(*) as total from Students");
$data=mysqli_fetch_assoc($result);
echo $data['total'];
$howmanyuser_query=$conn->query('SELECT COUNT(uno) FROM userentry;');
$howmanyuser=$howmanyuser_query->fetch_array(MYSQLI_NUM);
echo $howmanyuser[0];
after the so many hours excellent :)

Categories