简体   繁体   中英

PHP MYSQL Retrieve Min value from several columns

Very new to PHP so pls bear with me.

I have a table with several columns as such id | onezw | twozw | threezw | fourzw | fivezw | sixzw | minzw

each column has a number that get entered, I then need the 'minzw' column to show the minimum value of the 6 columns. I have the following code but just cant seem to get the problem. pls can someone nudge me in the right direction.

<?php
$host="localhost"; // Host name
$username="xxx"; // Mysql username
$password="xxx"; // Mysql password
$db_name="xxxx"; // Database name
$tbl_name="ZW"; // Table name


// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// get value of id that sent from address bar
$id=$_GET['id'];

// Retrieve data from database
$sql="SELECT * FROM $tbl_name WHERE id='$id'";
$result=mysql_query($sql);
$minzwarray = array("onezw" , "twozw" , "threezw" , "fourzw" , "fivezw" , "sixzw");
$minzw = min($minzwarray);

$rows=mysql_fetch_array($result);
echo $minzw['minzw'];


mysql_close();
?>

You can use mysql to return an extra column with the min value using LEAST() :

SELECT *,LEAST(onezw , twozw , threezw , fourzw , fivezw , sixzw) AS MIN_VALUE
FROM tab1

sqlfiddle demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM