Php and mysql query issue - 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';
?>

Related

Grading with dropdowns with php and ajax

I am currently making a system for a project. We need to create a grade calculator for the system.
I was stuck because I can only calculate the first set of data in the HTML table.
Grade Table
How can I change the other values? The data that is in the table is generated by PHP and that came from our database. I am just new to PHP, especially to ajax.
Here is the webpage:
?>
<select name="midterm" id="midterm" required class="form-control" onchange="DisableMenu()">
<?php
if($dblMidterm!="0.00"){
?>
<option value=" <?php echo $dblMidterm; ?> " selected> <?php echo $dblMidterm; ?> </option>
<?php
}
else{
?>
<option value="0.00">0.00</option>
<?php
}
?>
<option value="1.00">1.00</option>
<option value="1.25">1.25</option>
<option value="1.50">1.50</option>
<option value="1.75">1.75</option>
<option value="2.00">2.00</option>
<option value="2.25">2.25</option>
<option value="2.50">2.50</option>
<option value="2.75">2.75</option>
<option value="3.00">3.00</option>
<option value="5.00">5.00</option>
</select>
<?php
echo '</td>';
echo '<td>';
?>
<select name="finals" id="finals" required class="form-control">
<option value=" <?php echo $dblFinals; ?> "> <?php echo $dblFinals; ?> </option>
<option value="1.00">1.00</option>
<option value="1.25">1.25</option>
<option value="1.50">1.50</option>
<option value="1.75">1.75</option>
<option value="2.00">2.00</option>
<option value="2.25">2.25</option>
<option value="2.50">2.50</option>
<option value="2.75">2.75</option>
<option value="3.00">3.00</option>
<option value="5.00">5.00</option>
</select>
<?php
echo '</td>';
echo '<td>';
?>
<select name="overall" id="overall" disabled required class="form-control">
<?php
if($dblOverall!="0.00"){
?>
<option value=" <?php echo $dblOverall; ?> "> <?php echo $dblOverall; ?> </option>
<?php
}
else{
?>
<option value=" "></option>
<?php
}
?>
</select>
<?php
Here is the PHP part:
<?php
require_once('server.php');
?>
<?php
if(isset($_POST['dblmidterm'])&&isset($_POST['dblfinals'])){
$dblMidterm = mysqli_real_escape_string($objConn, $_POST['dblmidterm']);
$dblFinals = mysqli_real_escape_string($objConn, $_POST['dblfinals']);
$dblOverall = ($dblMidterm + $dblFinals)/2;
$dblOverall = number_format((float)$dblOverall, 2, '.', '');
echo '<option value="' . $dblOverall . '">' .$dblOverall. '</option>';
$dblMidterm = 0;
$dblFinals = 0;
}
?>
Here is the AJAX part:
$(document).ready(function() {
$("#midterm, #finals").change(function() {
var midterm = $("#midterm").val();
var finals = $("#finals").val();
if(midterm != "" && finals!= "") {
$.ajax({
url:"compute.php",
data:{dblmidterm:midterm,dblfinals:finals},
type:'POST',
success:function(response) {
var resp = $.trim(response);
console.log(midterm);
console.log(finals);
console.log(resp);
$("#overall").html(resp);
}
});
} else {
$("#overall").html("<option value=''> </option>");
}
});
});
The problem is you don't select specific selects, so JavaSript finds the first one.
You need to do some reading on this keyword.
var row = $(this).closest('tr'); //finds the row the select you used is in
var midterm = row.find('#midterm').val(); //finds the #midterm in that row
var finals = row.find('#finals').val(); //finds the #finals that row

html form using PHP_SELF & php validation - after submit, results displayed on new page without displaying form

I am trying to create an html search form using a similar code as posted below.
When I submit the form, I want to submit to PHP_SELF
I want to use php validation code to filter the data.
When I submit the form, I cannot figure out how to get the results to post to a new page without displaying the form.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "xyz_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$showHtml = true;
$month = $day = $year = "";
$monthErr = $dayErr = $yearErr = "";
$errorMessage = "Oops..Please correct the item(s) highlighted in red on the form below and re-submit";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Month error & filter check code....
if (empty($_POST["month"])) {
$month = "";
} else {
$month = test_input($_POST["month"]);
if (!preg_match("/^[a-zA-Z ]*$/",$month)) {
$monthErr = "An invalid entry has been detected. Please reset this form and re-submit.";
}
}
// Day error & filter check code....
if (empty($_POST["day"])) {
$day = "";
} else {
$day = test_input($_POST["day"]);
if (!is_numeric($day)) {
$dayErr = "Day Found - An invalid entry has been detected. Please reset this form and re-submit.";
}
}
// Year error & filter check code....
if (empty($_POST["year"])) {
$year = "";
} else {
$year = test_input($_POST["year"]);
if (!is_numeric($year)) {
$yearErr = "Year Found - An invalid entry has been detected. Please reset this form and re-submit.";
}
}
if (empty($monthErr) and empty($dayErr) and empty($yearErr)) {
$showHtml = false;
$value1 = $_POST['month'];
$value2 = $_POST['day'];
$value3 = $_POST['year'];
$sql = "SELECT * FROM xyz_test_database WHERE month = ('$value1') AND day = ('$value2') AND year = ('$value3')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {echo "<br><br><h2>Search Results</h2>
<table><tr>
<th>ID</th>
<th>Time Stamp</th>
<th>Month</th>
<th>Day</th>
<th>Year</th>
</tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>".$row["id"]."</td>
<td>".$row["time_stamp"]."</td>
<td>".$row["month"]."</td>
<td>".$row["day"]."</td>
<td>".$row["year"]."</td>
</tr>";
}
echo "</table>";
} else {
echo "<p id='no_results'>Sorry - No Results Found :( </p>";
}
}
}
$conn->close();
exit ();
?>
<?php
if ($showHtml)
{
?>
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
</head>
<body>
<form name="form1" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select id="item_select" name="month">
<option value="">Select Month</option>
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
<select id="item_select" name="day">
<option value="">Day</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<select id="item_select" name="year">
<option value="">Year</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="1975">1975</option>
</select>
<br>
<span class="error"><?php echo $monthErr;?></span>
<span class="error"><?php echo $dayErr;?></span>
<span class="error"><?php echo $yearErr;?></span>
<br>
<input type="Submit" id="submit" name="submit" value="Submit Search" style="width: 120px; color: blue;"/>
</form>
</body>
</html>
<?php
}
?>
There are a number of ways to achieve this. You can put an if statement around your html code so that it only displays if certain conditions (e.g. results aren't returned) are met.
One really simple way of doing this is to set a boolean value if results are returned. For example:
<?php
$showHtml = true;
...
if($result->num_rows > 0)
{
$showHtml = false;
...
}
...
$conn->close();
if($showHtml)
{
?>
<!DOCTYPE html>
...
</html>
<?php
}
?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "xyz_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$showHtml = true;
$month = $day = $year = "";
$monthErr = $dayErr = $yearErr = "";
$errorMessage = "Oops..Please correct the item(s) highlighted in red on the form below and re-submit";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Month error & filter check code....
if (empty($_POST["month"])) {
$month = "";
} else {
$month = test_input($_POST["month"]);
if (!preg_match("/^[a-zA-Z ]*$/",$month)) {
$monthErr = "An invalid entry has been detected. Please reset this form and re-submit.";
}
}
// Day error & filter check code....
if (empty($_POST["day"])) {
$day = "";
} else {
$day = test_input($_POST["day"]);
if (!is_numeric($day)) {
$dayErr = "Day Found - An invalid entry has been detected. Please reset this form and re-submit.";
}
}
// Year error & filter check code....
if (empty($_POST["year"])) {
$year = "";
} else {
$year = test_input($_POST["year"]);
if (!is_numeric($year)) {
$yearErr = "Year Found - An invalid entry has been detected. Please reset this form and re-submit.";
}
}
if (empty($monthErr) and empty($dayErr) and empty($yearErr)) {
$showHtml = false;
$value1 = $_POST['month'];
$value2 = $_POST['day'];
$value3 = $_POST['year'];
$sql = "SELECT * FROM xyz_test_database WHERE month = ('$value1') AND day = ('$value2') AND year = ('$value3')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {echo "<br><br><h2>Search Results</h2>
<table><tr>
<th>ID</th>
<th>Time Stamp</th>
<th>Month</th>
<th>Day</th>
<th>Year</th>
</tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>".$row["id"]."</td>
<td>".$row["time_stamp"]."</td>
<td>".$row["month"]."</td>
<td>".$row["day"]."</td>
<td>".$row["year"]."</td>
</tr>";
}
echo "</table>";
} else {
echo "<p id='no_results'>Sorry - No Results Found :( </p>";
}
}
}
$conn->close();
exit ();
?>
<?php
if ($showHtml)
{
?>
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
</head>
<body>
<form name="form1" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select id="item_select" name="month">
<option value="">Select Month</option>
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
<select id="item_select" name="day">
<option value="">Day</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<select id="item_select" name="year">
<option value="">Year</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="1975">1975</option>
</select>
<br>
<span class="error"><?php echo $monthErr;?></span>
<span class="error"><?php echo $dayErr;?></span>
<span class="error"><?php echo $yearErr;?></span>
<br>
<input type="Submit" id="submit" name="submit" value="Submit Search" style="width: 120px; color: blue;"/>
</form>
</body>
</html>
<?php
}
?>

how to put a mysql record in a value in dropdown list?

I have a page called update.php, inside my update .php i have a dropdown list of provinces,what i want to happen is that i want to display the value of province in a dropdown list, and also i can select different province if i want it to update..
here my code for the dropdown list..
<tr>
<td>Province</td>
<td>
<select name="Province" class="form-control" value="<?php echo $province; ?>" id="province" onchange="populate(this.id,'municipality')">
<option id="">Province</option>
<option value="Albay">Albay</option>
<option value="Camarines Norte">Camarines Norte</option>
<option value="Camarines Sur1">Camarines Sur 1</option>
<option value="Camarines Sur2">Camarines Sur 2</option>
<option value="Catanduanes">Catanduanes</option>
<option value="Masbate">Masbate</option>
<option value="Sorsogon">Sorsogon</option>
</select>
</td>
Code for javacript
function populate(s1,s2){
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
var optionArray;
s2.innerHTML = "";
if(s1.value == "Albay"){
optionArray = ["|","bacacay|Bacacay","camalig|Camalig","daraga|Daraga","guinobatan|Guinobatan","jovellar|Jovellar","legazpi|Legazpi","libon|Libon","ligao|Ligao","malilipot|Malilipot","malinao|Malinao","manito|Manito","oas|Oas","pioduran|Pioduran","polangui|Polangui","rapu-rapu|Rapu-Rapu","sto. domingo|Sto. Domingo","tabaco|Tabaco","tiwi|Tiwi"];
}
else if(s1.value == "Camarines Norte"){
optionArray = ["|","basud|Basud","capalonga|Capalonga","daet|Daet","imelda|Imelda","jose panganiban|Jose Panganiban","labo mercedes|Labo Mercedes","paracale|Paracale","san vicente|San Vicente","sta. elena|Sta. Elena","talisay|Talisay","vinzons|Vinzons","capalonga|Capalonga"];
}
else if(s1.value == "Camarines Sur1"){
optionArray = ["|","baao|Baao","balatan|Balatan","bato|Bato","buhi|Buhi","bula|Bula","cabusao|Cabusao","del gallego|Del Gallego","gainza|Gainza","iriga city|Iriga City","libmanan|Libmanan","lupi|Lupi","milaor|Milaor","minalabac|Minalabac","nabua|Nabua","pamplona|Pamplona","pasacao|Pasacao","ragay|Ragay","san fernando|San Fernando","sipocot|Sipocot"];
}
else if(s1.value == "Camarines Sur2"){
optionArray = ["|","bombon|Bombon","calabanga|Calabanga","camaligan|Camaligan","canaman|Canaman","caramoan|Caramoan","garchitorena|Garchitorena","goa|Goa","lagonoy|Lagonoy","magarao|Magarao","naga city|Naga City","ocampo|Ocampo","pili|Pili","presentacion|Presentacion","sagnay|Sagnay","san jose|San Jose","siruma|Siruma","tigaon|Tigaon","tinambac|Tinambac"];
}
else if(s1.value == "Catanduanes"){
optionArray = ["|","bagamanoc|Bagamanoc","baras|Baras","bato|Bato","caramoran|Caramoran","gigmoto|Gigmoto","pandan|Pandan","panganiban|Panganiban","san andres|San Andres","san miguel|San Miguel","viga|Viga","virac|Virac"];
}
else if(s1.value == "Masbate"){
optionArray = ["|","aroroy|Aroroy","baleno|Baleno","balud|Balud","batuan|Batuan","cataingan|Cataingan","cawayan|Cawayan","claveria|Claveria","dimasalang|Dimasalang","esperanza|Esperanza","mandaon|Mandaon","masbate|Masbate","milagros east|Milagros East","milagros west|Milagros West","mobo|Mobo","monreal|Monreal","palanas|Palanas","pio v. corpuz|Pio V. Corpuz","placer|Placer","san fernando|San Fernando","san jacinto|San Jacinto","san pascual|San Pascual","sipalay|Sipalay","uson north|Uson North","uson south|Uson South"];
}
else if(s1.value == "Sorsogon"){
optionArray = ["|","bacon|Bacon","barcelona|Barcelona","bulan|Bulan","casiguran|Casiguran","castilla|Castilla","donsol|Donsol","gubat|Gubat","irosin|Irosin","juban|Juban","magallanes|Magallanes","matnog|Matnog","pilar|Pilar","prieto diaz|Prieto Diaz","sorsogon|Sorsogon","sta. magdalena|Sta. Magdalena"];
}
for(var option in optionArray){
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
}
here's what i've tried
<tr>
<td>Land Type</td>
<?php
include_once 'dbconfig.php';
$sql = "SELECT Province FROM survey_section";
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($stmt->rowCount() > 0)
{
?>
<td><select name="Province" class="form-control">
<option selected="selected" value="">---</option>
<?php
foreach ($results as $row)
{
?>
<option value="<?php echo $row['Province']; ?>"><?php echo $row['Province']; ?></option>
<?php
}
?>
</select>
<?php
}
?>
</td>
</tr>
This will do the work
When using html please note correct amount of " and ' starts and ends
<select name="Province" class="form-control"
value="<?php echo $province; ?>" id="province" onchange="populate(this.id,'municipality')">
<?php
// start your php here
$select_data = mysqli_query($connect,"SELECT id_column,name_column from your_table_name LIMIT 10");
while($row = mysqli_fetch_assoc($select_data)){
?>
<option value="<?php echo $row['id_column'] ?>"><?php echo $row['name_column'] ?></option>
<?php
}
?>
</select>

Checking seat numbers correctly in MySql table

I am developing a script for a table called 'minivan'. Here is the table structure sql fiddle link. Admin provides seats for minivan.
I want to check if seats are available from this search form: search form link The method is GET.
First i want to check the date [this is format of date: 2015-02-16 for example] that a user submits. If the date matches i want to proceed with 'from' and 'to' location that a user chooses. If records are found i want to check what is the total passenger from the dropdown list for different ages that a users provides.
If the total number of passenger does not exceed the seat number for a particular day that a user chooses, i want to echo "seats are available". and proceed with other parts that i am planning to develop later.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_GET['submit'])) {
$date = $_GET['date_up'];
$query = "SELECT date_up FROM minivan WHERE date_up = '$date'";
$result = mysqli_query($conn, $query);
$numrows = mysqli_num_rows($result);
//print_r($numrows);
if ($numrows)
{
$startPlace = $_GET['startpoint'];
$query2 = "SELECT startpoint FROM minivan WHERE startpoint = '$startPlace'";
$result2 = mysqli_query($conn, $query2);
//print_r($result2);
$numrows2 = mysqli_num_rows($result2);
$endPlace = $_GET['endpoint'];
$query3 = "SELECT endpoint FROM minivan WHERE endpoint = '$endPlace'";
$result3 = mysqli_query($conn, $query3);
//print_r($result2);
$numrows3 = mysqli_num_rows($result3);
if ($numrows2 && $numrows3) {
$adult = $_GET['adult'];
$juvenile = $_GET['juvenile'];
$kids = $_GET['kids'];
$child = $_GET['child'];
$totalPassenger = $adult + $juvenile + $kids + $child ;
$seatQuery = "SELECT seat FROM minivan WHERE seat > $totalPassenger";
$result4 = mysqli_query($conn, $seatQuery);
$numrows4 = mysqli_num_rows($result4);//shows error here how to fix it?
if ($numrows4) {
while ($row = mysqli_fetch_row($result4)) {
$seats = $row[0];
echo "$seats are availble for the $date you selected";
}
} else {
echo "no seats are found";
}
}
} else {
"start point and end point does not match";
}
}
$conn->close();
?>
It shows error here $numrows4 = mysqli_num_rows($result4);//shows error here how to fix it?
here is the form i am trying to search with
<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">
Can't really figure out whats wrong with this. I am beginner in php and mysql. Please help me solve this.

php script won't connect MySQL

This is the code. and for some reason I can't find out why it is not working.
As you can see I've added a test query to see if it affects any changes on my db but nope :(
The funny thing is that in another php script I have succeeded to connect the db and even added some records to it thru the php script. Can't find the problem, Thanks from advance.
BTW. as you can see I have already defined the var "month" as string "hey" and echo it in the end of the php script to see if it changes. but nothing is happen!!
<form action="" name="form" id="form">
<label>
Select the month which you want to display its days.
<select name="month" form="form" required>
<option value="january">January</option>
<option value="february">February</option>
<option value="march">March</option>
<option value="april">April</option>
<option value="may">May</option>
<option value="june">June</option>
<option value="july">July</option>
<option value="august">August</option>
<option value="september">September</option>
<option value="october">October</option>
<option value="november">November</option>
<option value="december">December</option>
</select>
</label>
<input type="submit" name="update" value="Display" />
</form>
<?php
$month = "hey";
if(isset($_POST["update"]))
{
$month = $_POST["month"];
$query = "SELECT * FROM `days` WHERE `month`='{$month}';";
$conn = mysqli_connect("localhost","root","","db123");
$result = mysqli_query($conn,$query);
mysqli_query($conn,"INSERT INTO `days`(`month`,`day`) VALUES ('test','10');");
if($result)
{
die("Sorry!");
}
while($row = mysqli_fetch_row($result))
{
echo $month;
print_r($row);
}
mysqli_close($conn);
echo $month;
}
?
You didn't specified the method , its GET by default if.Change this line
if(isset($_POST["update"]))
to this
if(isset($_GET["update"]))
. Or if you want to use method as POST than just specify the method as POST
use the code below
<form action="" name="form" id="form" method="POST">
<label>
Select the month which you want to display its days.
<select name="month" form="form" required>
<option value="january">January</option>
<option value="february">February</option>
<option value="march">March</option>
<option value="april">April</option>
<option value="may">May</option>
<option value="june">June</option>
<option value="july">July</option>
<option value="august">August</option>
<option value="september">September</option>
<option value="october">October</option>
<option value="november">November</option>
<option value="december">December</option>
</select>
</label>
<input type="submit" name="update" value="Display" />
</form>
<?php
$month = "hey";
if(isset($_POST["update"]))
{
$month = $_POST["month"];
$query = "SELECT * FROM `days` WHERE `month`='{$month}';";
$conn = mysqli_connect("localhost","root","","db123");
$result = mysqli_query($conn,$query);
mysqli_query($conn,"INSERT INTO `days`(`month`,`day`) VALUES ('test','10');");
if($result)
{
die("Sorry!");
}
while($row = mysqli_fetch_row($result))
{
echo $month;
print_r($row);
}
mysqli_close($conn);
echo $month;
}
?>
Hope this helps you
<?php
$mysqli = new mysqli("localhost", "root", "", "db123");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$month = "hey";
if(isset($_POST["update"]))
{
$month = $_POST["month"];
$res = $mysqli->query("SELECT * FROM `days` WHERE `month`='{$month}'");
mysqli_query($conn,"INSERT INTO `days`(`month`,`day`) VALUES ('test','10');");
while($row = $res->num_rows)
{
echo $month;
print_r($row);
}
mysqli_close($conn);
echo $month;
}
?>

Categories