I have one text box name is Skills , if admin enter skill name we will get user data based on the user skills in database field . it will working fine . i can display all users data based on the skill set .
My requirement is if admin search any skill that skill is mentioned user in Resume also .i need based on the resume also display data in codeigniter. can you any one please help out this problem. Please find below QUERY in model.
SELECT js_simple.js_id,js_simple.firstname,js_skills_achievements.skill,js_ResumeDetails.fileResume,js_ResumeDetails.profileImage FROM js_simple LEFT JOIN js_skills_achievements ON js_skills_achievements.js_id = js_simple.js_id WHERE js_skills_achievements.skill = '".trim($skill)."'
This is working for me , my requirement is user having resume . with in the resume suppose user mention skills is PHP,JAVA,SQL. if admin search any skill RESUME also i need search . What is QUERY for this in codeigniter model .
view.php
<form id="advance_search" action="" method="post">
<div class="col-md-8" style="border: 2px solid lightgray;padding: 0px 0px 9px 0px;">
<div class="advanced_serach_bg" style="background: #4a90cc;">
<div class="col-md-8">
<h4 style="color:#fff;"> Quick Search </h4>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label style="color:#323232;" for="pincode">Any keyword</label>
<input style="color:#535353; background:#f1f1f1;height: 35px;" id="keywords" class="form-control" name="keywords" type="text">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label style="color:#323232;" for="pincode">Location</label>
<input style="color:#535353; background:#f1f1f1;" id="location" class="form-control" name="location" placeholder="Enter Location" type="text">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label style="color:#323232;" for="activein">Active in:</label>
<select style="background: #4a90cc;color:#fff;margin-top:2px;" name="active_records" id="active_records" class="form-control" >
<option value='3 day'> 3 days</option>
<option value='1 week'> 1 week</option>
<option value='30 day'> 30 days</option>
<option value='2 MONTH'> 2 months</option>
<option value='3 MONTH'> 3 months</option>
<option value='4 MONTH'> 4 months</option>
<option value='5 MONTH'> 5 months</option>
<option value='6 MONTH'> 6 months</option>
<option value='7 MONTH'> 7 months</option>
<option value='8 MONTH'> 8 months</option>
<option value='9 MONTH'>9 months</option>
<option value='10 MONTH'> 10 months</option>
<option value='11 MONTH'> 11 months</option>
<option value='12 MONTH'> 12 months</option>
<option value='10 Year'> 1 + Year</option>
</select>
</div>
</div>
<div class="clearfix"></div>
<br>
<div class="form-group">
<div class="col-md-offset-5 col-sm-4">
<input type="submit" value="Search" class="btn btn-normal subbtn">
</div>
</div>
</div>
</form>
javascript
<script>
$(function(){
$('form#advance_search').submit(function(e) {
e.preventDefault();
var formData = $('form#advance_search').serializeArray();
//var keywords = $('#keywords').tagEditor('getTags')[0].tags;
//console.log(keywords);
$.ajax({
url:"<?php echo base_url();?>newrecruiter_control/candidate_advance_search",
type:"post",
data:formData,
success:function(data) {
window.location.href="<?php echo base_url();?>newrecruiter_control/search_candidate";
}
});
});
});</script>
newrecruiter_control.php
public function candidate_advance_search() {
$this->recruiter_model->delete_candidate_search();
$data['job_seeker'] = $this->recruiter_model->advance_candidate_search();
}
recruiter_model.php
<?php
public function advance_candidate_search() {
$data = array(
'active_records' => $this->input->post('active_records')?$this->input->post('active_records'):'3 day',
'search_keyword' => $this->input->post('keywords')?$this->input->post('keywords'):'',
'semantic_search' => $this->input->post('search_mode')?$this->input->post('search_mode'):'ON',
'search_in_resume' => 'NO' //$this->input->post('search_resume')
);
$sql_query = $this->db->select('*')
->from('recruiter_recent_search_results')
->where('recruiter_id',$this->session->userdata('recruiter_id'))
->get();
if($sql_query->num_rows() >= 5 ){
$this->db->delete('recruiter_recent_search_results',array('recruiter_id' => $this->session->userdata('recruiter_id')));
}else{
$exp = $data['min_experience'];
$this->db->insert('recruiter_recent_search_results',array('recruiter_id' => $this->session->userdata('recruiter_id'),'skills' => strtoupper($data['search_keyword']), 'location' => ucfirst($data['location']),'experience' => $exp));
}
if($data['search_in_resume'] == 'YES') {
/*
if($data['semantic_search'] == 'OFF') {
$response_array = $this->getAdvanceSearchResultInResume($data);
}else{
$response_array = $this->getAllSearchResultInResume($data);
}*/
}else{
if($data['semantic_search'] == 'OFF') {
$response_array = $this->getAdvanceSearchResult($data);
}else{
$response_array = $this->getAllSearchResult($data);
}
}
}
public function getAllSearchResult($data) {
$search_query = "SELECT js_simple.js_id,js_simple.firstname,js_simple.lastname,js_simple.added_date,js_skills_achievements.skill1,js_ResumeDetails.percentage,js_ResumeDetails.fileResume,js_ResumeDetails.profileImage,js_ResumeDetails.profile_type,js_ResumeDetails.about_self FROM js_simple LEFT JOIN js_skills_achievements ON js_skills_achievements.js_id = js_simple.js_id LEFT JOIN js_ResumeDetails ON js_ResumeDetails.js_id = js_simple.js_id WHERE js_simple.added_date >= DATE_SUB(NOW(),INTERVAL ".$data['active_records']." ) ";
if($data['search_keyword'] != NULL) {
$search_key = explode(',',$data['search_keyword']);
if(count($search_key) == 1) {
$search_query .= " AND (js_skills_achievements.skill1 = '".trim($search_key[0])."' OR js_ResumeDetails.about_self LIKE '%".trim($search_key[0])."%')";
$str = $this->db->last_query($search_query);
echo $str;
}
}
$search_query .= " GROUP BY js_simple.js_id ORDER BY js_simple.added_date DESC LIMIT ".$data['sort_by'];
$response = $this->db->query($search_query);
// return $this->db->last_query();
return $response->result_array();
}
public function getAdvanceSearchResult($data) {
$this->db->select('*');
$this->db->from('js_simple,js_skills_achievements,js_ResumeDetails');
$this->db->join('js_skills_achievements','js_skills_achievements.js_id = js_simple.js_id','left');
$this->db->join('js_ResumeDetails','js_ResumeDetails.js_id = js_simple.js_id','left');
$this->db->where("js_simple.added_date >= DATE_SUB(NOW(),INTERVAL ".$data['active_records']." )",NULL,FALSE);
if($data['search_keyword'] != NULL) {
$search_key = explode(',',$data['search_keyword']);
if(count($search_key) == 1) {
$this->db->where('js_skills_achievements.skill1',$search_key[0]);
}
}
$this->db->group_by('js_simple.js_id');
$this->db->order_by('js_simple.added_date','desc');
if($data['sort_by'] != NULL) {
$this->db->limit($data['sort_by']);
}
$search_response = $this->db->get();
return $search_response->result_array();
}
public function getAllSearchResultInResume($data) {
$jobseekers = '';
$get_js_details = $this->getAllSearchResult($data);
foreach($get_js_details as $key => $jobseeker) {
if($jobseekers == NULL) {
$jobseekers .= $jobseeker['js_id'];
}else{
$jobseekers .= ','.$jobseeker['js_id'];
}
}
}
?>
Related
I don't know how to add a double record to db.
I have form with double same row content.
I would like to add a dynamic line in the next step using js but at this point I used double html to validate it.
<form class="formAddCoupon" action="/?dashboard=coupon" method="post">
<div class="windowEvents">
<div class="row">
<input type="text" class="teamInput" name="team1">
<input type="text" class="teamInput" name="team2">
<select name="score" id="selectOptions">
<option value="Liczba bramek">Liczba bramek</option>
<option value="Liczba rzutów rożnych">
Liczba rzutów rożnych</option>
<option value="Ilość kartek">Liczba kartek</option>
<option value="Wygrana drużyny">Wygrana drużyny</option>
<option value="Wygrana drużyny lub połowy">
Wygrana drużyny lub połowy</option>
<option value="Wygrana połowy">Wygrana jednej z połów</option>
<option value="Hendicap">Hendicap</option>
<option value="Ilość punktów">Liczba punktów</option>
</select>
<input type="text" class="scoreInput" name="type_score">
</div>
<div class="row">
<input type="text" class="teamInput" name="team1">
<input type="text" class="teamInput" name="team2">
<select name="score" id="selectOptions">
<option value="Liczba bramek">Liczba bramek</option>
<option value="Liczba rzutów rożnych">
Liczba rzutów rożnych</option>
<option value="Ilość kartek">Liczba kartek</option>
<option value="Wygrana drużyny">Wygrana drużyny</option>
<option value="Wygrana drużyny lub połowy">
Wygrana drużyny lub połowy</option>
<option value="Wygrana połowy">Wygrana jednej z połów</option>
<option value="Hendicap">Hendicap</option>
<option value="Ilość punktów">Liczba punktów</option>
</select>
<input type="text" class="scoreInput" name="type_score">
</div>
</div>
<div class="valueAmountRow">
<input
type="number"
name="bid_amount"
id="bid_amount"
placeholder="Stawka"
min="0"
step="any"
>
<input
type="number"
name="winner_amount"
id="winner_amount"
placeholder="Wygrana"
min="0"
step="any"
>
<input type="submit" value="Dodaj">
</div>
</form>
Controller.php:
$data = $this->getRequestPost();
If(!empty($data)) {
$couponData = [
'bid_amount' => $data['bid_amount'],
'winner_amount' => $data['winner_amount'],
'team1' => $data['team1'],
'team2' => $data['team2'],
'score' => $data['score'],
'type_score' => $data['type_score'],
];
$this->db->createCoupon($couponData);
}
Database.php
public function createCoupon(array $data)
{
try {
$this->createNewCoupon($data);
} catch(Throwable $e) {
dump($e);
throw new StorageException('Nie udało się wysłać kuponu', 400, $e);
}
}
private function createNewCoupon($data): void
{
$nr_coupon = trim($this->connection->quote($this->checkIssetCode()));
$created = $this->connection->quote(date('Y-m-d H:i:s'));
$bid_amount = trim($this->connection->quote($data['bid_amount']));
$winner_amount = trim($this->connection->quote($data['winner_amount']));
$team1 = trim($this->connection->quote($data['team1']));
$team2 = trim($this->connection->quote($data['team2']));
$score = trim($this->connection->quote($data['score']));
$typeScore = trim($this->connection->quote($data['type_score']));
$insertNumberCoupon = "INSERT INTO
coupon_number(
nr_coupon,
created,
bid_amount,
winner_amount
)
VALUES(
$nr_coupon,
$created,
$bid_amount,
$winner_amount
)";
$sql_create_number_coupon = $this->connection->prepare($insertNumberCoupon);
if($sql_create_number_coupon)
{
$sql_create_number_coupon->execute();
$id = (int) $this->connection->lastInsertId();
$addEvent = "INSERT INTO
events_at_coupon(
number_id_coupon,
team1,
team2,
score,
type_score
)
VALUES($id,$team1,$team2,$score,$typeScore)";
$sql_add_event_to_table = $this->connection->prepare($addEvent);
if($sql_add_event_to_table)
{
$sql_add_event_to_table->execute();
}
}
}
When i send a form only one record is added to database.
I know why, but what do i have to do to get a double record ?
I have this if statement
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$(document).on('submit', '#rentform', function () {
var data = $(this).serialize()
$.ajax({
type: 'POST',
url: 'newrent.php',
data: data,
success:(
function (data){$(".result").html(data)}
)
});
return false;
});
} )
$(document).ready(function () {
$('#rent').change(function(){
var x =($('#rent option:selected').data('sireal'))
$('#itemsn').val(x);
});
} )
</script>
<form method="post" id="rentform" action="" novalidate="novalidate">
<label for="item">REnter Name</label>
<select name="rnt_name" id="name_rent">
<option selected disabled>SELECT Renter Name</option>
<?php foreach ($nameq as $res) : ?>
<option value="<?= $res['user_name']?>"><?= $res['user_name'] ?></option>
<?php endforeach; ?>
</select>
<br/>
<br/>
<label for="item">Cameras</label>
<select name="item" id="rent">
<option selected disabled>SELECT ITEM</option>
<?php foreach ($rentq as $row) : ?>
<option value="<?= $row['item_brand']?>" data-sireal="<?= $row['s_n'] ?>"><?= $row['item_brand'] ?></option>
<?php endforeach; ?>
</select><br/>
<br/>
<input type="hidden" name="sn" id="itemsn" value="">
<label name="from_date">RENT FROM</label>
<input type="date" name="from_date"><br/>
<label name="from_hour">RENT FROM Hour</label>
<input type="time" name="from_hour"><br/>
<label name="to_date">RENT TO</label>
<input type="date" name="to_date"><br/>
<label name="to_hour">RENT FROM Hour</label>
<input type="time" name="to_hour"><br/>
<input type="submit" name="submit" value="Send Rent">
</form>
<div class="result">
</div>
if($_POST){
$name = $_POST['rnt_name'];
$item = $_POST['item'];
$fdate = $_POST['from_date'];
$fhour = $_POST['from_hour'];
$tdate = $_POST['to_date'];
$thour = $_POST['to_hour'];
$sn = $_POST['sn'];
$csheck = "SELECT * FROM rent";
$ckq = mysqli_query($link,$csheck);
foreach ($ckq as $res) {}
$count = "SELECT item_brand = '$item',s_n = '$sn',COUNT(*)
FROM item
WHERE status = 1 AND item_brand = '$item' AND s_n = '$sn'";
$cnt = mysqli_query($link,$count);
foreach ($cnt as $itm);
$itmq = "SELECT rent_item = '$item',COUNT(*)
FROM rent ";
$itemres = mysqli_query($link,$itmq);
foreach ($itemres as $missitm){};
if(($fdate >= $res['rent_from_d'] && $res['rent_to_d'] >= $tdate && $missitm['COUNT(*)'] >= $itm['COUNT(*)'] ) || ($fdate > $res['rent_from_d'] && $res['rent_to_d'] > $tdate && $fdate > $res['rent_from_d'] || $fdate <= $res['rent_to_d'] && $fhour <= $res['rent_to_t'] && $missitm['COUNT(*)'] >= $itm['COUNT(*)'] ) ) {
echo 'no good Item Rented To '.$res['renter'] ;
}else{
$newrent = "INSERT INTO rent (renter,rent_item,rent_from_d,rent_from_t,rent_to_d,rent_to_t)
VALUES ('$name','$item','$fdate','$fhour','$tdate','$thour')";
mysqli_query($link,$newrent);
echo 'pass';
}
this is what I get in my database after form submit
rent_id renter rent_item sn rent_from_d rent_from_t rent_to_d rent_to_t
115 dror x70 1234 2018-11-29 10:00 2018-11-29 14:00
What I am trying to do is create a rent system. My problem is how to validate if items are selected between two dates and time. Every time new rent is created, the status of the specific item that has been chosen set to 0, so that the system will no longer available.
Thanks in advance.
I'm learning PHP (and having great fun) but I've run up against a problem in a CRUD application that I can't seem to find a way around.
I need to use a dropdown for data entry on the create page. I also want to have the same dropdown on the update page, but of course this would need to set the value to the one already stored in the record when the update form loads. I have hand-coded some of the shorter dropdowns (see below) but the one I need to do next is 2008 records!! (it will be searched as input is typed).
I have looked at multiple posts about arrays etc and I can get the dropdown to list the values that way but can't figure out how to pull in the existing value.
The relevant code is as follows (please be gentle about the coding...I'm new!!):
<?php
require_once "../includes/header.php";
?>
<?php
if ( isset($_POST['patient_id']) && isset($_POST['datadate'])
&& isset($_POST['bedspace']) && isset($_POST['episode_id']) ) {
$sql = "UPDATE tbl_users SET patient_id = :patient_id,
datadate = :datadate, bedspace = :bedspace, isadmitday = :isadmitday, antimicrobial = :antimicrobial
WHERE episode_id = :episode_id";
$stmt = $PDO->prepare($sql);
$stmt->execute(array(
':patient_id' => $_POST['patient_id'],
':datadate' => $_POST['datadate'],
':bedspace' => $_POST['bedspace'],
':episode_id' => $_POST['episode_id'],
':isadmitday' => $_POST['isadmitday'],
':antimicrobial' => $_POST['antimicrobial']));
$_SESSION['success'] = '<div class="alert alert-success" role="alert"><strong>Record successfully updated</strong></div>';
header( 'Location: index.php' ) ;
return;
}
$stmt = $PDO->prepare("SELECT * FROM tbl_users where episode_id = :xyz");
$stmt->execute(array(":xyz" => $_GET['episode_id']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ( $row === false ) {
$_SESSION['error'] = '<div class="alert alert-danger" role="alert"> <strong>Unable to proceed - bad episode_id value</strong></div';
header( 'episode_id: index.php' ) ;
return;
}
$n = htmlentities($row['patient_id']);
$e = htmlentities($row['datadate']);
$l = htmlentities($row['bedspace']);
$i = htmlentities($row['isadmitday']);
$am = htmlentities($row['antimicrobial']);
$episode_id = htmlentities($row['episode_id']);
?>
<div class="container">
<div class="row">
<div class="row">
<div class="col-md-12">
<h2>Edit episode record</h2><br>
</div> <!-- /col-md-12 -->
</div> <!-- /row -->
</div> <!-- /row -->
<div class="row">
<form name="edit_record" id="edit_record" method="POST" action="">
<div class="form-group">
<label for="patient_id" control-label>Patient ID</label>
<input type="text" class="form-control" id="patient_id" name="patient_id" value="<?= $n ?>">
</div> <!-- /form-group -->
<div class="form-group">
<label for="datadate" control-label>Date</label>
<input type="text" class="form-control" id="datadate" name="datadate" value="<?= $e ?>">
</div> <!-- /form-group -->
<div class="form-group">
<label for="bedspace" control-label>Bedspace</label>
<select class="form-control" required="required" id="bedspace" name="bedspace" value="<?= $l ?>">
<option></option>
<option value="Side Ward 1" <?php echo $l == 'Side Ward 1'?'selected':'';?>>Side Ward 1</option>
<option value="Bed 1" <?php echo $l == 'Bed 1'?'selected':'';?>>Bed 1</option>
<option value="Bed 2" <?php echo $l == 'Bed 2'?'selected':'';?>>Bed 2</option>
<option value="Bed 3" <?php echo $l == 'Bed 3'?'selected':'';?>>Bed 3</option>
<option value="Bed 4" <?php echo $l == 'Bed 4'?'selected':'';?>>Bed 4</option>
<option value="Bed 5" <?php echo $l == 'Bed 5'?'selected':'';?>>Bed 5</option>
<option value="Side Ward 2" <?php echo $l == 'Side Ward 2'?'selected':'';?>>Side Ward 2</option>
<option value="Side Ward 3" <?php echo $l == 'Side Ward 3'?'selected':'';?>>Side Ward 3</option>
</select>
</div> <!-- /form-group -->
Ok after an intensive couple of days research I have things working like I want to, although I am sure my work-around isn't pretty! The dropdown is a list of antibiotc medicines called 'antimicrobials'. I have the dropdown list from the database using a SELECT statement and I am matching the value pulled from the other table to set the value of the dropdown when a record is edited.
The code below is from the edit.php file:
<?php
if (isset($_POST['episode_id']) ) {
$sql = "UPDATE tbl_users SET antimicrobial = :antimicrobial
WHERE episode_id = :episode_id";
$stmt=$PDO->prepare($sql);
$stmt->execute(array(
':antimicrobial' => $_POST['antimicrobial']));
$_SESSION['success'] = '<div class="alert alert-success" role="alert"><strong>Record successfully updated</strong></div>';
header( 'Location: index.php' ) ;
return;
}
$stmt = $PDO->prepare("SELECT * FROM tbl_users where episode_id = :xyz");
$stmt->execute(array(":xyz" => $_GET['episode_id']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ( $row === false ) {
$_SESSION['error'] = '<div class="alert alert-danger" role="alert"><strong>Unable to proceed - bad episode_id value</strong></div';
header( 'episode_id: index.php' ) ;
return;
}
$am = htmlentities($row['antimicrobial']);
$episode_id = htmlentities($row['episode_id']);
?>
<div class="form-group">
<label for="antimicrobial" control-label>Antimicrobial from database</label>
<?php
$sql_am = 'SELECT antimicrobial FROM tbl_antimicrobials';
$stmt_am = $PDO->query($sql_am);
?>
<select class="form-control" id="antimicrobial"></select>
<?php
while ($row = $stmt_am->fetch(PDO::FETCH_ASSOC))
{
$selected = ($row['antimicrobial'] == $am ) ? ' selected' : '';
echo "<option value='" . $row['antimicrobial'] . "'" . $selected . ">" . $row['antimicrobial'] . "</option>";
}
echo '</select>';
?>
</div> <!-- /form-group -->
I have a modal form with two select boxes with the same current_models class.
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Model</label>
<select class='form-control' id='left_model_id' name='left_model_id'>
<div id="left_model" class="current_models"></div>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Model</label>
<select class='form-control' id='right_model_id' name='right_model_id'>
<div id="right_model" class="current_models"></div>
</select>
</div>
</div>
</div>
Each select needs to have it's own id, but they are loading the same select options into groups like this:
$('.current_models').load('ajax_get_models_man_group.php');
Here's my ajax_get_models_man_group.php page:
<?php
require_once 'core/init.php';
$user = new User();
if(!$user->isLoggedIn()) {
Redirect::to('login.php');
}
$models = DB::getInstance()->query("SELECT man.id AS man_id, man.man AS man, models.name AS model, models.id AS model_id FROM hearing_aid_models models LEFT JOIN hearing_aid_man man ON man.id = models.man_id WHERE models.currently_fitting = 'Y' AND company_id = '" . $user->data()->company_id . "' ORDER BY man ASC");
if ($models->error()) {
echo 'Error occurred.';
} else {
$currentGroup = null;
foreach( $models->results() as $result ) {
// start a new optgroup
if( $currentGroup == null || $result->man_id != $currentGroup ) {
// end the previous group
if( $currentGroup != null ) {
echo "</optgroup\n>";
}
// start a new group
echo "<optgroup data-id='{$result->man_id}' label='{$result->man}'>\n";
$currentGroup = $result->man_id;
}
echo "<option value='{$result->model_id}'>{$result->model}</option>\n";
}
// end the last opt group
if( $currentGroup != null ) echo "</optgroup>\n";
}
?>
The problem is that the values do not load into the select divs!
Here's my ajax source code results:
<optgroup data-id='1' label='Audibel'>
<option value='95'>Start 7 Wireless</option>
<option value='96'>Start 7</option>
<option value='99'>A3i Platinum</option>
</optgroup>
<optgroup data-id='16' label='Phonak'>
<option value='98'>Naida Q70</option>
</optgroup>
<optgroup data-id='2' label='Starkey'>
<option value='100'>S Series i30</option>
<option value='81'>3 Series I 70</option>
<option value='82'>3 Series I 90</option>
</optgroup>
1) Get rid of divs inside select tags
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Model</label>
<select class='form-control current_models' id='left_model_id' name='left_model_id'>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Model</label>
<select class='form-control current_models' id='right_model_id' name='right_model_id'>
</select>
</div>
</div>
</div>
2) load ajax inside the right div
$('.current_models').load('ajax_get_models_man_group.php');
I have a simple table like this: table. A form submits data to check in this table.
<form action="" method="GET">
From
<select name="startpoint" id="from">
<option >Hat Yai Airport</option>
<option >Pak Bara</option>
<option >Kohlipe</option>
</select>
To
<select name="endpoint" id="to">
<option >Pak Bara</option>
<option >Hat Yai Airport</option>
<option >Kohlipe</option>
</select>
<label for="Date">Date</label>
<input type="text" name="date_up" id="datepicker">
<h4 style="margin-top: 30px;">Passengers</h4>
Adults
<select name="adult" id="from">
<option >1</option>
<option >2</option>
<option >3</option>
<option >4</option>
<option >5</option>
</select>
< 12 years
<select name="juvenile" id="to">
<option >0</option>
<option >1</option>
<option >2</option>
<option >3</option>
<option >4</option>
</select>
< 7 years
<select name="kids" id="from">
<option >0</option>
<option >1</option>
<option >2</option>
<option >3</option>
</select>
< 3 years
<select name="child" id="to">
<option >0</option>
<option >1</option>
<option >2</option>
<option >3</option>
</select>
<input type="submit" value="Search" class="submit" name="submit">
And this is the initial i have made to check this table.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "hello";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_GET['submit'])) {
$date = $_GET['date_up'];
$startPlace = $_GET['startpoint'];
$endPlace = $_GET['endpoint'];
$adult = $_GET['adult'];
$juvenile = $_GET['juvenile'];
$kids = $_GET['kids'];
$child = $_GET['child'];
$totalPassenger = $adult + $juvenile + $kids + $child;
$query = "SELECT * FROM taxi WHERE date_up = '$date'";
$result = mysqli_query($conn, $query);
if (!$result) {
echo "Could not successfully run query from DB: " . mysqli_error();
exit;
}
if (mysqli_num_rows($result) == 0) {
$nodate = "No date matches for speedboat";
echo $nodate;
} else {
while ($row = mysqli_fetch_assoc($result)) {
$start = $row["startpoint"];
$end = $row["endpoint"];
$standards= $row["standards"];
$deluxe= $row["deluxe"];
//print_r($deluxe);
}
if (($start === $startPlace && $end === $endPlace) && (what can be the right query?????)) {
$success = "seats are found in taxi. total seat: user choses seat for $totalPassenger people";
echo $success;
}
}
}
We have total 10 taxi(standard 5 , deluxe 5). A taxi is for four people. I want to check if the total passenger is more than 4 people but less than 8 people and if this is true i want to check the standard or deluxe columns whether they both have at least two taxi(int 2) and return something. If the total passenger is more than 8 but less than 12 i need to check both columns if they have at least 3 taxi and this will go on until i reach 20 people. Because if the total passenger is more than 16 but less than 20 we need 5 taxi and this is our limit. If user provides more passenger after 20 we can return "not enough taxi for your query". How can i check this pattern.
I also need to return at least one column result. For example user searches with 7 passenger and i check and find that in deluxe column i have 2 taxi but in the standard column i have 1 taxi, so i need to return the deluxe column match result to the user(or to make the query more challenging we can return one standard taxi and one deluxe taxi right?). How can i implement this scenario. Please help me.
This code use ajax to fetch data without refreshing the page. and i have used PDO you can change it to mysqli
<?php
$db = new PDO('mysql:host=localhost; dbname=data','root','');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$results = $db->query('SELECT * FROM taxi');
//this is a function for creating a table
function availableTaxis($results){ ?>
<table>
<tr>
<th>ID</th>
<th>from</th>
<th>to</th>
<th>Available On</th>
<th>standard</th>
<th>deluxe</th>
</tr>
<?php foreach ($results as $value) : ?>
<tr>
<td><?php echo $value['taxi_id']; ?></td>
<td><?php echo $value['startpoint']; ?></td>
<td><?php echo $value['endpoint']; ?></td>
<td><?php echo $value['date_up']; ?></td>
<td><?php echo $value['standards'] .' ('.($value['standards'] * 4).' Passengers)'; ?></td>
<td><?php echo $value['deluxe'].' ('.($value['deluxe'] * 4).' Passengers)'; ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php } ?> <!-- end of a function -->
<!-- this is another function for getting taxi routes -->
<?php function routes(){ ?>
<br>
<form>
From
<select name="startpoint" onchange="available(this.value,to.value)" id="from">
<option value="Hat Yai Airport">Hat Yai Airport</option>
<option >Pak Bara</option>
<option >Kohlipe</option>
</select>
To
<select name="endpoint" onchange="available(from.value,this.value)" id="to">
<option >Pak Bara</option>
<option >Hat Yai Airport</option>
<option >Kohlipe</option>
</select>
<p id="availabe_date"></p>
<div id="disable">
<label for="Date">Date</label>
<input type="date" name="date_up" value="<?php echo date('Y-m-d'); ?>" id="datepicker" onchange="available(from.value,to.value)">
<h4 style="margin-top: 30px;">Passengers</h4>
Adults
<select name="adult" id="adult">
<option >1</option>
<option >2</option>
<option >3</option>
<option >4</option>
<option >5</option>
</select>
12 years
<select name="juvenile" id="juvenile">
<option >0</option>
<option >1</option>
<option >2</option>
<option >3</option>
<option >4</option>
</select>
7 years
<select name="kids" id="kids">
<option >0</option>
<option >1</option>
<option >2</option>
<option >3</option>
</select>
3 years
<select name="child" id="child">
<option >0</option>
<option >1</option>
<option >2</option>
<option >3</option>
</select>
<br>
<p id="error" style="color:red"></p>
<br>
<input type="button" value="Search" onclick="results(datepicker.value,startpoint.value,endpoint.value,adult.value,juvenile.value,kids.value,child.value)" id="submit" name="submit">
</div>
</form>
<?php } ?><!-- end of a function -->
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
table,th,td{
border: 1px solid #000;
}
th{
width: 120px;
background-color: #000;
color: #fff;
text-transform: capitalize;
}
table {
border-collapse: collapse;
}
</style>
<script type="text/javascript">
//creating ajax
function available(from,to){
var query = "from="+from+"&"+"to="+to;
var data = new XMLHttpRequest();
data.open("POST","answer.php");
data.onreadystatechange = function(){
if(data.readyState === 4 && data.status === 200){
document.getElementById('availabe_date').innerHTML = data.responseText;
if(data.responseText.indexOf('is not avalaible') > -1){
document.getElementById('disable').style.display = 'none';
}else{
document.getElementById('disable').style.display = 'inline';
if(data.responseText.indexOf(datepicker.value) == -1){
document.getElementById('error').style.display = 'inline';
document.getElementById('error').innerHTML = 'There\'s no taxi on : '+datepicker.value +', from <span style="font-style:italic;text-decoration:underline">'+from+'</span> to <span style="font-style:italic;text-decoration:underline">'+to+'</span>';
document.getElementById('submit').style.display = 'none';
document.getElementById('res').style.display = 'none';
}else{
document.getElementById('error').style.display = 'none';
document.getElementById('submit').style.display = 'inline';
document.getElementById('res').style.display = 'inline';
//document.getElementById('error').innerHTML = 'There\'s no taxi on : '+datepicker.value;
}
}
}
}
data.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
data.send(query);
}
function results(date_up,startpoint,endpoint,adult,juvenile,kids,child){
var query = 'date_up='+date_up+'&'+'startpoint='+startpoint+'&'+'endpoint='+endpoint+'&'+'adult='+adult+'&'+'juvenile='+juvenile+'&'+'kids='+kids+'&'+'child='+child;
var data = new XMLHttpRequest();
data.open("POST","results.php");
data.onreadystatechange = function(){
if(data.readyState === 4 && data.status === 200){
document.getElementById('res').innerHTML = data.responseText;
}
}
data.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
data.send(query);
}
</script>
</head>
<body>
<?php availableTaxis($results);
routes();
?>
<div id="res">
</div>
</body>
</html>
answer.php file
<?php
$from = $_POST['from'];
$to = $_POST['to'];
$db = new PDO('mysql:host=localhost; dbname=data','root','');
$results = $db->prepare('SELECT * FROM `taxi` WHERE `startpoint` = ? AND `endpoint` = ?');
$results->execute(array($from,$to));
$rows = $results->fetchAll(PDO::FETCH_ASSOC);
$avalaible = "Avalaible on: <br>";
for ($i=0; $i < count($rows) ; $i++) {
$avalaible = $avalaible. $rows[$i]['date_up'].'<br>';
}
if(count($rows) > 0){
echo "$avalaible ";
}else{
echo "Taxi from <span style='font-style:italic;text-decoration:underline'>$from</span> to <span style='font-style:italic;text-decoration:underline'>$to</span> is not avalaible";
}
?>
results.php
<?php
$db = new PDO('mysql:host=localhost; dbname=data','root','');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$date = $_POST['date_up'];
$startPlace = $_POST['startpoint'];
$endPlace = $_POST['endpoint'];
$adult = $_POST['adult'];
$juvenile = $_POST['juvenile'];
$kids = $_POST['kids'];
$child = $_POST['child'];
$totalPassenger = $adult + $juvenile + $kids + $child;
$taxis = ceil($totalPassenger/4);
$results = $db->prepare('SELECT * FROM taxi where (startpoint = ? AND endpoint = ?) AND (date_up = ?) AND (standards >= ? OR deluxe >= ?)');
try {
$results->execute(array($startPlace,$endPlace,$date,$taxis,$taxis));
} catch (PDOException $e) {
echo $e->getMessage();
}
$rows = $results->fetchAll(PDO::FETCH_ASSOC);
$seats = ($rows[0]['standards']+$rows[0]['deluxe']) * 4;
$taxis = $rows[0]['standards']+$rows[0]['deluxe'];
echo 'Found '.$seats." seats, in $taxis taxis:<br>".($rows[0]['standards']*4).' Standards seats.<br>'.($rows[0]['deluxe']*4).' Deluxe seats.<br>For '.$totalPassenger.' passengers';
?>