Update value based on checkbox selected - php

I am trying to update the value in a text box based on selections made on the form. When a user checks a box for an option, I am trying to get the total cost to increase by a defined amount. Everything else is working on the form and if I change the cost value manually it will post to database correctly. Is this possible with my approach or do I need to resort to a different technique?
<HEAD>
<script>
function tally()
{
Cost = 60;
if (Document.edituser.survivor10.checked ) { Cost = Cost + 10; }
if (document.edituser.high5.checked ) { Cost = Cost + 10; }
if (document.edituser.margin.checked == true ) { Cost = Cost + 10; }
if (document.edituser.survivor20.checked == true ) { Cost = Cost + 20; }
if (document.edituser.confidence.checked == true ) { Cost = Cost + 10; }
if (document.edituser.loser.checked == true ) { Cost = Cost + 10; }
if (document.edituser.vegas.checked == true ) { Cost = Cost + 10; }
document.edituser.cost.value = Cost;
}
<?php
require('includes/application_top.php');
include('includes/classes/class.formvalidation.php');
if (isset($_POST['submit'])) {
$my_form = new validator;
if($my_form->checkEmail($_POST['email'])) { // check for good mail
if ($my_form->validate_fields('firstname,lastname,email,password')) { //
comma delimited list of the required form fields
if ($_POST['password'] == $_POST['password2']) {
$salt = substr($crypto->encrypt((uniqid(mt_rand(), true))), 0, 10);
$secure_password = $crypto->encrypt($salt . $crypto->encrypt($_POST['password']));
$sql = "update nflp_users ";
$sql .= "set password = '".$secure_password."', salt = '".$salt."', firstname = '".$_POST['firstname']."', lastname = '".$_POST['lastname']."', textOption = '".$_POST['textOption']."', phone = '".$_POST['phone']."', carrier = '".$_POST['carrier']."', email = '".$_POST['email']."', survivor10 = '".$_POST['survivor10']."', survivor20 = '".$_POST['survivor20']."', loser = '".$_POST['loser']."', margin = '".$_POST['margin']."', high5 = '".$_POST['high5']."', vegas = '".$_POST['vegas']."', confidence = '".$_POST['confidence']."', cost = '".$_POST['cost']."'";
$sql .= "where userID = " . $user->userID . ";";
//die($sql);
$mysqli->query($sql) or die($mysqli->error);
//set confirmation message
$display = '<div class="responseOk">Account updated successfully.</div><br/>';
} else {
$display = '<div class="responseError">Passwords do not match, please try again.</div><br/>';
}
} else {
$display = str_replace($_SESSION['email_field_name'], 'Email', $my_form->error);
$display = '<div class="responseError">' . $display . '</div><br/>';
}
} else {
$display = '<div class="responseError">There seems to be a problem with your email address, please check.</div><br/>';
}
}
include('includes/header.php');
$sql = "select * from " . DB_PREFIX . "users where userID = " . $user->userID;
$query = $mysqli->query($sql);
if ($query->num_rows > 0) {
$row = $query->fetch_assoc();
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$email = $row['email'];
$survivor10 = $row['survivor10'];
$survivor20 = $row['survivor20'];
$loser = $row['loser'];
$margin = $row['margin'];
$high5 = $row['high5'];
$confidence = $row['confidence'];
$vegas = $row['vegas'];
// $textOption = $row['textOption'];
// $phone = $row['phone'];
// $carrier = $row['carrier'];
$cost = $row['cost'];
}
if (!empty($_POST['firstname'])) $firstname = $_POST['firstname'];
if (!empty($_POST['lastname'])) $lastname = $_POST['lastname'];
if (!empty($_POST['email'])) $email = $_POST['email'];
if (!empty($_POST['survivor10'])) $survivor10 = $_POST['survivor10'];
if (!empty($_POST['survivor20'])) $survivor20 = $_POST['survivor20'];
if (!empty($_POST['loser'])) $loser = $_POST['loser'];
if (!empty($_POST['margin'])) $margin = $_POST['margin'];
if (!empty($_POST['high5'])) $high5 = $_POST['high5'];
if (!empty($_POST['confidence'])) $confidence = $_POST['confidence'];
if (!empty($_POST['vegas'])) $vegas = $_POST['vegas'];
// if (!empty($_POST['textOption'])) $textOption = $_POST['textOption'];
// if (!empty($_POST['phone'])) $phone = $_POST['phone'];
// if (!empty($_POST['carrier'])) $carrier = $_POST['carrier'];
if (!empty($_POST['cost'])) $cost = $_POST['cost'];
?>
<h1>Edit User Account Details</h1>
<?php if(isset($display)) echo $display; ?>
<form action="user_edit.php" method="post" name="edituser">
<fieldset>
<legend style="font-weight:bold;">Enter User Details:</legend>
<p>First Name:<br />
<input type="text" name="firstname" value="<?php echo $firstname; ?>"></p>
<p>Last Name:<br />
<input type="text" name="lastname" value="<?php echo $lastname; ?>"></p>
<p>Email:<br />
<input type="text" name="email" value="<?php echo $email; ?>" size="30"></p>
<p>New Password:<br />
<input type="password" name="password" value=""></p>
<p>Confirm Password:<br />
<input type="password" name="password2" value=""></p><br>
<tr><td></td></tr>
<legend style="font-weight:bold;">Side Pools:</legend>
<tr>
<p><type=hidden value=" " name="survivor10" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="survivor10" <? if($survivor10== "1") {echo "checked";} ?>><b> Survivor $10</b></p>
<p><type=hidden value=" " name="survivor20" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="survivor20" <? if($survivor20== "1") {echo "checked";} ?>><b> Survivor2 $20</b></p>
<p><type=hidden value=" " name="loser" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="loser" <? if($loser== "1") {echo "checked";} ?> ><b> Loser $10</b></p>
<p><type=hidden value=" " name="high5" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="high5" <? if($high5== "1") {echo "checked";} ?>><b> High 5 $10</b></p>
<p><type=hidden value=" " name="margin" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="margin" <? if($margin== "1") {echo "checked";} ?> ><b> Margin $10</b></p>
<p><type=hidden value=" " name="vegas" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="vegas" <? if($vegas== "1") {echo "checked";} ?> ><b> Vegas $10</b></p>
<p><type=hidden value=" " name="confidence" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="confidence" <? if($confidence== "1") {echo "checked";} ?>><b> Confidence $10</b></p>
</tr><br>
<td><font color=red>Your Total Fee Is :</font><input type="int" size="3" name="cost" value= "<? if($cost!= "") {echo "$cost"; } else {echo "60";}?>"</td><br><br>
<!--<tr>Text alert option: Message and data rates may apply. Expect approx. 3 msgs/week.</tr> -->
<p><input type="submit" name="submit" value="Submit" class="btn btn-primary"></p>
</fieldset>
</form>

JavaScript is case sensitive, so Document and document are two different things. In your case, you want to use document. So you should change all if conditions inside tally, to use document.
Btw. never trust the user! You could do the calculation on the client side as an indicator for the user, but you should definitly do it again on the serverside or everyone could post costs as the like - even negative ones.

Related

Updating a specific row in an SQL table selected by a drop-down list in PHP

I've been making a Car Parking System for a school project, and I've been stuck on this problem for a while now. The goal of the project is to have a maximum of 10 parking slots, where the user is able to select which slot they want to be in from a drop-down box. So far, I've managed to get the drop-down box to show along with the 10 parking slots, but I could never get it to update on the row selected on the drop-down box. Here are my codes so far:
<?php
$CustomerName = $PlateNumber = $CarName = $CarColor = $Slot = "";
$CustomerNameErr = $PlateNumberErr = $CarNameErr = $CarColorErr = "";
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if(empty($_POST["CustomerName"]))
{
$CustomerNameErr = "Please fill out this field";
}
else
{
$CustomerName = $_POST["CustomerName"];
}
if(empty($_POST["PlateNumber"]))
{
$PlateNumberErr = "Please fill out this field";
}
else
{
$PlateNumber = $_POST["PlateNumber"];
}
if(empty($_POST["CarName"]))
{
$CarNameErr = "Please fill out this field";
}
else
{
$CarName = $_POST["CarName"];
}
if(empty($_POST["CarColor"]))
{
$CarColorErr = "Please fill out this field";
}
else
{
$CarColor = $_POST["CarColor"];
}
}
?>
<form class="logintext" method="POST" action="<?php htmlspecialchars("PHP_SELF");?>">
<br><b>Register Parking</b><br><br>
<!-- Slot select-->
Select Slot: <select name="slots">
<?php
$mysqli = NEW mysqli('localhost','root','','sad');
$slot_query = $mysqli->query("SELECT slot FROM parkingrecords");
while ($rows = $slot_query->fetch_assoc())
{
$SlotVal = $rows['Slot'];
echo "<option value='".$rows['Slot']."'>".$rows['Slot']."</option>";
}
?>
</select><br><br>
<!-- fill-up form; this is the data that replaces the "empty" slots on the table-->
Customer Name: <input type="text" name="CustomerName" value="<?php echo $CustomerName ?>"><br>
<span class="error"><?php echo $CustomerNameErr; ?></span><br>
Plate Number: <input type="text" name="PlateNumber" value="<?php echo $PlateNumber ?>"><br>
<span class="error"><?php echo $PlateNumberErr; ?></span><br>
Car Name: <input type="text" name="CarName" value="<?php echo $CarName ?>"><br>
<span class="error"><?php echo $CarNameErr; ?></span><br>
Car Color: <input type="text" name="CarColor" value="<?php echo $CarColor ?>"><br>
<span class="error"><?php echo $CarColorErr; ?></span><br>
<input type="submit" value="Register">
</form>
<?php
include("carpark_connections.php");
if($Slot && $CustomerName && $PlateNumber && $CarName && $CarColor)
{
$query = mysqli_query($connections, "UPDATE parkingrecords SET CustomerName = '$CustomerName', PlateNumber = '$PlateNumber', CarName = '$CarName', CarColor = '$CarColor' WHERE Slot = '$SlotVal' ");
echo "<script language = 'javascript'>alert('You have been registered!')</script>";
echo "<script>window.location.href='ParkNow.php';</script>";
} ...
Nothing happens when I try to submit the update form. The data I type in doesn't seem to go anywhere at all, but it still executes the query since the javascript alert is working. I don't know what I'm missing here. Any help would be appreciated!
EDIT: I fixed a little bit of the code and now instead of nothing happening, it just keeps on updating the 10th slot no matter which slot i select on the dropdown.
Below is an updated code please replace it with this updated code.
<?php
$CustomerName = $PlateNumber = $CarName = $CarColor = $Slot = "";
$CustomerNameErr = $PlateNumberErr = $CarNameErr = $CarColorErr = "";
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if(empty($_POST["CustomerName"])){
$CustomerNameErr = "Please fill out this field";
}else{
$CustomerName = $_POST["CustomerName"];
}
if(empty($_POST["PlateNumber"])){
$PlateNumberErr = "Please fill out this field";
}else{
$PlateNumber = $_POST["PlateNumber"];
}
if(empty($_POST["CarName"])){
$CarNameErr = "Please fill out this field";
}else{
$CarName = $_POST["CarName"];
}
if(empty($_POST["CarColor"])){
$CarColorErr = "Please fill out this field";
}else{
$CarColor = $_POST["CarColor"];
}
if(empty($_POST["slots"])){
$SlotErr = "Please fill out this field";
}else{
$Slot = $_POST["slots"];
}
}
?>
<form class="logintext" method="POST" action="<?php htmlspecialchars("PHP_SELF");?>">
<br><b>Register Parking</b><br><br>
<!-- Slot select-->
Select Slot: <select name="slots">
<?php
$mysqli = NEW mysqli('localhost','root','','sad');
$slot_query = $mysqli->query("SELECT slot FROM parkingrecords");
while ($rows = $slot_query->fetch_assoc())
{
$SlotVal = $rows['Slot'];
echo "<option value='$SlotVal'>$SlotVal</option>";
}
?>
</select><br><br>
<!-- fill-up form; this is the data that replaces the "empty" slots on the table-->
Customer Name: <input type="text" name="CustomerName" value="<?php echo $CustomerName ?>"><br>
<span class="error"><?php echo $CustomerNameErr; ?></span><br>
Plate Number: <input type="text" name="PlateNumber" value="<?php echo $PlateNumber ?>"><br>
<span class="error"><?php echo $PlateNumberErr; ?></span><br>
Car Name: <input type="text" name="CarName" value="<?php echo $CarName ?>"><br>
<span class="error"><?php echo $CarNameErr; ?></span><br>
Car Color: <input type="text" name="CarColor" value="<?php echo $CarColor ?>"><br>
<span class="error"><?php echo $CarColorErr; ?></span><br>
<input type="submit" value="Register">
</form>
<?php
include("carpark_connections.php");
if($Slot && $CustomerName && $PlateNumber && $CarName && $CarColor)
{
$query = mysqli_query($connections, "UPDATE parkingrecords SET CustomerName = '$CustomerName', PlateNumber = '$PlateNumber', CarName = '$CarName', CarColor = '$CarColor' WHERE Slot = '$Slot' ");
echo "<script language = 'javascript'>alert('You have been registered!')</script>";
echo "<script>window.location.href='ParkNow.php';</script>";
}
You are missing a part where should you accept the $_POST['slots']
if(empty($_POST["slots"]))
{
$slotErr = "Please select value for this field";
}
else
{
$slot = $_POST["slots"];
}

Update multiple record with single query in database using php [duplicate]

This question already has an answer here:
Post form and update multiple rows with mysql
(1 answer)
Closed last year.
I am making an invoice in PHP where multiple products are inserted at once into one table and there grand total goes to another table. I am trying to UPDATE the invoice in MYSQL and PHP. When I press the submit button, the multiple records data from the form goes to the update.php but the query does not run.
database.php
<?php
$connect = mysqli_connect('localhost','root','','invoice');
if (!$connect){
die("Connection failed: " . mysqli_connect_error());
}
?>
edit_invoice.php
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
table,tr,td,th { border: 1px black solid;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
Back to Invoice List<br><br>
<?php
include('database.php');
$invoice_number = $_GET['invoice_number'];
$sql = "SELECT * from invoice where invoice_number = '$invoice_number' ";
$query = mysqli_query($connect, $sql);
if ($query->num_rows > 0) {
// output data of each row
$fetch = $query->fetch_assoc();
}
?>
<form method="POST" action="update_invoice.php">
<table>
<thead>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>Width</th>
<th>Height</th>
<th>Total</th>
<th>Action</th>
</thead>
<?php
$sql2 = "SELECT * from invoice_order where invoice_number = '$invoice_number' ";
$query2 = mysqli_query($connect, $sql2);
if ($query2->num_rows > 0) {
// output data of each row
$srno = 1;
$count = $query2->num_rows;
for ($i=0; $i < $count; $i++) {
while($row = $query2->fetch_assoc()) {
?>
<tbody id="product_table">
<tr>
<td><input type="text" name="product[]" value="<?php echo $row["product"]; ?>"></td>
<td><input type="text" name="price[]" value="<?php echo $row["price"]; ?>"></td>
<td><input type="text" name="quantity[]" value="<?php echo $row["quantity"]; ?>"></td>
<td><input type="text" name="width[]" value="<?php echo $row["width"]; ?>"></td>
<td><input type="text" name="height[]" value="<?php echo $row["height"]; ?>"></td>
<td><input type="text" name="total[]" value="<?php echo $row["total"]; ?>" class="totalPrice" readonly></td>
<td><input type="button" value="X" onclick="deleteRow(this)"/></td>
</tr>
</tbody>
<?php
}
}
} else {
echo "No Record Found";
}
?>
<input type="button" name="submit" value="Add Row" onclick="add_fields();">
<span>Invoice Date:<input type="date" value="<?php echo $fetch["invoice_date"]; ?>" name="invoice_date"></span>
<span>Invoice #:<input type="text" name="invoice_number" value="<?php echo $fetch["invoice_number"]; ?>" readonly></span>
<span>Select Customer:
<select name="to_user" class="form-control">
<option><?php echo $fetch["customer_id"]; ?></option>
<?php
include('database.php');
$sql = mysqli_query($connect, "SELECT * From customer");
$row = mysqli_num_rows($sql);
while ($row = mysqli_fetch_array($sql)){
echo "<option value='". $row['customer_id'] ."'>" .$row['customer_id'] ." - " .$row['customer_name'] ."</option>" ;
}
?>
</select>
</span>
</table>
<span>Grand Total<input type="text" name="grandtotal" id="grandtotal" value="<?php echo $fetch["grandtotal"]; ?>" readonly></span><br><br>
<span>Paid Amount<input type="text" name="paid" id="paid" value="<?php echo $fetch["paid"]; ?>"></span><br><br>
<span>Balance<input type="text" name="balance" id="balance" value="<?php echo $fetch["balance"]; ?>" readonly></span><br><br>
<input type="submit" name="send" value="Submit">
</form>
</body>
<script>
const table = document.getElementById('product_table');
table.addEventListener('input', ({ target }) => {
const tr = target.closest('tr');
const [product, price, quantity, width, height, total] = tr.querySelectorAll('input');
var size = width.value * height.value;
var rate = price.value * quantity.value;
if (size != "") {
total.value = size * rate;
}else{
total.value = rate;
}
totalPrice();
});
function add_fields() {
var row = document.createElement("tr");
row.innerHTML =
'<td><input type="text" name="product[]"></td>' +
'<td><input type="text" name="price[]"></td>' +
'<td><input type="text" name="quantity[]"></td>' +
'<td><input type="text" name="width[]" value="0"></td>' +
'<td><input type="text" name="height[]" value="0"></td>' +
'<td><input type="text" name="total[]" class="totalPrice" readonly></td>' +
'<td><input type="button" value="X" onclick="deleteRow(this)"/></td>';
table.appendChild(row);
}
function deleteRow(btn) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
totalPrice();
}
function totalPrice() {
var grandtotal = 0;
var paid = 0;
$(".totalPrice").each(function() {
grandtotal += parseFloat($(this).val());
paid = grandtotal;
});
$("#grandtotal").val(grandtotal);
$("#paid").val(paid);
}
$(document).ready(function() {
$('#paid').on('input', function() {
grandtotal = $("#grandtotal").val();
paid = $("#paid").val();
balance = parseFloat(grandtotal) - parseFloat(paid);
$("#balance").val(balance);
})
});
</script>
</html>
Update_invoice.php
<?php
include('database.php');
if (isset($_POST['send'])) {
$product = $_POST['product'];
$price = $_POST['price'];
$quantity = $_POST['quantity'];
$width = $_POST['width'];
$height = $_POST['height'];
$total = $_POST['total'];
$customer_id = $_POST['to_user'];
$invoice_date = $_POST['invoice_date'];
$invoice_number = $_POST['invoice_number'];
$grandtotal = $_POST['grandtotal'];
$paid = $_POST['paid'];
$balance = $_POST['balance'];
$amount_status = "";
if ($grandtotal == $paid) {
$amount_status = "Paid";
} elseif ($grandtotal == $balance) {
$amount_status = "Due";
} else {
$amount_status = "Partial";
}
// Start of Updating data to invoice_order table
for ($i = 0; $i < count($_POST['total']); $i++) {
if ($i <> count($_POST['total'])) {
$sql = "UPDATE invoice_order SET invoice_number = '$invoice_number' , product = '$_POST['product'][$i]', price = '$_POST['price'][$i]' , quantity = '$_POST['quantity'][$i]', width = '$_POST['width'][$i]' , height = '$_POST['height'][$i]' , total = '$_POST['total'][$i]' WHERE invoice_number='$invoice_number' ";
$query = mysqli_query($connect, $sql);
if ($query) {
header('location: list_invoice.php');
} else {
echo "Unable to enter records in invoice_order table";
}
}
}
// End of updating data to invoice_order table
// Start of updating data to invoice table
$sql2 = "UPDATE invoice SET customer_id = '$customer_id', grandtotal = '$grandtotal', invoice_number = '$invoice_number', invoice_date = '$invoice_date', paid = '$paid', balance = '$balance', amount_status = '$amount_status' WHERE invoice_number='$invoice_number' ";
$query2 = mysqli_query($connect, $sql2);
if ($query2) {
header('location: list_invoice.php');
} else {
echo "Unable to enter record in invoice table";
}
// End of updating data to invoice table
}
?>
The approach you are using is not the preferred way of doing the job. Use mysql prepare statement. This will make the code clean, easy to read and secured. Here is the link you can refer Mysql Prepared Statement in PHP

Posting info from PHP to a database [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I can not for the life of me figure out why the info i enter in from the form when it runs, will not enter into the database that i have linked to it. The info from the database shows up when I manually put it in, and the delete button works to erase the section of the database, but adding things doesnt work using the php form. Please help!
<?php
// A simple PHP script demonstrating how to connect to MySQL.
$servername = getenv('IP');
$username = getenv('C9_USER');
$password = "potato12";
$database = "c9";
$dbport = 3306;
// Create connection
$db = new mysqli($servername, $username, $password, $database, $dbport);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
echo "Connected successfully (".$db->host_info.")";
$thisPHP = $_SERVER['PHP_SELF'];
echo <<<EOT
<form action="$thisPHP" method="POST">
Name: <input type="text" name="Name"> Address: <input type="text" name="Address"><br>
Phone: <input type="text" name="Phone"> Email: <input type="text" name="Email"><br>
Availability: <input type="Radio" name="Availability" Value="Now"> Now(<1 month) <input type="Radio" name="Availability" value="Soon"> Soon(1-3 months) <input type="Radio" name="Availability" value="Exploring"> Exploring(3+ months)<br>
Company Title: <input type="text" name="Title"><br>
Job Title: <input type="text" name="Job Title"><br>
Description: <input type="text" name="Description"><br>
Skill 1 <select name="Skill1">
<option>Organized</option><option>Works in a team</option><option>Problem Solving</option>
</select>
Skill 2 <select name="Skill2">
<option>Organized</option><option>Works in a team</option><option>Problem Solving</option></select>
Skill 3 <select name="Skill3">
<option>Organized</option><option>Works in a team</option><option>Problem Solving</option></select><br>
Experiance <select name="Experiance">
<option>0</option><option>1-3</option><option>3-5</option><option>5-10</option><option>10+</option></select><br>
Position: <input type="radio" name="Position" value="Team-Member"> Team-Member <input type="radio" name="Position" value="Team-Leader"> Team-Leader <input type="radio" name="Position" value="Manager"> Manager <input type="radio" name="Position" value="Executive"> Executive <br>
<input type="submit" name="Add" value="Add"> <br>
<hr>
</form>
EOT;
// Start executing the script
$id = $_POST["ID"];
$Name = $_POST["Name"];
$Email = $_POST["Email"];
$Phone = $_POST["Phone"];
$Address = $_POST["Address"];
$Availability = $_POST["Availability"];
$Ctitle = $_POST["Title"];
$Jtitle = $_POST["Job Title"];
$Description = $_POST["Description"];
$Skill1 = $_POST["Skill1"];
$Skill2 = $_POST["Skill2"];
$Skill3 = $_POST["Skill3"];
$Experiance = $_POST["Experiance"];
$Position = $_POST["Position"];
// At least name must be specified
if (!empty($name)){
// Form sql string
$sql = "insert into Employee (ID, Name, Phone, Email, Address, Availability, Title, Job Title, Description, Skill1, Skill2, Skill3, Experiance, Position ) values ('$id', '$Name', '$Phone', '$Email', '$Address' , '$Availability' , '$Ctitle' , '$Jtitle' , '$Description' , '$Skill1' , '$Skill2' , '$Skill3', '$Experiance' , '$Position')";
if ($db->query ($sql) == TRUE)
{
echo "Record added <br>";
}
}
// Check if delete is selected
if (isset($_POST['btnDelete'])) {
$gid = $_POST['gid'];
$sql = "delete from Employee where id='$id'";
if ($db->query ($sql) == TRUE)
{
echo "Record deleted <br>";
}
}
else if (isset($_POST['btnEdit'])) {
$sql = "select * from Employee where id='$id'";
if (($result = $db->query ($sql)) == TRUE)
{
while($row = $result->fetch_assoc()) {
$id = $_POST["ID"];
$Name = $_POST["Name"];
$Email = $_POST["Email"];
$Phone = $_POST["Phone"];
$Address = $_POST["Address"];
$Availability = $_POST["Availability"];
$Ctitle = $_POST["title"];
$Jtitle = $_POST["Job Title"];
$Description = $_POST["Description"];
$Skill1 = $_POST["Skill1"];
$Skill2 = $_POST["Skill2"];
$Skill3 = $_POST["Skill3"];
$Experiance = $_POST["Experiance"];
}
}
echo <<<EOE
<form action="$thisPHP" method="POST">
Name: <input type="text" name="name"> Address: <input type="text" name="Address"><br>
Phone: <input type="text" name="phone"> Email: <input type="text" name="email"><br>
Availability: <input type="Radio" name="Availability" Value="Now"> Now(<1 month) <input type="Radio" name="Availability" value="Soon"> Soon(1-3 months) <input type="Radio" name="Availability" value="Exploring"> Exploring(3+ months)<br>
Company Title: <input type="text" name="title"><br>
Job Title: <input type="text" name="Job Title"><br>
Description: <input type="text" name="description"><br>
Skill 1 <select name="skill1">
<option>Organized</option><option>Works in a team</option><option>Problem Solving</option>
</select>
Skill 2 <select name="skill2">
<option>Organized</option><option>Works in a team</option><option>Problem Solving</option></select>
Skill 3 <select name="skill3">
<option>Organized</option><option>Works in a team</option><option>Problem Solving</option></select><br>
Experiance <select name="experiance">
<option>0</option><option>1-3</option><option>3-5</option><option>5-10</option><option>10+</option></select><br>
Position: <input type="radio" name=Position" value="Team-Member"> Team-Member <input type="radio" name=Position" value="Team-Leader"> Team-Leader <input type="radio" name=Position" value="Manager"> Manager <input type="radio" name=Position" value="Executive"> Executive <br>
<input type="submit" name="Add" value="Add"> <br>
<hr>
</form>
EOE;
}
// Show rows
$sql = "SELECT * FROM Employee";
$result = $db->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc())
{
$id = $row["ID"];
echo
"id: " . $id . " - Name: " . $row["Name"] .
" - Email: " . $row["Email"] .
" - Phone: " . $row["Phone"] .
" - Address: " . $row["Address"] .
" - Availability: " . $row["Availability"] .
" - Company Title: " . $row["Company Title"] .
" - Job Title: " . $row["Job Title"] .
" - Description: " . $row["Description"] .
" - Skill 1: " . $row["Skill1"] .
" - Skill 2: " . $row["Skill2"] .
" - Skill 3: " . $row["Skill3"] .
" - Experiance: " . $row["Experiance"];
echo " <form action=\"$thisPHP\" method='post' style=\"display:inline\" >";
echo "<input type='hidden' name='id' value='$id'>";
echo "<input type='submit' name='btnEdit' value='Edit'> ";
echo "<input type='submit' name='btnDelete' value='Delete'> </form>" . "<br>";
}
} else
{
echo "0 results";
}
$db->close();
?>

Only 1 checkbox can be checked? PHP

I'm having an issue with checkboxes. I can check both checkboxes, but after submitting, only 1 checkbox is checked. I want them to both be checked after submitting.
Why are they not both checked after submit? What's going wrong in the process?
<?php
$id = $_GET["id"];
$stmt = $dbConnection->prepare('SELECT * FROM paginas WHERE id = ?');
$stmt->bind_param('s', $id);
$stmt->execute();
$result = $stmt->get_result();
if(mysqli_num_rows($result) > 0) {
while ($row = $result->fetch_assoc()) {
?>
Terugkeren naar mijn pagina's
<h1>Wijzig pagina: <?php echo $row["name"]; ?></h1>
<?php
if(isset($_POST["opslaan"])) {
if(empty($_POST["heading"])) {
echo '<p class="error">Titel kan niet leeg zijn</p>';
} elseif(empty($_POST["content"])) {
echo '<p class="error">Content kan niet leeg zijn</p>';
} else {
$heading = $_POST["heading"];
$content = $_POST["content"];
$updated = date("d-m-Y H:i:s");
$id = $row["id"];
$public = $_POST["public"];
$menu = $_POST["menu"];
$stmt = $dbConnection->prepare('UPDATE paginas SET heading = ?, content = ?, updated = ?, public = ?, menu = ? WHERE id = ?');
$stmt->bind_param('ssssss', $heading, $content, $updated, $public, $menu, $id);
$stmt->execute();
echo '<p class="success">Wijzigingen zijn succesvol opgeslagen. Bekijken</p>';
}
} else {
?>
<form method="POST" action="">
<input type="text" name="heading" id="fulltext" placeholder="Titel" value="<?php echo $row["heading"]; ?>">
<textarea id="fullbox" class="editor" name="content"><?php echo $row["content"]; ?></textarea>
<div class="pad"><input type="checkbox" name="public" id="public" value="<?php
if($row["public"] == "1") {
echo '0';
} else {
echo '1';
}
?>" <?php
if($row["public"] == "1") {
echo ' checked';
} else {
echo '';
}
?>><label for="public" class="checker">Gepubliceerd</label><input type="checkbox" name="menu" id="menu" value="<?php
if($row["menu"] == "1") {
echo '0';
} else {
echo '1';
}
?>" <?php
if($row["menu"] == "1") {
echo ' checked';
} else {
echo '';
}
?>><label for="menu" class="checker">Menu</label></div>
<div class="clear"></div>
<p id="left">Laatst gewijzigd: <?php echo $row["updated"]; ?></p><input type="submit" value="Bewaar wijzigingen" name="opslaan" class="nomp">
<div class="clear"></div>
</form>
<?php
}
}
} else {
echo '<p>Deze pagina bestaat niet.</p>';
}
?>
The value of the checkbox should always be 1 instead of the condition you have there, and when preparing to put it in the database you should do:
$public = isset($_POST['public']) ? 1 : 0;
Otherwise, you will be submitting the value 0 every other time, which will turn the value off even if you checked the box.
In addition to Niet the Dark Absol's answer above you should create dynamic names for each element or use name="public[] to capture all selected values.
You must set your input name with [] after the name. like check_list[].
For example:
<form action="test.php" method="post">
<input type="checkbox" name="check_list[]" value="value 1">
<input type="checkbox" name="check_list[]" value="value 2">
<input type="checkbox" name="check_list[]" value="value 3">
<input type="checkbox" name="check_list[]" value="value 4">
<input type="checkbox" name="check_list[]" value="value 5">
<input type="submit" />
</form>
<?php
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
echo $check; //echoes the value set in the HTML form for each checked checkbox.
//so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
//in your case, it would echo whatever $row['Report ID'] is equivalent to.
}
}
?>

Only updating half the data to MySQL table

The code below is for updating data in a MySQL table. It was written by pulling all the data from one query but I have tried to adapt it to pull data from two queries to improve the ordering. Now only some of the records update when the submit button is clicked and I'm not sure how to fix it.
The original code was:
if(isset($_POST['submit'])){
$password = $_POST['password'];
$total = $_POST['total'];
$park_id = $_POST['park_id'];
if($password=="****"){
for($i =1; $i<=$total; $i++){
$ride_id = $_POST['ride_id'.$i];
$name = $_POST['ride_name'.$i];
$type = $_POST['type'.$i];
$topride = $_POST['topride'.$i];
$info = $_POST['info'.$i];
$speed = $_POST['speed'.$i];
$height = $_POST['height'.$i];
$length = $_POST['length'.$i];
$inversions = $_POST['inversions'.$i];
$query = "update tpf_rides set name='$name',type='$type'";
if($topride!=""){$query .= ",top_ride=$topride";}
if($info!=""){$query .= ",info='$info'";}
if($height!=""){$query .= ",height=$height";}
if($length!=""){$query .= ",length=$length";}
if($speed!=""){$query .= ",speed=$speed";}
if($inversions!=""){$query .= ",inversions=$inversions";}
$query .= " where ride_id=".$ride_id." and park_id=".$park_id;
mysql_query($query);
}
header('location:index.php?msg=Successfully Updated.');
}else{
echo "Enter Correct Password.";
}
}
if(isset($_GET['id'])){
$id = $_GET['id'];
$sql = "select name from tpf_parks where park_id=".$id;
$result = mysql_fetch_array(mysql_query($sql));
echo '<h2>'.$result['name'].'</h2>';
$qry = "select * from tpf_rides where park_id=".$id;
$res = mysql_query($qry);
$no = mysql_num_rows($res);
$x = 0;
if($no>0){ ?>
<form action="" method="post">
<input type="hidden" value="<?=$no?>" name="total">
<input type="hidden" value="<?=$id?>" name="park_id">
<table> <?php
while($row = mysql_fetch_array($res)){ $x++;
echo '<input type="hidden" value="'.$row['ride_id'].'" name="ride_id'.$x.'">';
echo '<tr><td>Name : </td><td><input type="text" name="ride_name'.$x.'" value="'.$row['name'].'"></td></tr>';
echo '<tr><td>Type : </td><td><input type="text" name="type'.$x.'" value="'.$row['type'].'"></td></tr>';
echo '<tr><td>Top Ride : </td><td><input type="text" name="topride'.$x.'" value="'.$row['top_ride'].'"></td></tr>';
echo '<tr><td>Info : </td><td><input type="text" name="info'.$x.'" value="'.$row['info'].'"></td></tr>';
if($row['type']!="Roller Coaster"){
echo '<tr><td>Speed : </td><td><input type="text" name="speed'.$x.'" value="'.$row['speed'].'"></td></tr>';
echo '<tr><td>Height : </td><td><input type="text" name="height'.$x.'" value="'.$row['height'].'"></td></tr>';
echo '<tr><td>Length : </td><td><input type="text" name="length'.$x.'" value="'.$row['length'].'"></td></tr>';
echo '<tr><td>Inversions : </td><td><input type="text" name="inversions'.$x.'" value="'.$row['inversions'].'"></td></tr>';
}
echo '<tr><td colspan="2"><hr></td></tr>';
} ?>
<tr><td>Password :</td><td><input type="password" value="" name="password" id="password"></td></tr>
<tr><td></td><td><input onclick="return check()" type="submit" value="Save" name="submit"></td></tr>
</table>
</form>
<?php
}else{
echo "No Rides in this park.";
}
}else{
if(isset($_GET['msg'])){echo $_GET['msg'].'<br>';}
$qry = "select * from tpf_parks order by name";
$res = mysql_query($qry);
?>
Select Park : <select name="park" onChange="getdata(this.options[this.selectedIndex].value)">
<option value="">Select Park</option>
<?php
while($row = mysql_fetch_array($res)) { ?>
<option value="<?=$row['park_id']?>"><?=$row['name']?></option>
<? } ?>
</select>
<?php } ?>
and the new code where I altered the queries is here:
if(isset($_POST['submit'])){
$password = $_POST['password'];
$total = $_POST['total'];
$park_id = $_POST['park_id'];
if($password=="*****"){
for($i =1; $i<=$total; $i++){
$ride_id = $_POST['ride_id'.$i];
$name = $_POST['ride_name'.$i];
$type = $_POST['type'.$i];
$topride = $_POST['topride'.$i];
$info = $_POST['info'.$i];
$speed = $_POST['speed'.$i];
$height = $_POST['height'.$i];
$length = $_POST['length'.$i];
$inversions = $_POST['inversions'.$i];
$query = "update tpf_rides set name='$name',type='$type'";
if($topride!=""){$query .= ",top_ride=$topride";}
$query .= ",info='$info'";
if($height!=""){$query .= ",height=$height";}
if($length!=""){$query .= ",length=$length";}
if($speed!=""){$query .= ",speed=$speed";}
if($inversions!=""){$query .= ",inversions=$inversions";}
$query .= " where ride_id=".$ride_id." and park_id=".$park_id;
mysql_query($query);
}
header('location:index.php?msg=Successfully Updated.');
}else{
echo "Enter Correct Password.";
}
}
if(isset($_GET['id'])){
$id = $_GET['id'];
$sql = "select name from tpf_parks where park_id=".$id;
$result = mysql_fetch_array(mysql_query($sql));
echo '<h2>'.$result['name'].'</h2>';
$qry = "SELECT * FROM tpf_rides
WHERE park_id = $id AND type LIKE '%Roller Coaster%' ORDER BY name ASC";
$res = mysql_query($qry);
$qry2 = "SELECT * FROM tpf_rides
WHERE park_id = $id AND type NOT LIKE '%Roller Coaster%' ORDER BY name ASC";
$res2 = mysql_query($qry2);
$qry3 = "SELECT * FROM tpf_rides WHERE park_id = $id";
$res3 = mysql_query($qry2);
$no = mysql_num_rows($res3);
$x = 0;
$xx = 0;
if($no>0){ ?>
<form action="" method="post">
<input type="hidden" value="<?=$no?>" name="total">
<input type="hidden" value="<?=$id?>" name="park_id">
<table> <?php
while($row = mysql_fetch_array($res)){ $x++;
echo '<input type="hidden" value="'.$row['ride_id'].'" name="ride_id'.$x.'">';
echo '<tr><td>Name : </td><td><input type="text" name="ride_name'.$x.'" value="'.$row['name'].'"></td></tr>';
echo '<tr><td>Type : </td><td><input type="text" name="type'.$x.'" value="'.$row['type'].'"></td></tr>';
echo '<tr><td>Top Ride : </td><td><input type="text" name="topride'.$x.'" value="'.$row['top_ride'].'"></td></tr>';
echo '<tr><td>Info : </td><td><input type="text" name="info'.$x.'" value="'.$row['info'].'"></td></tr>';
echo '<tr><td>Speed : </td><td><input type="text" name="speed'.$x.'" value="'.$row['speed'].'"></td></tr>';
echo '<tr><td>Height : </td><td><input type="text" name="height'.$x.'" value="'.$row['height'].'"></td></tr>';
echo '<tr><td>Length : </td><td><input type="text" name="length'.$x.'" value="'.$row['length'].'"></td></tr>';
echo '<tr><td>Inversions : </td><td><input type="text" name="inversions'.$x.'" value="'.$row['inversions'].'"></td></tr>';
echo '<tr><td colspan="2"><hr></td></tr>';
}
while($row2 = mysql_fetch_array($res2)){ $xx++;
echo '<input type="hidden" value="'.$row2['ride_id'].'" name="ride_id'.$xx.'">';
echo '<tr><td>Name : </td><td><input type="text" name="ride_name'.$xx.'" value="'.$row2['name'].'"></td></tr>';
echo '<tr><td>Type : </td><td><input type="text" name="type'.$xx.'" value="'.$row2['type'].'"></td></tr>';
echo '<tr><td>Top Ride : </td><td><input type="text" name="topride'.$xx.'" value="'.$row2['top_ride'].'"></td></tr>';
echo '<tr><td>Info : </td><td><input type="text" name="info'.$xx.'" value="'.$row2['info'].'"></td></tr>';
echo '<tr><td colspan="2"><hr></td></tr>';
}
?>
<tr><td>Password :</td><td><input type="password" value="" name="password" id="password"></td></tr>
<tr><td></td><td><input onclick="return check()" type="submit" value="Save" name="submit"></td></tr>
</table>
</form>
<?php
}else{
echo "No Rides in this park.";
}
}else{
if(isset($_GET['msg'])){echo $_GET['msg'].'<br>';}
$qry = "select * from tpf_parks order by name";
$res = mysql_query($qry);
?>
Select Park : <select name="park" onChange="getdata(this.options[this.selectedIndex].value)">
<option value="">Select Park</option>
<?php
while($row = mysql_fetch_array($res)) { ?>
<option value="<?=$row['park_id']?>"><?=$row['name']?></option>
<? } ?>
</select>
<?php } ?>
After testing what is not getting amended, it is data from both the LIKE and NOT LIKE queries being skipped so perhaps a record count problem?
Any ideas what I have done wrong?
Are you sure your column type has value 'Roller Coaster' or not?
Sorry to post as an answer as I have no rights no comment.

Categories