How to show the average of a column in mysql?
Below is my code which i have tried so far :
<?php
if (isset($_GET["age"]));
$age = ($_GET["age"]);
include($_SERVER["DOCUMENT_ROOT"] . "/includes/config.php");
// Input
$sql = "SELECT AVG(column_name) FROM table_name";
// Check age
if ($age > 99 or $age < 5) {
echo ("We only store data of people between the age of 5 and 99.");
if (!mysqli_query($conn, $sql)) {
die('Error: ' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
}
}
else {
echo ("We got it!");
}
// Close connection
((is_null($___mysqli_res = mysqli_close($conn))) ? false : $___mysqli_res);
die();
?>
But how to exactly define a variable to the result of the AVG with a maximum of 2 decimals?
I want to used and show it into another file (so I will include this one).
What I have right now
<?php
if (isset($_GET["age"]));
$age = ($_GET["age"]);
include($_SERVER["DOCUMENT_ROOT"] . "/3/includes/config.php");
include($_SERVER["DOCUMENT_ROOT"] . "/3/includes/opendb.php");
// My own created code
$sql = $conn->query("SELECT ROUND(AVG(price AS FLOAT), 2) FROM data WHERE age= '$age'");
$data = $sql->mysqli_fetch_assoc();
$avg_data = $data['price'];
echo $avg_data;
// This below is from an other post but don't know how it works and if it is good.
$ratings = $conn->query("SELECT AVG(price) avg_rating FROM data form_id = '" . $age . "'");
$data2 = $ratings->mysqli_fetch_assoc();
$avg_rating = $data2['avg_rating'];
echo $avg_rating;
die();
?>
Use Like This For Getting Average witth two decimal points.
$sql = "SELECT ROUND(AVG(column_name AS FLOAT), 2) FROM table_name";
How I fixed it:
<?php
if (isset($_GET["age"])) {
$age = ($_GET["age"]);
include($_SERVER["DOCUMENT_ROOT"] . "/3/includes/config.php");
$con=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT AVG(price) FROM data WHERE age= '$age'") or die("Error: " . mysqli_error($con));
while($row = mysqli_fetch_array($result)) {
echo $row['AVG(price)'];
echo number_format($row['AVG(price)'], 2);
}
die();
}
else {
echo 'Something went wrong, try again.';
}
?>
$sql = 'SELECT *, ROUND(AVG(column_name), 2) AS avg_value FROM table_name';
avg_value will store the rounded + average value and add * if need to get all the column.
Related
This time I'm trying to make some php code to work with mysqli in order to check if today date is between a range of dates in a Mysql table, if the condition is true I need to print a price from a table otherwise it shuould print a different price from another table. so I already have all sql connections set in another php file, the problem is that when I try the code, it just shows nothing, a blank page only. This is the code im using:
<?php
$currentdate = date("Y/m/d");
//basic include files
require_once('/home/user/public_html/folder/db.php');
$seasonalpricedate = mysqli_query($conn, "SELECT `seasonal_price` FROM `hotel_seasonal_price` WHERE room_type_id = '1' AND $currentdate >= 'seasonal_from' AND $currentdate <= 'seasonal_to';");
$result = ($seasonalpricedate) or die(mysqli_error());
if (mysqli_num_rows($result) != 0) {
$standardprice = mysqli_query($conn, "SELECT `room_price` FROM `hotel_room_price` WHERE price_id = '1'");
if(! $standardprice ){
die('Could not get data: ' . mysqli_error());
}
while($standard = mysqli_fetch_array($standardprice, MYSQL_ASSOC)){
echo "$ {$standard['room_price']} ";
}
} else {
if(! $seasonalpricedate ){
die('Could not get data: ' . mysqli_error());
while($standard2 = mysqli_fetch_array($seasonalpricedate, MYSQL_ASSOC)){
echo "$ {$standard2['seasonal_price']} ";
}
}
}
?>
I already tried both codes with standardprice and seasonalprice working without a conditional, but when I try to do it like this, it does not show anything.
PostData: Im still trying to learn english, so please appologize me if I fail some words, thanks in Advance.
UPDATE: Ok so in this way it works if there is no values true its ok, it shows the standardprice, but if match the date, dont show anything, here is the code changed:
<?php
error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
$currentdate = date("Y-m-d");
//basic include files
require_once('/home/trankilo/public_html/book/db.php');
$seasonalpricedate = mysqli_query($conn, "SELECT `seasonal_price` FROM `hotel_seasonal_price` WHERE room_type_id = '1' AND '$currentdate' >= seasonal_from AND '$currentdate' <= seasonal_to");
$result = ($seasonalpricedate) or die(mysqli_error());
if (mysqli_num_rows($result) != 0) {
$seasonalprice = mysqli_query($conn, "SELECT `seasonal_price` FROM `hotel_seasonal_price` WHERE room_type_id = '1'");
if(! $seasonalprice )
{
die('Could not get data: ' . mysqli_error());
while($standard2 = mysqli_fetch_array($seasonalprice, MYSQL_ASSOC))
{
echo "$ {$standard2['seasonal_price']} ";
}
}
} else {
$standardprice = mysqli_query($conn, "SELECT `room_price` FROM `hotel_room_price` WHERE price_id = '1'");
if(! $standardprice )
{
die('Could not get data: ' . mysqli_error());
}
while($standard = mysqli_fetch_array($standardprice, MYSQL_ASSOC))
{
echo "$ {$standard['room_price']} ";
}
}
mysqli_close($conn);
?>
So close to make it work, thanks to
UPDATE: Because you are also updated your OP, now i found what causes the problem. Ther proble were when you says: die('Could not get data: ' . mysqli_error()); And after that you want to try a while loop. while won't executed, because you terminated the script with a die(); Move the while to the else case of your if condition. See my comments.
Use this:
error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
//Also display your errors.
display_errors(true);
$currentdate = date("Y-m-d");
//basic include files
require_once('/home/trankilo/public_html/book/db.php');
//Put your query into a variable, so you can dump / print it.
$sql = "SELECT `seasonal_price`"
. " FROM `hotel_seasonal_price`"
. " WHERE room_type_id = '1'"
. " AND '" . $currentdate . "' >= seasonal_from"
. " AND '" . $currentdate . "' <= 'seasonal_to'";
echo $sql;
//Try to run it in the sql directly. Is it gives back you any result?
//Do not need to
$result = mysqli_query($conn, $sql) or die(mysqli_error());
if (mysqli_num_rows($result) != 0) {
//Check if we have result by echoing some dummy text
echo "Yes, we have result!";
$sql = "SELECT `seasonal_price` FROM `hotel_seasonal_price` WHERE room_type_id = '1'";
//Do the same as the previous query. Does it gives you back anything?
$seasonalprice = mysqli_query($conn, $sql);
if (!$seasonalprice) {
//I do not really get what happens here. If you have no seasonalprice,
//then you can not fetch_array on that!
//Move this whole section.... You've say die, and after that do a while?
die('Could not get data: ' . mysqli_error());
} else {
while ($standard2 = mysqli_fetch_assoc($seasonalprice)) {
echo "$ " . $standard2['seasonal_price'] . " ";
}
}
} else {
//Same as previous
$sql = "SELECT `room_price` FROM `hotel_room_price` WHERE price_id = '1'";
$standardprice = mysqli_query($conn, $sql);
if (!$standardprice) {
die('Could not get data: ' . mysqli_error());
//same here, move the while to the else...
} else {
while ($standard = mysqli_fetch_array($standardprice, MYSQL_ASSOC)) {
echo "$ {$standard['room_price']} ";
}
}
}
mysqli_close($conn);
im trying to query the database and apply code to each result and insert a record per result to a databse. This code works but only does it for the last result row. Ive tried foreach but cannot get it to work most likley because i dont understand how it should work. Please help and thank you
<?php
if(isset($_POST['bill1'])){
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
require ('dbconnect.php');
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
$invoicedate= $_POST['invoicedate'];
$invoiceduedate= $_POST['invoiceduedate'];
echo 'post is good';
require ('dbconnect.php');
echo 'db connect';
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM customer WHERE terms = 1");
while($row = mysqli_fetch_array($result)) {
echo 'array good';
$item = $row['inputItem'];
$itemdescription = $row['description1'];
$itemprice = $row['itemprice1'];
$id = $row['id'];
$paidstatus = 5;
$totaldue = $itemprice;
require ('dbconnect.php');
echo $item;
echo $itemdescription;
echo $itemprice;
echo $id;
echo $paidstatus;
echo $invoicedate;
echo $invoiceduedate;
$resulttt = mysqli_query($con,"SELECT invoice_number FROM invoices ORDER BY invoice_number DESC LIMIT 1");
while($row = mysqli_fetch_array($resulttt)){
$addone = "1";
$invoicenewnumber = $addone + $row [invoice_number];
}
echo $invoicenewnumber;
//echo $row [invoice_number];
$invoice_number = $invoicenewnumber;
require ('dbconnect.php');
$put = mysqli_query($con,"INSERT INTO invoices (item, description, item_total, id, paidstatus, duedate, invoicedate, invoice_number, total_due)VALUES('$item', '$itemdescription', '$itemprice', '$id', '$paidstatus', '$invoiceduedate', '$invoicedate', '$invoice_number', '$totaldue')");
if (!mysqli_query($con,$put))
die('Error: ' . mysqli_error($con));
echo 'succsess';
}
?>
<?php
$resulttt = mysqli_query($con,"SELECT invoice_number FROM invoices ORDER BY invoice_number DESC LIMIT 1");
while($row = mysqli_fetch_array($resulttt))
{
$addone = "1";
$invoicenewnumber = $addone + $row [invoice_number];
$invoice_number = $invoicenewnumber;
$put = mysqli_query($con,"INSERT INTO invoices (item, description, item_total, id, paidstatus, duedate, invoicedate, invoice_number, total_due)VALUES('$item', '$itemdescription', '$itemprice', '$id', '$paidstatus', '$invoiceduedate', '$invoicedate', '$invoice_number', '$totaldue')");
}
?>
Try this insert the second query in the while loop.
And read the comment where ever you find them in the Answer
Note:You need the connection only one time in whole page.
<?php
if(isset($_POST['bill1']))
{mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
require ('dbconnect.php'); You need the connection only once
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}}
$invoicedate= $_POST['invoicedate'];
$invoiceduedate= $_POST['invoiceduedate'];
echo 'post is good';
//require ('dbconnect.php'); Dont need here
// echo 'db connect'; Dont need here
//if (mysqli_connect_errno()) {
// echo "Failed to connect to MySQL: " . mysqli_connect_error();
// }
$result = mysqli_query($con,"SELECT * FROM customer WHERE terms = 1");
while($row = mysqli_fetch_array($result)) {
echo 'array good';
$item = $row['inputItem'];
$itemdescription = $row['description1'];
$itemprice = $row['itemprice1'];
$id = $row['id'];
$paidstatus = 5;
$totaldue = $itemprice;
require ('dbconnect.php');
echo $item;
echo $itemdescription;
echo $itemprice;
echo $id;
echo $paidstatus;
echo $invoicedate;
echo $invoiceduedate;
$resulttt = mysqli_query($con,"SELECT invoice_number FROM invoices ORDER BY invoice_number DESC LIMIT 1");
while($row = mysqli_fetch_array($resulttt)){
$addone=$addone+1;//If you want to add one to the invoice number you have to use this.
$invoicenewnumber = $addone + $row ['invoice_number'];//}//remove the closing while loop from here,
//Added quete to the Invoice_number
echo $invoicenewnumber;
//echo $row [invoice_number];
$invoice_number = $invoicenewnumber;
require ('dbconnect.php');
$put = mysqli_query($con,"INSERT INTO invoices (item, description, item_total, id, paidstatus, duedate, invoicedate, invoice_number, total_due)VALUES('$item', '$itemdescription', '$itemprice', '$id', '$paidstatus', '$invoiceduedate', '$invoicedate', '$invoice_number', '$totaldue')");
}
if (!mysqli_query($con,$put))
die('Error: ' . mysqli_error($con));
echo 'succsess';
}
?>
How can I disable the round up in my PHP script. If I sum up something it only displays the rounded Number.
<?php
$con=mysqli_connect("localhost","XXXX","XXXX","XXXX");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM energrid WHERE ID = 1 ");
while($row = mysqli_fetch_array($result)) {
$wert = $row['Wert'];
}
$result = mysqli_query($con,"SELECT * FROM energrid WHERE ID = 3 ");
while($row = mysqli_fetch_array($result)) {
$wert1 = $row['Wert'];
}
mysqli_close($con);
echo "here we go.:";
echo $wert + $wert1;
?>
Ok, I guess I've found my mistake. The values are like 3,5 with a , instead of a .
How can I change that if these are values directly from the MySQL DB.?
1.You can use number_format function
2.optimize your code -there is no need of while loop to do this
<?php
$db = mysql_connect("localhost","username","password"); ///connect to mysql
if (!$db) {
// throw error if not connect
die("Database connection failed miserably: " . mysql_error());
}
$db_select = mysql_select_db("databasename",$db); ///select database
if (!$db_select) {
//database connection error
die("Database selection also failed miserably: " . mysql_error());
}
$sum=0;
$result = mysqli_query($db,"SELECT sum(wert) as sum FROM energrid WHERE ID in ('1','3') ");
$row = mysqli_fetch_array($result)
$sum =$row['sum'];
`enter code here`
echo number_format($sum,'number','.','');
//where number-no. of place you want to round off
?>
use str_replace() like this to replace the comma , in number by decimal point .
$a = "3,5";
str_replace(",",".",$a);
Try using a cast like this :
echo (int)$wert + (int)$wert1;
echo (float)$wert + (float)$wert1;
I am trying to use AES_DECRYPT in MySQL to decrypt a successfully encrypted SSN. In the output I get the word "Array" instead of the actual data from that field. My PHP and MySQL knowledge is a bit rusty, so I'm sure it's something silly I overlooked. Any help would be appreciated.
OUTPUT:
verify_name other_names ssn dob
: test : test : Array : test
CODE:
$key="88b871WZ3SntWK67rN3l2J1SvMqsOjyk";
$SQLstring = "SELECT * FROM applications";
$QueryResult = #mysql_query($SQLstring, $conn) or die("Query Problem - "
. mysql_error($conn) . " - Error Number - "
. mysql_errno($conn));
echo "verify_name other_names ssn dob";
$num_result = mysql_num_rows($QueryResult);
for ($i = 0; $i < $num_result; $i++)
{
$row = mysql_fetch_array($QueryResult);
$SQLstring2 = "SELECT AES_DECRYPT(ssn,'$key') FROM applications WHERE name='" . $row["name"] . "'";
$QueryResult2 = #mysql_query($SQLstring2, $conn) or die("Query Problem - "
. mysql_error($conn) . " - Error Number - "
. mysql_errno($conn));
$num_result2 = mysql_num_rows($QueryResult2);
for ($j = 0; $j < $num_result; $j++){
$ssndecrypt = mysql_fetch_array($QueryResult2);
echo $ssndecrypt[0];
}
echo $row["verify_name"];
echo $row["other_names"];
echo $ssndecrypt;
echo $row["dob"];
It's because you're fetching the result as an array.
$ssndecrypt = mysql_fetch_array($QueryResult2);
...
echo $ssndecrypt;
It's echoing Array because you never reassign the $ssndecrypt variable.
The core of the problem, however, seems to be that you're needlessly complicating your queries. There's no reason to query the table twice when you can just do:
SELECT verify_name,
other_names,
dob,
AES_DECRYPT(ssn,'$key') AS ssn
FROM applications
This simplifies the code quite a bit:
$stmt = "SELECT verify_name, other_names, dob, AES_DECRYPT(ssn,'$key') AS ssn FROM applications";
$result = #mysql_query($stmt, $conn) or die("Query Problem - " . mysql_error($conn) . " - Error Number - " . mysql_errno($conn));
echo "verify_name other_names ssn dob";
while ($row = mysql_fetch_assoc($result))
{
echo $row["verify_name"];
echo $row["other_names"];
echo $row["ssn"];
echo $row["dob"];
}
Ideally, though, you should be using PDO instead of the mysql_* functions:
try {
$dbh = new PDO('mysql:host=localhost;dbname=mydb', $user, $pass);
foreach($dbh->query("SELECT verify_name, other_names, dob, AES_DECRYPT(ssn,'$key') AS ssn FROM applications") as $row) {
echo $row["verify_name"];
echo $row["other_names"];
echo $row["ssn"];
echo $row["dob"];
}
$dbh = null;
} catch (PDOException $e) { die("ERROR: " . $e->getMessage()); }
I'm writing a quiz program using PHP and a bit of Javascript. The questions can be answered correctly when IE or Chrome is used but Firefox refreshes the page and increments the session variable.
Here's a code snippet:
if(isset($_GET['answer1']))
{
if($_GET['answer'] == $_GET['answer1'])
{
include 'config.php';
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db, $con);
$userId = $_SESSION['userId'];
$wordNow = $_SESSION['word'];
$sql3 = "SELECT * FROM userAccomplishments Where UserId = '$userId' AND
word = '$wordNow'";
$result3 = mysql_query($sql3);
if (mysql_num_rows($result3) == 0) {
$sql4 = "SELECT wordId from allwords WHERE word = '$wordNow'";
$result = mysql_query($sql4);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting from random number";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
$wordId = $row["wordId"];
// echo $row["word"] . " " ."<BR>" ;
}
list($usec, $sec) = explode(' ', microtime());
$script_end = (float) $sec + (float) $usec;
$elapsed_time = (float)($script_end - $script_start);
$elapsed_time = $_GET['formvar'];
$sql2 = "INSERT INTO userAccomplishments (UserId, word, TimeTaken, wordId)
VALUES ('$userId', '$wordNow', '$elapsed_time', '$wordId')";
echo 'You got '. $wordNow . ' in ' .$elapsed_time . ' seconds. <BR><BR>';
$result = mysql_query($sql2);
}
$_SESSION['views'] = $_SESSION['views'] + 1;
}
else
{
$_SESSION['views'] = $_SESSION['views'] + 1;
echo 'Keep studying <BR>';
}
}
else
{
$_SESSION['views'] = 1;
}
Doesn't look like you're calling session_start(). Make sure you call it to get your session in gear! Woo! Yeah!