How to create Holiday Function in PHP? - php

I'm trying to make a function to generate holiday in PHP.
I've stored the holiday date in Oracle Table:
HOLIDAY
01-JAN-15
03-JAN-15
04-JAN-15
etc
My question is, how to make a function to get holiday date?
I mean, I need to find out that is_holiday('01-JAN-15') holiday is TRUE.
Here's my source code:
<?php
include "config/connect.php";
function is_holiday($thedate)
{
$sql = OCIParse($connect, "SELECT * FROM UF2T_HOLIDAY WHERE HOLIDAY = '".$thedate."'");
ociexecute($sql);
$result = oci_fetch_array($sql);
if(!empty($result[0]))
{
$holiday = "TRUE";
}
else
{
$holiday = "FALSE";
}
return $holiday;
}
echo is_holiday("08-JAN-15");
?>
This code doesn't work and always return FALSE.
What I'm supposed to do to make this code work?
Additional information:
I try to run it outside of a function, something like this :
<?php
include "config/connect.php";
$thedate = '01-JAN-15';
$sql = OCIParse($connect, "SELECT HOLIDAY FROM UF2T_HOLIDAY WHERE HOLIDAY = '".$thedate."'");
ociexecute($sql);
$result = oci_fetch_array($sql);
if(!empty($result[0]))
{
$holiday = "TRUE";
}
else
{
$holiday = "FALSE";
}
echo $holiday;
?>
This code is work. So I think the problem is around the function. Any suggestion? Please help. Thanks in advance.
Sorry for my bad English. :D

I think, that problem is, that variable $connect is not available in your function. Try this:
function is_holiday($thedate, $connect)
and then call the function:
echo is_holiday("08-JAN-15", $connect);

That's becuase in PHP global variables by default are not visible in the functions. In your case the connection inside your function is a local variable which value is undefined. Change your function like this:
function is_holiday($thedate)
{
global $connect;
$sql = OCIParse($connect, "SELECT * FROM UF2T_HOLIDAY WHERE HOLIDAY = '".$thedate."'");
ociexecute($sql);
...

Related

How to fetch and dispaly specific data with PDO

I'm having issues making my project for lesson attendance and management work the way I'd like it to. Sorry if this has already been addressed here. After days of searching, I still cannot for the life of me find a way to display a limited result set from my DB query to my home page.
This part of the project gets all Towns listed on my homepage like so:
Verona
Mantova
Rovereto
Bardolino
...
What I'd rather want is to get control over whatever is displayed! Specifically, I'd like to have ONLY Rovereto and Bardolino returned (as example). I'm thinking of probably doing this with additional page e.g. index1.php so when this page is loaded it will show only desired values and not all fetched values!
The search function result is also case sensitive. If I type "Bardolino", I get result but with "bardolino", no joy at all. I'm new to this, please help me out. Thank you very much.
File index.php:
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Lesson Number</th>
<th>Town</th>
</tr>
</thead>
<tbody>
<?php
for($i=0; $i < count(User::get_all_users()); $i++){
echo "<tr>";
echo "<td>".User::get_all_users()[$i]['id']."</td>";
echo "<td>".Lesson::get_lesson_by_id(User::get_all_users()[$i]['lesson_id'])['number']."</td>";
echo "<td>".show_town(Lesson::get_lesson_by_id(User::get_all_users()[$i]['lesson_id'])['town_id'])."</td>";
echo "</tr>";
}
?>
File user_controller.php:
if(isset($_GET['type']) && $_GET['type'] == 'search'){
global $user_search_list;
$user_search_list= array();
for($i=0; $i < count(User::get_all_users()); $i++){
$user = User::get_all_users()[$i];
$lesson_number = Lesson::get_lesson_by_id($user['lesson_id'])['number'];
$town_name = show_town(Lesson::get_lesson_by_id($user['lesson_id'])['town_id']);
if(strpos($lesson_number,$_GET['search_term']) !== False ||
strpos($town_name,$_GET['search_term']) !== False)
{
$user_search_list[] = $user;
}
}
$_SESSION['search_list'] = $user_search_list;
header("Location: search_user_list.php");
exit();
}
if(isset($_GET['type']) && $_GET['type'] == 'reserve'){
$user = User::get_user_by_id($_GET['user_id']);
if(!empty($_GET['seat_id'])) {
if(count($_GET['seat_id']) * $user['price'] > intval(Balance::get_user_balance($_SESSION['user_id'])['amount'])){
header("Location: reserve.php?user_id=".$user['id']."&balance_error=set");
exit();
}else{
foreach($_GET['seat_id'] as $seat_id){
echo $seat_id;
echo "<br>";
Reservation::create_reservation('', $_SESSION['user_id'], $_GET['user_id'], $seat_id, getdate()[0]);
Balance::update_balance($_SESSION['user_id'], intval(Balance::get_user_balance($_SESSION['user_id'])['amount']) - intval(User::get_user_by_id($_GET['user_id'])['price']));
Seat::reserve_seat($seat_id,$_SESSION['user_id']);
Action::create_action('', "User - ".$_SESSION['user_id'].'reserve Seat ID - '.$seat_id. " on User ID - ".$_GET['user_id'],"reserve" , getdate()[0]);
}
if(count(Reservation::get_all_reservations_by_user($_SESSION['user_id'])) == 5){
Balance::update_balance($_SESSION['user_id'] ,intval(Balance::get_user_balance($_SESSION['user_id'])['amount']) + 10);
header('Location: index.php?reserve_success=set&reward=set');
exit();
}
header('Location: index.php?reserve_success=set');
exit();
}
}
else{
header("Location: reserve.php?user_id=".$user['id']."&seat_error=set");
exit();
}
}
function show_town($id){
return Place::get_place_by_id(Town::get_town_by_id($id)['place_id'])['name'].
}
File User.php:
class User
{
static $id;
static $lesson_id;
static $starting_date;
static $starting_time;
static $arrival_time;
static $price;
static function create_user($id, $lesson_id, $starting_date, $starting_time, $arrival_time, $price){
global $db;
$sql = "INSERT INTO `lesson_database`.`users` (`id`, `lesson_id`, `starting_date`, `starting_time`, `arrival_time`, `price`) VALUES (NULL, '".$lesson_id."', '".$starting_date."', '".$starting_time."', '".$arrival_time."', '".$price."');";
$db_result = $db->query($sql);
if($db_result){
return True;
}
else{
return False;
}
}
static function get_all_users(){
global $db;
$sql = "SELECT * FROM `users`";
$db_result = $db->query($sql);
if($db_result){
return $db_result->fetchAll();
}
else {
return False;
}
}
static function get_user_by_id($id){
global $db;
$sql = "SELECT * FROM `users` WHERE `id` = '".$id."' LIMIT 1";
if(!isset($sql)){
echo "not set";
}
$db_result = $db->query($sql);
if($db_result){
$db_row = $db_result->fetch(PDO::FETCH_ASSOC);
if($db_row){
return $db_row;
}
else {
return False;
}
}
return False;
}
static function delete_user($id){
global $db;
$sql = "DELETE FROM `lesson_database`.`users` WHERE `users`.`id` = '".$id."'";
$db_result = $db->query($sql);
if($db_result){
return True;
}
else{
return False;
}
}
}
I feel a little bit like you've jumped ahead and skipped some basics as lots of this doesn't make sense.
Firstly, you've said about using PDO in the title but you're not using PDO in your queries, you really need to be using PDO so if you're not sure how then try and find a good tutorial about using prepared statements.
Secondly, you're doing loads of extra calls within loops and duplicating calls all over the place so I think you could do with looking for a tutorial on design patters and think about how you could streamline this code.
As a very basic you could get all your users once by using a fetchAll (or fetch_assoc i think in mysqli) and then just loop through that variable e.g.
<?php
$users = User::get_all_users;
foreach($users as $user){
$lesson = Lesson::get_lesson_by_id($user['lesson_id']);
echo "<tr>";
echo "<td>".$user['id']."</td>";
echo "<td>".$lesson['number']."</td>";
echo "<td>".show_town(lesson['lesson_id'])['town_id'])."</td>";
echo "</tr>";
}
as for your search the simplest way would be to pass a search string in the url and use global $_GET['searchString'] (obviously you will need to sanitize the string) and then search for results directly in sql such as
SELECT * FROM table WHERE town LIKE . $yourvariable .% (ideally in your newly learned PDO style)
then it will be both not case sensitive and will also mean you've got the data in the first place so you don't waste time looping through a bunch of extra rows.
If you need to make this case insensitive in the meantime then the simplest way is to convert the search and the comparison string to the same case (strtolower for example) and then they will match
It also strikes me that your database might not be in good shape as I would be surprised to find that a user table contains lesson ids, so you might want to look into the idea of database normalisation, this will then allow you to do some more creative queries and more easily gather together accurate information for whatever your task is (i.e. make it scalable and manageable).
I hope some of that is helpful, sorry it's not a quick answer but it's not a quick problem I think. Don't fear though, we all started somewhere!!

PHP function returns wrong values

I have this function
function getNick($uid)
{
$sqli = "SELECT nick FROM users WHERE userid='".$uid."'";
mysqli_real_escape_string($con,$sqli);
$resulti = mysqli_query($con,$sqli);
$rowi = mysqli_fetch_assoc($resulti);
if($resulti->num_rows > 0) return $rowi["nick"];
else return "(none)";
}
Basically it should return me nick based on user's id. Problem is that I only keep getting '(none)'. What is interesting I printed actual $sqli and copied it into phpMyAdmin and it worked as expected. I even tried to just print nick without IFs but I ended up with empty string. What might be the issue? Am I overlooking something? Thanks
<?php
$con = mysqli_connect("localhost","root","","test");
function getNick($uid,$con)
{
$sqli = "SELECT nick FROM users WHERE userid='".$uid."'";
mysqli_real_escape_string($con,$sqli);
$resulti = mysqli_query($con,$sqli);
$rowi = mysqli_fetch_assoc($resulti);
if($resulti->num_rows > 0) return $rowi["nick"];
else return "(none)";
}
echo getNick(1,$con);
?>
it works
variable scope problem
use above method to pass connection in method or
use $GLOBALS['con'] to access connection in method getNick

mysqli and global variable

I've been been on this for hours trying to find the small mistake I've done and I just can't find it... All I'm doing is calling a variable as global in a function and it's just not working even though it worked fine with the function above it...
I get an error saying mysqli is null...
include 'data/mysqli_connect.php';
function process_login(){
global $mysqli;
$username = $_SESSION['username'];
$sql = "SELECT * FROM auth WHERE user='".mysqli_real_escape_string($mysqli,$username)."'";
$query = mysqli_query($mysqli,$sql);
if(mysqli_num_rows($query)>0){
$sql = "DELETE FROM auth WHERE user='".mysqli_real_escape_string($mysqli,$username)."'";
$query = mysqli_query($mysqli,$sql);
if(!$query){
die(mysqli_error());
}
}
$sql = "INSERT INTO auth (user, session) VALUES ('".mysqli_real_escape_string($mysqli,$username)."', '".$_SESSION['id']."')";
$query = mysqli_query($mysqli,$sql);
if(!$query){
echo "Can not insert info into database!<br />". mysqli_error();
}else{
header("Location:chat.php");
}
}
function logout(){
global $mysqli;
$sql = "DELETE FROM auth WHERE session='".mysqli_real_escape_string($mysqli,$_SESSION['id']). "'";
$query = mysqli_query($mysqli,$sql);
if(!$query){
echo "Can not delete info from database!";
}else{
session_destroy();
header("Location: chat.php");
}
}
function get_username(){
global $mysqli;
$sql = "SELECT * FROM auth WHERE session='".mysqli_real_escape_string($mysqli,$_SESSION['id']). "'";
$query = mysqli_query($mysqli,$sql);
$row = mysqli_fetch_array($query);
if(mysqli_num_rows($query) == "0"){
$username = "Guest";
}else{
$username = $row['user'];
}
return $username;
}
function post_message(){
global $mysqli;
$text = addslashes(htmlentities(htmlspecialchars($_REQUEST['text'])));
$sql = "INSERT INTO chat (time, user, text) VALUES ('".date("H:i")."', '".get_username()."', '".$text."')";
$query = mysqli_query($mysqli,$sql);
if(!$query){
die(mysqli_error());
}
}
mysqli_connect.php
$mysqli = mysqli_connect(localhost, "info", "info", "info");
Like I said it worked on the function above this one but not this one, it doesn't make sens... I'm guessing I have a stupid mistake in there somewhere just don't know where.
By the way,the functions that I tested and work are process_login() and logout() and get_username()
get_username() runs first then process_login(). post_message() runs from a jquery code that calls it when i press on enter that probably works fine since i can see the error code when i press enter.
Oh and sorry about the bad code formatting,not sure how to fix it on here.
Thank you for any help or advice you may find.
How/When is post_message() called? From what you edited in, I can't find anything specifically in that that would clear the $mysqli variable - but to debug it, we would need more of the program flow.
Or you could create a 'hack' in the code and within post_message() after you declare global $mysqli;, do include 'data/mysqli_connect.php'; again since the $mysqli reference to your DB connection has been lost by then. But, ideally, you need to follow the flow of your code to figure out where to fix it correctly - and your flow seems not to be able to be posted fully, or is too great to post fully here.
(Too long for a comment, so this response comes in answer form, my apologies.)
Instead of making $mysqli a global variable, try passing it as an additional parameter to your functions. I was having the same problem and that's how i solved it. ie...
function post_message($mysqli){
$text = addslashes(htmlentities(htmlspecialchars($_REQUEST['text'])));
$sql = "INSERT INTO chat (time, user, text) VALUES ('".date("H:i")."',
'".get_username()."', '".$text."')";
$query = mysqli_query($mysqli,$sql);
if(!$query){
die(mysqli_error());
}
Hope this works for you.

mysqli/mysql query inside function not working [duplicate]

This question already has answers here:
Executing mysqli_query inside a function
(2 answers)
Closed 1 year ago.
I'm tryin to build some functions for a website of mine and some of them consist in
fetching data from the mysql database. When I test the code outside of the function
it seems to work properly. So here it is, The first page:
require('db.php');
require('functions.php');
$email = 'sample#gmail.com';
if (user_exists($email) == true){
echo "Good news, this exists";
}
Now db.php :
$db = new MySQLi("localhost","test","test","test");
if ($db->connect_errno){
echo "$db->connect_errno";
}
And the functions.php file:
function sanitize ($data){
$db->mysqli_real_escape_string($data);
}
function user_exists($usermail){
$usermail = sanitize($usermail);
$query = $db->query("SELECT COUNT(userId) FROM users WHERE userEmail= '$usermail' ");
$check = $query->num_rows;
return ($check == 1) ? true : false;
}
And the error I'm getting when accessing the first file is:
Notice: Undefined variable: db in C:\xampp\htdocs\auctior\inc\functions.php on line 6
Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\auctior\inc\functions.php on line 6
SO I've required/included the db.php where $db is the mysqli connect. And within the same file(first file) I call the functions located at functions.php
Thank you in advance,
I'd appreciate your help as this is pissing me off......
You probably need to use the global keyword, otherwise $db is considered a var in local scope.
function sanitize ($data){
global $db;
$db->mysqli_real_escape_string($data);
}
function user_exists($usermail){
global $db;
$usermail = sanitize($usermail);
$query = $db->query("SELECT COUNT(userId) FROM users WHERE userEmail= '$usermail' ");
$check = $query->num_rows;
return ($check == 1) ? true : false;
}
Try to connect inside the function, and connection needs to be included before you include functions.
Something like this:
function user_exists($usermail){
$db = new MySQLi("localhost","test","test","test");
$usermail = sanitize($usermail);
$query = $db->query("SELECT COUNT(userId) FROM users WHERE userEmail= '$usermail' ");
$check = $query->num_rows;
return ($check == 1) ? true : false;
}

Call to a member function fetch_assoc() on a non-object

Here's my function:
function get_fname($un){
$registerquery = $this->conn->query("SELECT f_name FROM tz_members WHERE
usr='".$un."'");
while ($row = $registerquery->fetch_assoc()) {
return $fname = $row[$un];
}
}
Edit:
I chose to answer my own question because it has an editor.
#Mark Baker:
<?php
require_once 'Mysql.php';
$mysql = new Mysql();
?>
<html>
<head>
</head>
<body>
<h4><?php echo $mysql->get_fname("joann"); ?></h4>
</body>
</html>
That's how I am doing it...
It seems that your query failed. Because in that case query returns false. So try this:
$registerquery = $this->conn->query("SELECT f_name FROM tz_members WHERE
usr='".$un."'");
if ($registerquery) {
while ($row = $registerquery->fetch_assoc()) {
return $fname = $row[$un];
}
}
The failure may be caused by a syntax error in your query when $un contains characters that break the string declaration (like ' or \). You should use MySQLi::real_escape_string to escape that characters to prevent that.
Additionally, a function can only return a value once. So the while will be aborted after the first row.
$fname = $row[$un]; is assigning the value in $row[$un] to the variable $fname, then returning the result.
It's pointless doing that assignment to $fname because $fname is simply a local variable within the function.... if it's defined as global, then it's not good programming practise.
If echo $mysql->get_fname("joann") is the line where you're calling the get_fname() function, then how are you setting $mysql?
And what do you think will happen if the database query doesn't find any valid result for the query?
while ($row = fetch_assoc($registerquery)) {
return $fname = $row[$un];
}
}
Is it possible you forgot to give a table name in the connection?
$conn = new mysqli('localhost', 'root', 'password', 'ANY VALUE HERE??');

Categories