您需要重新组织此脚本,但没有正确检查。您还存在SQL注入问题:
<?php
# Add this to the top, don't add it as an "if" conditional
session_start();
# Add this once and also at the top, regardless of if you use it
include('../db_config/connection.php');
# Same
include('check_login.php');
# I would make a function for this (move to it's own page and include it)
function getUserInfo($uid,$conn)
{
$uid = (is_numeric($uid))? $uid : false;
if(!$uid)
return false;
# Fetch
$result = $conn->query("SELECT * FROM user_info where user_index = '$uid'");
if($result->num_rows > 0) {
$row = $result->fetch_assoc();
return $row;
}
return [];
}
# Create a function to add the user's leave BUT YOU NEED TO BIND PARAMETERS
# HERE! WHAT YOU HAVE IS NOT SAFE!!
function addUserLeave($uid,$array,$conn)
{
# Question marks are placeholders for values
$sql = "INSERT INTO tblleaves(leavetype, todate, fromdate, description, status, isRead, user_index) VALUES (?,?,?,?,1,1,?)";
# Prepare the statement
$query = $conn->prepare($sql);
# Bind the values to question marks in the statement, use the first parameter in this
# method to indicate to the method what each value type each should be
$query->bind_param('ssssssi',$array['leavetype'], $array['fromdate'], $array['todate'], $array['description'],$uid);
# Now run the query
return $query->execute($sql);
}
# Set a default error
$error = 'You must submit the form';
# You have to use braces to cover all the other assigned post values
if(isset($_POST['apply'])) {
$uid = $_SESSION['user_index'];
$leavetype = $_POST['leavetype'];
$fromdate = $_POST['fromdate'];
$todate = $_POST['todate'];
$description = $_POST['description'];
# I have no idea how these are used, they seem pointless based
# on your sample script
$status =
$isread = 0;
# Check date
if($fromdate > $todate) {
$error = '"To" date should be greater than the "from" date';
}
# If you have an error on date, it doesn't make sense to keep going
# with the script, so use else
else {
# Fetch user info here
$userInfo = getUserInfo($uid,$conn);
# Check that there is a value here
if(!empty($userInfo['user_index'])) {
# Redirect AND exit
header("Location: ../add_leave.php?err=Leave for {$uid} is not available&ent_id={$uid}");
exit;
}
else {
# Run the function to insert
$added = addUserLeave($uid,$_POST,$conn);
if($added) {
# Redirect AND exit
header("Location: apply_leave.php?message={$leavetype} have been requested");
exit;
}
else
$error = $conn->error;
}
}
}
# Default is to redirect
header("location: add_leave.php?err={$error}");