show the maximum value of a column of mysql table in php? - php

I want to show the maximum value of a particular column of mysql table in php. Here is my code:
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$var = $_POST['value'];
$sql = mysql_query(" SELECT MAX(column) FROM tableName WHERE variable='$var' ") or die(mysql_error());
$row = mysql_fetch_array($sql) or die(mysql_error());
echo "Maximum value is :: ".$row['column'];
?>
output:::
Maximum value is ::

Or you could be a bit creative:
$sql = mysql_query("SELECT `column` FROM tableName WHERE variable='$var' ORDER BY `column` DESC LIMIT 1") or die(mysql_error());

This is the same problem that I was searching for a solution. The approach below worked. The solution was using "MYSQLI_NUM". While the code below gives the intended result it still seems way too complex. Is there a way to "short-cut" using the "while" statement to search an array since there is only one returned value?
Selecting a max value only returns one number, yet PHP still seems to require a loop to evaluate an entire array. I was expecting something easy, like: max_value=result(0).
<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error.' Sorry, could not connect to the database server');
$query = "SELECT MAX(IssueIDNUM) FROM tblIssueList";
$result =$conn->query($query);
if (!$result) die($conn->error);
while($row=mysqli_fetch_array($result, MYSQLI_NUM))
{
$maxresult=$row[0];
echo $maxresult;
}
$result->close();
$conn->close();
?>
With further experimentation, I was also able to adapt the code by Jim H. to develop the following solution. Though it works the code still seems too complex.
// Solution #2
$result =$conn->query("SELECT MAX(IssueIDNUM) `max` FROM tblIssueList");
if (!$result) die($conn->error);
while($row=mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo $row['max'];
}

The real name of column is MAX(column), try:
print_r($row);
You may either do:
$sql = mysql_query(" SELECT MAX(column) AS `column` FROM tableName WHERE variable='$var' ") or die(mysql_error());
Or:
$row = mysql_fetch_row($sql) or die(mysql_error());
echo "Maximum value is :: ".$row[0];

You have two choices. By Index or by Column Name. If you really want to use a column name, alias the column in your query.
$sql = mysql_query(" SELECT MAX(column) `max` FROM tableName WHERE variable='$var' ") or die(mysql_error());
Then you can use
$row['max'];
or
$row[0];

You are probably not returning any rows. You should try WHERE variable LIKE '%$var%';

$sql = mysql_query(" SELECT MAX(column) AS GIVE_A_NAME FROM tableName WHERE variable='$var' ") or die(mysql_error());
and
echo "Maximum value is :: ".$row['GIVE_A_NAME'];

Related

Concatenate an echo statement having mysql_result

I want to get the first name, last name and county to display but I am getting errors when I try to concatenate the echo statement here. How can I correct this?
$query = mysql_query("
SELECT `first_name`, `last_name`,`county`
FROM `contact`
WHERE `first_name` ='". mysql_real_escape_string(trim($_POST['name'])) ."'
");
echo (mysql_num_rows($query) !== 0)? mysql_result($query,0,'first_name'):'Name not found';
?>
This is the message I receive:
Warning: mysql_result(): last_name.county not found in MySQL result index 5 in C:\xampp\htdocs\ajax_Contact\name.php on line 14
This code should answer the OP's question in relation to his current code:
$query = mysql_query("
SELECT `first_name`, `last_name`,`county`
FROM `contact`
WHERE `first_name` ='". mysql_real_escape_string(trim($_POST['name'])) ."'
");
(mysql_num_rows($query) !== 0) ? print mysql_result($query,0,'first_name') : print 'Name not found';
?>
Also according to your error, make sure that this line:
`last_name`,`county`
is not currently
`last_name`.`county`
Notice the comma/period difference.
OR, if you are trying to display first name, last name, and county use this:
$query = mysql_query("
SELECT `first_name`, `last_name`,`county`
FROM `contact`
WHERE `first_name` ='". mysql_real_escape_string(trim($_POST['name'])) ."'
");
(mysql_num_rows($query) !== 0) ? print mysql_result($query,0,'first_name')." ".mysql_result($query,0,'last_name')." ".mysql_result($query,0,'county') : print 'Name not found';
?>
And ultimately for better performance and supported code use
$mysqli = new mysqli("your_host", "your_user", "your_password", "your_database");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "
SELECT `first_name`, `last_name`,`county`
FROM `contact`
WHERE `first_name` ='". mysql_real_escape_string(trim($_POST['name'])) ."'
";
$result = $mysqli->query($query);
while($row = $result->fetch_array()){
$rows[] = $row;
}
if($result->num_rows === 0){
print 'Name not found';
}
foreach($rows as $row){
print $row['first_name']." ".$row['last_name']." ".$row['county'];
}
/* free result set */
$result->close();
/* close connection */
$mysqli->close();
Your easyest way is to use a newer version of the MySQL functions - mysqli is a very good one to go with. But if you have to rely on the old function set, then pleace read the documentation; mysql_result returns the data, and you should prepare it yourself in the code.
Also, I have to agree with #MarcB - use mysql_fetch_assoc or something like that when oyu are only and really expecting one single row.
But if you have the time, merge to the mysqli or PDO methods - they are more modern (in other words they are OOP all the way) and safer.
First, don't use the mysql_*() library. It's deprecated and obsolete. But if you have to use it, then DON'T use mysql_result. It's inefficient. A better process is to fetch an entire row using the fetch functions
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($row);
if (mysql_num_rows($result) != 0) {
echo $row['first_name'], $row['last_name'], $row['county'];
}

PHP not displaying data

Any ideas why this simple php code won't display results when trying to echo the data.
<?php
{
mysql_connect("localhost" , "" , "") or die (mysql_error());
mysql_select_db("") or die(mysql_error());
$pid=intval($_SESSION["User_id"]);
$query = "SELECT `car`, `details`, `price` FROM `Car``";
//executes query on the database
$result = mysql_query ($query) or die ("didn't query");
//this selects the results as rows
$num = mysql_num_rows ($result);
while($row=mysql_fetch_assoc($result))
{
$_SESSION['car'] = $row['car'];
$_SESSION['details'] = $row['details'];
$_SESSION['price'] = $row['price'];
}
}
?>
<?php echo $_SESSION['car']; ?>
<?php echo $_SESSION['details']; ?>
<?php echo $_SESSION['price']; ?>
Just testing at the moment to see if the car, price and details display from the database and they don't seem to.
You missed session_start(); at start of page and change
$query = "SELECT `car`, `details`, `price` FROM `Car``";
^
to
$query = "SELECT `car`, `details`, `price` FROM `Car`";
Are you expecting one or many results for this query ?
If many results, you are saving the last entry in the session.
If only one, just do : $row=mysql_fetch_assoc($result) instead of this while.
Check the query.Try to echo it, copy, paste in MySQL and run it. But you have $pid, have you put it in the query?
$query = "SELECT car, details, price FROM Car WHERE id = $pid ";
I rather remove all backticks since non of those identifiers are reserved keywords.
$query = "SELECT car, details, price FROM Car";

How to display table data in reverse? (php)

I have simple code for displaying images. I created table with 4 columns (ID, location, capture, equence) and inserted there 18 records. My question is: how to display all records from table in reverse mode? I need to make that the last entry will be displayed first, and the first entry displayed last.
What I need: 18-1
What I have now: 1-18
I was searching for simple codes to do that, but notwing worked at all. So i'd be very grateful if someone will help me to solve that problem.
Heres the basic code of my display script:
<?php
mysql_connect("localhost", "***", "***") or die(mysql_error());
mysql_select_db("martinidb1337") or die(mysql_error());
$result = mysql_query("SELECT * FROM klpgalerija") or die(mysql_error()); while($row = mysql_fetch_array( $result )) {
echo '<p><img src="'.$row['location'].'"></p>';
}
You have to use MySQL ORDER BY clause for that,
SELECT * FROM klpgalerija ORDER BY id DESC
Note: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated.
So use either PDO or MySQLi (IMO PDO is way to go)
Changed query from "SELECT * FROM klpgalerija" to "SELECT * FROM klpgalerija ORDER BY ID DESC"
<?php
mysql_connect("localhost", "***", "***") or die(mysql_error());
mysql_select_db("martinidb1337") or die(mysql_error());
$result = mysql_query("SELECT * FROM klpgalerija ORDER BY ID DESC") or die(mysql_error()); while($row = mysql_fetch_array( $result )) {
echo '<p><img src="'.$row['location'].'"></p>';
}
add an order by desc clause in your sql query
$result = mysql_query("SELECT klpgalerija.* FROM klpgalerija order by klpgalerija.ID desc") or die(mysql_error());

Help displaying data from a MySQL database

I want to display some basic data from a MySQL database. Here's the current code I have, but it doesn't seem to work. Could someone please explain why this doesn't work and offer a solution? Thanks!
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("cede") or die("Couldn't find database");
$result = 'SELECT * FROM 'users' ORDER BY 'DATE' DESC LIMIT 8';
echo = "'$result'"
?>
Providing your connection and structure information is correct, the following should work for you:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("cede") or die("Couldn't find database");
$result = 'SELECT * FROM `users` ORDER BY `DATE` DESC LIMIT 8';
$query = mysql_query($result) or die("Query Error");
while($row = mysql_fetch_assoc($query))
{
echo = "'" . $row['user'] . "'";
}
?>
You forgot to query the database!
You need to use mysql_query() to retrieve data from your DB server, then loop through it with a while() loop.
Also, you can't use quotes inside quoted strings - it breaks the string, meaning you'll get a syntax error with the SELECT ... line. You don't actually need to quote database fields in queries, so the following should work fine:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("cede") or die("Couldn't find database");
$query = 'SELECT * FROM users ORDER BY DATE DESC LIMIT 8';
$result = mysql_query($query); // Query the database.
// Loop through each returned row
while($row = mysql_fetch_assoc($result))
{
print_r($row); // Prints the current row
}
?>
To show any errors that PHP reports, put these two lines at the top of your script.
error_reporting(E_ALL);
ini_set('display_errors', '1');
They will output any errors you get, making problems much easier to solve.
After the selecting the database need
$stmt = mysql_query("SELECT * FROM users ORDER BY DATE DESC LIMIT 8");
while ($result = mysql_fetch_array($stmt, MYSQL_NUM))
{
var_dump($result);
}
mysql_free_result($stmt);
You should query your string and then echo the result, like this for example:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("cede") or die("Couldn't find database");
$query = 'SELECT * FROM `users` ORDER BY `DATE` DESC LIMIT 8';
$result = mysql_query($query);
echo = "'$result'"; // This may need a foreach loop
?>
You should escape the ' in your string, because you use them to open and close your string too. The syntax highlighter actually tells you that you are wrong ('users' and 'DATE' are black instead of maroon). :)
Please see the PHP.net documentation about strings:
After that, you'll need to further process $result. It is just a resource pointer and cannot be echoed that way. But that's a second step. :)

Select latest entry from MySQL database error

<?php
mysql_connect("localhost", "user", "password") or die(mysql_error());
mysql_select_db("jmvarela_jacket") or die(mysql_error());
$query = 'SELECT * FROM `quote` ORDER BY `id` DESC LIMIT 1';
$row = mysql_fetch_array( $query );
echo $row['frase'];
?>
I cant get this to work.
I get this error:
Warning: mysql_fetch_array(): supplied
argument is not a valid MySQL result
resource in
/home/jmvarela/public_html/ihateyourjacket.com/latest/index.php
on line 7
I am trying to select the latest entry to the mysql database.
The table is called "quote"
There are three fields: id, frase and name.
Just to clarify (because this could be VERY bad coding) I am trying to get the "biggest" id and to display it's correspondant "frase".
you have not perform your query
$result = mysql_query($query);
$row = mysql_fetch_array( $result );
try this
Looks like you are not running the query.
// construct the query.
$query = 'SELECT * FROM `quote` ORDER BY `id` DESC LIMIT 1';
// run the query..THIS IS MISSING.
$result = mysql_query($query);
Also it's better to change SELECT * to SELECT frase, since you're interested only in the frase column. This will not bring all the unwanted columns from MySql to PHP, making your program perform better.
I´m not sure if this should be done but ill leave the complete running code for future refence.
<?php
mysql_connect("localhost", "user", "password") or die(mysql_error());
mysql_select_db("jmvarela_jacket") or die(mysql_error());
// construct the query.
$query = 'SELECT * FROM `quote` ORDER BY `id` DESC LIMIT 1';
$result = mysql_query($query);
$row = mysql_fetch_array( $result );
echo $row['frase'];
?>
Thanks to everyone!

Categories