Conditional mysqli date range check to print a price in sql - php

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);

Related

How to show average from mysql

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.

Updating field in Database with if else statement

I am working on recieveing an item from another application with the use of $_POST and I am trying to see if that item already exists in the database. If it does, then $count increases by one. If it does not exist in the database, then it will added in with the use of INSERT INTO.
Here is my code:
<?php
date_default_timezone_set('Asia/Manila');
$today = date('m-d-Y');
echo $today;
$con= mysqli_connect("******","******","******")
or die ('Error: ' . mysql_error());
mysqli_select_db($con,"a3656574_opacmin");
$sql= "SELECT keyWord FROM searchedWords";
$result= mysqli_query($con,$sql);
if($result==$_POST[keyWord])
{
$upD="UPDATE searchedWords SET countr = countr + 1";
while (!mysqli_query($con,$upD))
{
die('Error: ' . mysqli_error($con));
}
}
else
{
$insertIn="INSERT INTO `searchedWords`( `keyWord`, `countr`) values ('$_POST[keyWord]',1)";
while (!mysqli_query($con,$insertIn))
{
die('Error: ' . mysqli_error($con));
}
}
?>
I don't know what's wrong. No items are sent to the database at all. Does anyone know how to fix it?
Change your code like this...
$result= mysqli_query($con,"SELECT keyWord FROM searchedWords");
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if($row['keyWord']==$_POST[keyWord])
{
$upD="UPDATE searchedWords SET countr = countr + 1";
while (!mysqli_query($con,$upD))
{
die('Error: ' . mysqli_error($con));
}
}
$result==$_POST['keyWord'] won't work becase $result is object there so...
After this line
$result= mysqli_query($con,$sql);
You have to fetch the data
$keyword = '';
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$keyword = $row["keyWord"];
}

Query error update field mysql

I am very frustrated with the function below. It is not updated my flag in the database. I have tried putting the ones and zeros inbetween quotes and not. I have the field set to small integer in database. Do you see what I am doing wrong? The entry is there but the 1 is not updating to 0.
function postValue(){
global $customerID;
$query="SELECT flag FROM welcomecall WHERE customerID= '$customerID'";
echo $query;
$result = mysql_query($query) or die('Error in the query: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "The customer flag is ". $row["flag"];
}
if ($row['flag']=='0'){
$query="UPDATE welcomecall SET flag='1' WHERE customerID='$customerID'";
$result = mysql_query($query) or die('Error in the query: ' . mysql_error());
}
else if($row['flag']=='1'){
$query="UPDATE welcomecall SET flag='0' WHERE customerID='$customerID'";
$result = mysql_query($query) or die('Error in the query: ' . mysql_error());
}
}
When the while expression exits, there'll be no $row left:
while ($row = mysql_fetch_assoc($result)) {
So this will not be true:
if ($row['flag']=='0'){
Consider moving the if statements inside the while loop.
Looks like you're using logic outside of your loop that belongs inside of your loop:
function postValue(){
global $customerID;
$query="SELECT flag FROM welcomecall WHERE customerID= '$customerID'";
echo $query;
$result = mysql_query($query) or die('Error in the query: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "The customer flag is ". $row["flag"];
// Moved
if ($row['flag']=='0'){
$query="UPDATE welcomecall SET flag='1' WHERE customerID='$customerID'";
$result = mysql_query($query) or die('Error in the query: ' . mysql_error());
}
else if($row['flag']=='1'){
$query="UPDATE welcomecall SET flag='0' WHERE customerID='$customerID'";
$result = mysql_query($query) or die('Error in the query: ' . mysql_error());
}
}
}

Session variables working when testing with Chrome and IE but not Firefox

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!

mysql error in php

i'm trying to run this php code which should display a quote from mysql, but can't figure out where is it going wrong. the result variable is null or empty. can someone help me out. thanks!
<?php
include 'config.php';
// 'text' is the name of your table that contains
// the information you want to pull from
$rowcount = mysql_query("select count(*) as rows from quotes");
// Gets the total number of items pulled from database.
while ($row = mysql_fetch_assoc($rowcount))
{
$max = $row["rows"];
//print_r ($max);
}
// Selects an item's index at random
$rand = rand(1,$max)-1;
print_r ($rand);
$result = mysql_query("select * from quotes limit $rand, 1") or die ('Error: '.mysql_error());
if (!$result or mysql_num_rows($result))
{
echo "Empty";
}
else{
while ($row = mysql_fetch_array($result)) {
$randomOutput = $row['cQuotes'];
echo '<p>' . $randomOutput . '</p>';
}
}
$result = mysql_query("SELECT * FROM quotes ORDER BY rand() LIMIT 1") or die ('Error: '.mysql_error());
if (!$result || mysql_num_rows($result) == 0)
echo "Empty";
else {
while ($row = mysql_fetch_array($result)) {
$randomOutput = $row['cQuotes'];
echo '<p>' . $randomOutput . '</p>';
}
}
// your script probably can't go on without this file?
require 'config.php';
// I prefer to always pass the connection resource to mysql_query/mysql_real_escape_string
// assume $mysql = mysql_connect....
$result = mysql_query("SELECT Count(*) AS rows FROM quotes", $mysql)
or die(mysql_error());
// there's only one row with only one column, so mysql_result() is fine
$rowcount = mysql_result($result, 0, 0);
$rand = rand(0,$rowcount-1);
$result = mysql_query("SELECT cQuotes FROM quotes LIMIT $rand, 1", $mysql)
or die ('Error: '.mysql_error());
// there's either one or zero records. Again, no need for a while loop
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if ( !$row ) {
echo "Empty";
}
else{
// do you have to treat $row['cQuotes'] with htmlspecialchars()?
echo '<p>', $row['cQuotes'], '</p>';
}
if ($result && mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$randomOutput = $row['cQuotes'];
echo '<p>' . $randomOutput . '</p>';
}
} else {
echo "Empty";
}

Categories