How to Select Smallest Value From Multiple Columns with PHP - php

I have a table with the following:
6xx 8xx 9xx 11xx 12xx
1 0.01 0.002 0.004 0.001 0.025
2 0.025 0.125 0.002 0.01 0.011
I would like to find the Smallest Value from the column make that column to be green color.
For example in 1st the smallest value is 0.001 so i want it to be green color, for second 0.002 is smallest value i want it to be green color.
can any one guide me how to make this ,thanks
below is the code how i selecting it from database and displaying int in a table
<?php
$dbHost = 'localhost'; // usually localhost
$dbUsername = 'xxxx';
$dbPassword = 'xxxx';
$dbDatabase = 'xxxx';
$db = mysql_connect($dbHost, $dbUsername, $dbPassword) or die ("Unable to connect to Database Server.");
mysql_select_db ($dbDatabase, $db) or die ("Could not select database.");
$ColumnNames = mysql_query("SELECT column_name
FROM information_schema.COLUMNS
WHERE table_name = 'supplierprice'
AND column_name NOT IN ('supp_price_id',
'region',
'country',
'net_id',
'networkname',
'mcc',
'mnc',
'mnp')")
or die("mysql error");
$columnArray=array();
$i=0;
while($rows=mysql_fetch_array($ColumnNames))
{
$columnArray[]=$rows[0];
echo "<th style='width:67px;' class='. $columnArray[$i] .' >" . $columnArray[$i] . "
</th>";
$i++;
}
?>
foreach($columnArray as $value) {
//$columnArray[]=$rows1[0];
echo '<td style="width:67px;font-weight:'.$text.'" id="CPH_GridView1_xxx" width="0px;" class="'.$value.' '.$rows["net_id"].'"><p>'.$rows[$value].'</p></td>';
}

one answer for your problem may be this:
1- extract minimum of each column by sql query like this:
$res1=mysql_query('select min(6xx) as min6, min(8xx)as min8, min(9xx) as min9, min(11xx)as min11, min(12xx) as min12 from tbl_name');
$rec1=mysql_fetch_array($res1);
$min6=rec1['min6'];
$min8=rec1['min8'];
$min9=rec1['min9'];
....
2- when you fetch information in html you should check if the value is like min then background (some css) become green:
$res=mysql_query('select * from tbl_name');
echo "<table>";
foreach($rec=mysql_fetch_array($res))
{
echo "<tr>"
echo "<td";
if($rec['6xx']==$min6) echo "class='green_cell' ";
echo "";
echo $rec['6xx'];
echo "</td>";
....
echo "</tr>"

Not entirely sure on your requirements. You appear to be getting some column names for a table. I presume that you want to get the values of these columns and display them in a table, highlighting the one with the lowest value.
If some something like this. Gets the columns, loops through them once to display the headings. For each row it then calls a function with displays them. The key of the lowest value is found (if 2 keys share the lowest value then the lowest key is used). It loops around the columns returned and echos them out, putting out a color:#ff0000; in the style for the lowest value column.
<?php
$dbHost = 'localhost'; // usually localhost
$dbUsername = 'xxxx';
$dbPassword = 'xxxx';
$dbDatabase = 'xxxx';
$db = mysql_connect($dbHost, $dbUsername, $dbPassword) or die ("Unable to connect to Database Server.");
mysql_select_db ($dbDatabase, $db) or die ("Could not select database.");
$ColumnNames = mysql_query("SELECT GROUP_CONCAT(CONCAT('`', column_name, '`')) AS some_columns
FROM information_schema.COLUMNS
WHERE table_name = 'supplierprice'
AND column_name NOT IN ('supp_price_id',
'region',
'country',
'net_id',
'networkname',
'mcc',
'mnc',
'mnp')")
or die("mysql error");
if($rows=mysql_fetch_array($ColumnNames))
{
$sql = "SELECT ".$row['some_columns']." FROM supplierprice";
$query_values = mysql_query($sql);
if($rows2=mysql_fetch_assoc($ColumnNames))
{
echo "<tr>";
foreach($rows2 AS $key=>$value)
{
echo "<th style='width:67px;' >".$key." </th>";
}
echo "</tr>";
process_row($rows2);
while($rows2=mysql_fetch_assoc($ColumnNames))
{
process_row($rows2);
}
}
}
function process_row($in_row)
{
$lowest_values_key = min(array_keys($in_row, min($in_row)));
echo "<tr>";
foreach($in_row AS $key=>$value)
{
echo "<td style='width:67px;".(($lowest_values_key == $key) ? 'color:#ff0000;' : '' )."' >".$value." </th>";
}
echo "</tr>";
}
?>

Related

Calculate Pecent Value from Sum of Two Columns in MySQL Database

I am attempting to get total values from two columns (I have already done this) -- and take these values and create a percent from them. In this case I have a Weighted Value and a Total Value. I need to know what Percent of the Total Value my Weighted Value is.
I have tried:
$result = mysqli_query($mysqli, "SELECT SUM(WEIGHTEDV / VALUE) FROM test.service");
$result = mysqli_query($mysqli, "SELECT WEIGHTEDV, VALUE, (WEIGHTEDV / VALUE) AS percent FROM test.service;
$result = mysqli_query($mysqli,"SELECT (WEIGHTEDV / VALUE)*10 AS Percent
FROM test.service");
There were a few other attempts I do not readily remember.
Here is more complete code:
Login & Working SUM of VALUE
<?php
//LOGIN INFO
$db_host = 'localhost';
$db_user = 'root';
$db_pw = "********";
$database = "test";
//LOGIN VARIABLE
$mysqli = new mysqli($db_host, $db_user, $db_pw);
//VERIFY LOGIN INTEGRITY
if ($mysqli === false) {
die("Cannot connect to Database Server" . $mysqli->connect_error);
}
if (!mysqli_select_db($mysqli, $database)) {
die("Cannot select test Database" . $mysqli->connect_error);
}
$result = mysqli_query($mysqli, "SELECT SUM(VALUE) FROM test.service");
//PRINT ROWS
$fields_num = mysqli_num_fields($result);
while($row = mysqli_fetch_row($result)) {
foreach($row as $cell) {
echo "$$cell";
}
}
?>
Working SUM of WEIGHTEDV
<?php
$result = mysqli_query($mysqli, "SELECT SUM(WEIGHTEDV) FROM test.service");
//PRINT ROWS
$fields_num = mysqli_num_fields($result);
while($row = mysqli_fetch_row($result)) {
foreach($row as $cell) {
echo "$$cell";
}
}
?>
The expected output with the current totals in my Table is
Expected Output: %54.8
Test Variables:
VALUE: 38940.00
WEIGHTEDV:21345.00
Both have a type of (I changed the type to INT -- same result):
DECIMAL(12,2)
Example of actual output (directly out of the HTML table):
65.000000100.0000000.00000050.00000025.000000100.00000050.000000
Current code with above output:
$result = mysqli_query($mysqli,"SELECT (WEIGHTEDV / VALUE)*100 AS Percent
FROM test.service");
This is boggling me pretty good. I am sure it is something simple I am overlooking. Any assistance would be greatly appreciated as to why I cannot get a simple % value output.
seems you need number format and a proper <br />
while($row = mysqli_fetch_row($result)) {
foreach($row as $cell) {
echo umber_format($cell, 2, '.', ',')."<br>";
}
}

How to display count of submitted radio button values using PHP [duplicate]

This question already has answers here:
Combine group by and count mysql
(2 answers)
Closed 5 years ago.
I am trying to display the total number of submitted radio button value, in my previous form, there is a choice between "Male", "Female" for user to choose and submit, and I have a database to store the values (radiob).
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT radiob FROM playertest";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["radiob"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
I have my code above only display all the items in the database under radiob,
Male
Male
Female
Is there anyway that I can display it with the total count?
Would want it to look like:
Male: 2
Female: 1
Use an Aggragage query with count
"SELECT count(id) as total, radiob FROM playertest GROUP BY radiob ";
I suggest adding an Auto Increment ID field as the primary key if you don't already have it.
This is known as a surrogate key in the Database world, and as your table grows you will really want to have one so you can properly refer to a row in other queries.
if you don't like that you can do
if ($result->num_rows > 0) {
$rows = [];
while($row = $result->fetch_assoc()) {
$rows[] = $row["radiob"];
}
}
$totals = array_count_values($rows);
array_count_values() returns an array using the values of array as keys and their frequency in array as values.
http://php.net/manual/en/function.array-count-values.php
SO $rows should be like this
['male','male', 'female']
And array_count_values will give you this
['male' => 2, 'female' => 1]
Now if you want rows to contain more data such as
while($row = $result->fetch_assoc()) {
$rows[] = $row; //assume row is ['name'=>'foo', 'radiob' => 'male']
}
You can first do array_column such as ( to unwrap it )
$totals = array_count_values(array_column($rows, 'radiob'));
array_column() returns the values from a single column of the input, identified by the column_key. Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array.
http://php.net/manual/en/function.array-column.php
In summery the best way is to Aggregate it using the query, but you may have other data besides this you need ( such as name ), in that case do the second method.
Cheers!
Here is a possible solution. There are various ways to do it and I am not 100% certain of the output you want. But this might get you started. I added variables to hold the integer values of the male/female counts. I put them in an array with a key value that matches the values in your database. Then in each loop, the value is incremented on the total of the array element matching the DB row value. At the end I echo the two totals.
$sql = "SELECT radiob FROM playertest";
$result = $conn->query($sql);
$array[ 'Male' => 0, 'Female' => 0 ];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$array[$row["radiob"]]++;
echo $row["radiob"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
echo "Male {$array['Male']}\n";
echo "Female {$array['Female']}\n";
You should modify the code using a group by sentence to look like this
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT radiob,COUNT(*) as total FROM `playertest` group by radiob";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["radiob"] . ": ".$row["total"]."<br>";
}
} else {
echo "0 results";}
$conn->close();
?>

php-mysql How to select the particular number of the row in mysql?

I am new at this and learning the code.
I want to create the php code which select the particular row.
say 5th row or 6th row any row.
I create the code like this
<?php
$servername = "localhost";
$username = "test1";
$password = "pass";
$dbname = "test1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT FIELD1, FIELD2 FROM mytable ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["FIELD1"]. " - Name: " . $row["FIELD2"]. " <br>";
}
} else
{
echo "0 results";
}
$conn->close();
?>
THis code works fine but it give the all data of the table.I want to just select particular row number data.how to do this??
You can do it with the LIMIT statement, say LIMIT 3,1 to select the 4th row. First number is the starting row, second number is the count of rows to select.
$sql = "SELECT FIELD1, FIELD2 FROM mytable LIMIT $row_index, 1";
will give you row $row_index + 1
You can do it using WHERE condition in query as SELECT FIELD1, FIELD2 FROM mytable WHERE id = 1.

Displaying data from database in a Dropdown Menu

I have successfully got my php code to connect to my database and retreieve data and display it. I am now trying to take this data and display it in a dropdown menu, however when I do this the dropdown menu displays the correct number of options that correlates with the data in the database(ie. it gives three options if there is 3 values in the db). But it doesn't display the text all the options are blank. Any ideas as to why it is not displaying the text?
<?php
$dbhost= 'Host IP';
$dbuser ='My Username';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$sql='SELECT event_id FROM events';
mysql_select_db('db_name');
$retval= mysql_query($sql, $conn);
echo'<select name=dropdown value=', '>Dropdown</option>';
while($r= mysql_fetch_array($retval))
{
echo "<option value={$r["event_id"]}>{$r["events"]}</option>";
}
echo "</select>";
?>
http://i.imgur.com/30Uq0Ok.png
The link is what the menu currently returns
Thanks
You did not select events from database. You need to select all(*) or required columns by its name in the query .
Change your query:
$sql='SELECT event_id FROM events';
to :
$sql='SELECT * FROM events';
You also need to take option value inside quotes.
Change this line inside loop:
echo "<option value={$r["event_id"]}>{$r["events"]}</option>";
to:
echo "<option value=\"{$r['event_id']}\">{$r['events']}</option>";
try it like this (change your query to select *)
echo '<option value='.$r["event_id"].'>'.$r["events"].'</option>';
You are just selecting event_id from the table. So, $r["events"] is always empty.
Select the title field, too.
<?php
$dbhost= 'Host IP';
$dbuser ='My Username';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$sql='SELECT event_id,event_title FROM events';
mysql_select_db('db_name');
$retval= mysql_query($sql, $conn);
echo'<select name=dropdown value=', '>Dropdown</option>';
while($r= mysql_fetch_array($retval))
{
echo "<option value={$r["event_id"]}>{$r["event_title"]}</option>";
}
echo "</select>";
?>
I assumed, that the field name is "event_title".

PHP/MySQL outing a table from the data base but excluding a field from a table?

I have a form which allows the user to set what the sort the data by in the table and if it increase or decreasing order
http://damiensplace.co.uk/test/requestTableDisplay.htm
However I want the user to choose to exclude a field (Age Grade) form set the variable but been racking my brain on how to do this but only way I come up with is not neat as I basically need to write two lots of code am I missing a trick?
<html><head><title>MySQL Table Viewer</title></head><body>
<?php
$db_host = '****';
$db_user = '***';
$db_pwd = '***';
$sortOn = $_POST['SortOn'];
$sortIn = $_POST['SortIn'];
$database = '****';
$table = '***';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// sending query
$result = mysql_query("SELECT * FROM {$table} order by {$sortOn} {$sortIn}");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<h1>Table: {$table}</h1>";
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysql_free_result($result);
?>
</body></html>
If someone can point me in the right direction I would be most grateful
Pretty simple. Instead of running this query:
SELECT * FROM {$table} order by {$sortOn} {$sortIn}
run this one:
"SELECT hats, cats, margarine FROM {$table} order by {$sortOn} {$sortIn}
...where hats, cats and margarine are to be replaced by fields in your table. You can specify any number of fields in this way, even down to grabbing only a single field.
You should have your query as follows:
SELECT (columns) FROM (table)
Do not SELECT all, it appears you only want specific columns.

Categories