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
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
}
?>
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>
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.
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;
}
?>