$_GET[ID] from two tables [closed] - php

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am currently trying to fetch two segments of data from two different tables and display them in an "edit" type format.
I can get either "incident" or "location" to displaying using the $_GET[id] variable as a way to use the incidentID primary key reference. I thought about setting my Databases auto sequence so that incident and location would be sync, but that is not really a solution.
How would one go about using the $_GET[id] variable to call two different tables?
The code is as follows, on a side note I am aware that my sql is open for injection and I should be slapped on the wrist for not using PDOs.
I can add the DB structure if that would at all help but I would prefer to leave the DB structure where it is at currently.
searching for the data in the first place
FILE) . '\connection.php';
// Process the search query
if(isset($_POST['searchquery']) && $_POST['searchquery'] != ""){
// run code if condition meets here
$searchquery = preg_replace('#[^a-z 0-9?]#i', '', $_POST['searchquery']);
if($_POST['filter1'] == "0"){
$sqlCommand = "SELECT * FROM `incident` WHERE `iTypeID` = 0 AND `disasterName` LIKE '%$searchquery%'";
}else if($_POST['filter1'] == "1"){
$sqlCommand = "SELECT incidentID FROM `incident` WHERE `iTypeID` = 2 AND `disasterName` LIKE '%$searchquery%'";
}else if($_POST['filter1'] == "2"){
$sqlCommand = "SELECT incidentID FROM `incident` WHERE `iTypeID` = 2 AND `disasterName` LIKE '%$searchquery%'";
}else if($_POST['filer1'] == "3"){
$sqlCommand = "SELECT incidentID FROM `incident` WHERE `iTypeID` = 3 AND `disasterName` LIKE '%$searchquery%'";
}else if($_POST['filter1'] == "4"){
$sqlCommand = "SELECT incidentID FROM `incident` WHERE `iTypeID` = 2 AND `disasterName` LIKE '%$searchquery%'";
}else if($_POST['filter1'] == "5"){
$sqlCommand = "SELECT incidentID FROM `incident` WHERE `iTypeID` = 2 AND `disasterName` LIKE '%$searchquery%'";
}else if($_POST['filter1'] == "6"){
$sqlCommand = "SELECT incidentID FROM `incident` WHERE `iTypeID` = 2 AND `disasterName` LIKE '%$searchquery%'";
}else if($_POST['filter1'] == "7"){
$sqlCommand = "SELECT incidentID FROM `incident` WHERE `iTypeID` = 2 AND `disasterName` LIKE '%$searchquery%'";
}
$query = mysql_query($sqlCommand) or die(mysql_error());
$count = mysql_num_rows($query);
if($count >= 1){
while($row = mysql_fetch_array($query)){
$incidentID = $row["incidentID"];
$dangerLevel =$row["dangerLevel"];
$search_output .= "Item ID: <br> $incidentID <br> Danger Level: <br> $dangerLevel<br/>
Modify Entry
<span> </span>
Delete Entry <br /><br />";
} // close while
} else {
}
}
?>
<html>
<head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<fieldset>
<legend>Incident Search Form</legend>
<p><label>Search a Disaster (by name): <input name="searchquery" type="text"></label></p>
<p><label>Search by Type<select name="filter1"></label></p>
<option value="0">None</option>
<option value="1">Fire</option>
<option value="2">Flood</option>
<option value="3">Hurricane</option>
<option value="4">Tropical Storm</option>
<option value="5">LandSlide</option>
<option value="6">Biological Outbreak</option>
</select>
</fieldset>
<input name="myBtn" type="submit">
<br />
<br />
<div>
<?php echo $search_output; ?>
</div>
</form>
</body>
</head>
</html>
Modifying the data after it has been searched
FILE) . '\connection.php';
if(!isset($_POST['submit'])){
$q = "SELECT * FROM incident WHERE incidentID = $_GET[id]";
$ql = "SELECT * FROM location where locationID = $_GET[id]";
$results = mysql_query($q);
$incident = mysql_fetch_array($results);
$results2 = mysql_query($ql);
$incident2 = mysql_fetch_array($results2);
}
?>
</html>
<head>
<body>
<h1>You are Modifying an Incident</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<fieldset>
<legend>Incident</legend>
<p><label>Disaster Name: <input type="text" name ="inputIncident" value = "<?php echo $incident['disasterName']; ?>" placeholder = "SampleTree Fire" /></label></p>
<p><label>Disaster Description: <input type="text" name ="inputDescription" value = "<?php echo $incident['description']; ?>" placeholder = "Large Forest fire near" /></label></p>
<p><label>Time of Incident: <input type="time" name ="inputTime" value = "<?php echo $incident['time']; ?>" placeholder = "hh:mm:ss"/></label></p>
<p><label>Date of Incident: <input type="date" name ="inputDate" value = "<?php echo $incident['date']; ?>" placeholder = "yyyy/mm/dd"/></label></p>
<p><label>Danger of Incident: <input type="number" name ="inputdangerLevel" placeholder = "1-10" value = "<?php echo $incident['dangerLevel']; ?>" /></label></p>
<p><label for ="type">Select Disaster Type:</label>
<select id="type" name="type" value = "<?php echo $incident['iTypeID']; ?>"
<option value="0">None</option>
<option value="1">Fire</option>
<option value="2">Flood</option>
<option value="3">Hurricane</option>
<option value="4">Tropical Storm</option>
<option value="5">LandSlide</option>
<option value="6">Biological Outbreak</option>
</select>
</fieldset>
<fieldset>
<legend>Location</legend>
<p><label>Street Name:<input type="text" name ="inputStreet" value = "<?php echo $incident2['streetName']; ?>" placeholder = "Avalon Place" /></label></p>
<p><label>Street Number:<input type="number" name ="inputNumber" value = "<?php echo $incident2['streetNumber']; ?>" placeholder = "9" /></label></p>
<p><label>Suburb:<input type="text" name ="inputSuburb" value = "<?php echo $incident2['suburb']; ?>" placeholder = "Upper Kedron" /></label></p>
<p><label>Postcode:<input type="text" name ="inputPostCode" value = "<?php echo $incident2['postCode']; ?>" placeholder = "4055" /></label></p>
<p><label>Region:<input type="number" name ="inputRegion" value = "<?php echo $incident2['region']; ?>" placeholder = "4" /></label></p>
<p><label>Lattitude:<input type="text" name ="inputLattitude" value = "<?php echo $incident2['mapLat']; ?>" placeholder = "136.10" /></label></p>
<p><label>Longitude:<input type="text" name ="inputLongitude" value = "<?php echo $incident2['mapLon']; ?>" placeholder = "182.86" /></label></p>
<p><label for ="state">State:</label>
<select id="state" name="state" value = "<?php echo $incident2['state']; ?>">
<option value="QLD">QLD</option>
<option value="NSW">NSW</option>
<option value="NT">NT</option>
<option value="ACT">ACT</option>
<option value="SA">SA</option>
<option value="WA">WA</option>
<option value="TAS">TAS</option>
</select>
</fieldset>
</p>
<br/>
</fieldset>
<input type="hidden" name="id" value="<?php echo $_GET['id'];?>"/>
<!--<input type="hidden" name="id2" value="<?php echo $_GET['id'];?>"/>-->
<input type="submit" name="submit" value="modify"/>
</form>
</body>
</head>
</html>
<?php
if(isset($_POST['submit'])){
$u = "UPDATE incident SET `disasterName`='$_POST[inputIncident]',
`description`='$_POST[inputDescription]',
`time`='$_POST[inputTime]',
`date`='$_POST[inputDate]',
`dangerLevel`='$_POST[inputdangerLevel]',
`iTypeID`='$_POST[type]'
WHERE incidentID = $_POST[id]";
$ul = "UPDATE location SET `streetName`='$_POST[inputStreet]',
`steetNumber`='$_POST[inputNumber]',
`suburb`='$_POST[inputSuburb]',
`postcode`='$_POST[inputPostCode]',
`region`='$_POST[inputRegion]',
`lattitude`='$_POST[inputLattitde]',
`longitude`='$_POST[inputLongitude]',
`state`='$_POST[state]'
WHERE locationID = $_POST[id]";
mysql_query($u) or die (mysql_error());
mysql_query($ul) or die (mysql_error());
echo "User has been modified!";
header ('Location: output.php');
} else{
}
?>
Incident
Column Type Null Default Links to
incidentID int(15) No
dangerLevel int(2) No
description varchar(250) No
time time No
date date No
isresolved tinyint(1) No
locationID int(11) No location -> locationID
isPublic tinyint(1) No
iTypeID int(11) No itype -> iTypeID
disasterName text No
Location
Column Type Null Default
locationID int(10) No
postCode int(4) No
region text No
state text No
mapLat float No
mapLon float No
streetNumber int(11) No
streetName text No
suburb text No
I think I might of found a different way to do it but still need a little hand on doing so, how would one expand this out so $row['incidentID'] and $row['locationID'] would be assigned to ID and ID2?
Modify Entry

If this is a 1:M relationship (a location can have many incidents), you'd want to join the tables together:
select * from incident i, location l where i.id = ? and i.location_id = l.id
Each row would have columns from incident and the corresponding location.
EDIT:
You can update the location via the incident ID using an update join:
update location l
join incident i on i.location_id = l.id
set l.city = ?
where i.id = ?
(You can also combine the 2 tables into one if this is a 1:1 relationship where each incident has a unique location.)

Related

How can I sort table output when the query is dependent on a $_GET with only PHP?

I have a Website which presents the tools from one table and the corresponding ratings from another table within on page calles f_toolseite.php. I would like for the user to be able to sort the ratings according to best rating and worst ratings. however, since I am using only php the info which tool is being looked at is getting deleted when i press the button to sort the ratings. What I mean by that is that the $_GET variables im using to get to the tool and ratings the user wishes to see are being deleted from the adress bar.
Ive tought of implementing sessions but i cant get it to work. is there any way i can solve this problem with php only?
here is my code
for f_toolseite.php
'''
<html>
<head>
<center>
<div class="tool-container">
<?php
$name = mysqli_real_escape_string($conn, $_GET['name']);
$sql = "SELECT * FROM Tools WHERE t_name = '$name' ";
$result = mysqli_query($conn, $sql);
$queryResults = mysqli_num_rows($result);
if($queryResults > 0 ){
while ($row = mysqli_fetch_assoc($result)){
## $image = base64_encode($row['t_bild']);
## echo "
## <img src=data:image/png;base64,'$image'>";
echo " <div class='tool-box'>
<img src=".$row['t_logo']. " width= 200>
<h3> ".$row['t_kategorie']."</h3>
<br>
<img src=".$row['t_bild']. " width= 800>
<br>
<br>
<p>".$row['t_beschreibung']."<p>
<br>
<p><b>Probier's doch gleich aus!</b></p>
".$row['t_link']."
</div>";
}
}
?>
<br>
<br>
<br>
<br>
<div class="avg-container">
<?php
$id = mysqli_real_escape_string($conn, $_GET['id']);
$sql3 = "SELECT ROUND (AVG (b_nivg)) AS average FROM Bewertungen WHERE t_id = '$id'";
$result3 = mysqli_query($conn, $sql3);
$row = mysqli_fetch_assoc($result3);
$average = $row['average'];
echo ("ALLES IN ALLEM EINE $average VON 10 ");
$sql4 = "SELECT b_industrie
COUNT(b_industrie) AS oft
FROM Bewertungen WHERE t_id = '$id'
GROUP BY b_industrie
ORDER BY oft DESC
LIMIT 1";
$result4 = mysqli_query($conn, $sql4);
$row = mysqli_fetch_assoc($result4);
$industry = $row['oft'];
echo ("Am beliebtesten in der $industry Industrie ");
?>
</div>
<br>
<br>
<br>
<div class="filter-container">
<form action="f_toolseite.php" method="post">
<select name="sort">
<option value="" selected="selected">Nach den neusten Bewertungen geordnet</option>
<option value="b_nivg ASC">Am besten bewertet</option>
<option value="b_nivg DESC">Am schlechtesten bewertet</option>
</select>
<input name="search" type="submit" value="Ordnen"/>
</form>
<?php
if(isset($_POST['sort'])) {
$sort = $_POST['sort'];
}
?>
</div>
<div class="rate-container">
<?php
$id = mysqli_real_escape_string($conn, $_GET['id']);
if(!empty($sort)){
$sql2 = "SELECT * FROM Bewertungen WHERE t_id = '$id' ORDER BY b_datum DESC,'$sort'";
}
else{
$sql2 = "SELECT * FROM Bewertungen WHERE t_id = '$id' ORDER BY b_datum DESC";
}
$result2 = mysqli_query($conn, $sql2);
$queryResults2 = mysqli_num_rows($result2);
$crown= "https://project-disti.wbs.hs-rm.de/learn/ss2021/workspace/dbmgruppe2/Collatio%20(22.06.2021)/img/Webtool-Bilder/crown_PNG16.png";
if($queryResults2 > 0 ){
while ($row = mysqli_fetch_assoc($result2)){
echo " <div class='rating-box'>
<p>".$row['b_vorname']." ".$row['b_nachname']."</p>
<br>
<p>".$row['b_industrie']."</p>
<p>".$row['b_dauer']."<p>
<p>".$row['b_niveau']."<p>
".( $row['b_exp'] == 'pro' ? "<img src= $crown width:10 />" : "" )."
<p>Design: ".$row['b_niv1']." / 10 </p>
<p>Intuitivität: ".$row['b_niv2']." / 10 </p>
<p>Vielseitigkeit: ".$row['b_niv3']." / 10 </p>
<p>Mehrwert: ".$row['b_niv4']." / 10 </p>
<p>Einzigartigkeit: ".$row['b_niv5']." / 10 </p>
<p>Gesamteindruck: ".$row['b_nivg']." / 10 </p>
<p>".$row['b_pro']."<p>
<p>".$row['b_con']."</p>
<p>".$row['b_kommentar']."</p>
<p>".$row['b_datum']."</p>
<br>
<br>
</div>";
}
}
?>
</div>
<footer>
<?php include '../Include/footer.php';?>
</footer>
</body>
</html> '''
You need to change your html form like this and to fetch sort value in from get request instead of post
<form action="f_toolseite.php" method="get">
<input type = "hidden" name = "name" value = "<?= $_GET['name'] ?>" />
<input type = "hidden" name = "id" value = "<?= $_GET['id'] ?>" />
<select name="sort">
<option value="" selected="selected">Nach den neusten Bewertungen geordnet</option>
<option value="b_nivg ASC">Am besten bewertet</option>
<option value="b_nivg DESC">Am schlechtesten bewertet</option>
</select>
<input name="search" type="submit" value="Ordnen"/>

not able to get values from database and updating values to the database

into schooling entry form, I am not able to get value of employee_id from post.
I did Print_r for $employee_id, blank output is rendered.
Also if allocated static value to $employee_id, $sum contains only value posted through the form, instead it should show the value from input form plus value from existing value available in database.
<?php
$get = db_query("SELECT field_employee_id_value FROM field_data_field_employee_id ORDER BY field_employee_id_value ASC");
$getempnames = db_query("SELECT field_employee_id_value FROM field_data_field_employee_id ORDER BY field_employee_id_value ASC");
if(isset($_POST['apply'])){
$sql = db_query("SELECT COUNT(id) as count_id FROM schooling WHERE employee_id = '$_POST[employee_id]' AND claim_year = '$_POST[claim_year]'");
$row = $sql->fetchAssoc();
if('1' == $row['count_id']){
$sqlupdate = db_query("UPDATE schooling SET limit_amount = '".$_POST['limit_amount']."' WHERE employee_id = '$_POST[employee_id]'");
echo "Schooling limit updated to user ";
} elseif ('0' == $row['count_id']){
$sqlinsrt = db_query("INSERT INTO schooling (employee_id, limit_amount, claim_year) VALUES ('".$_POST["employee_id"]."','".$_POST["limit_amount"]."','".$_POST["claim_year"]."')" );
echo "Schooling limit applied to user";
} else{
echo "Already Applied schooling limit";
}
}
if(isset($_POST['save'])){
$employee_id = $_POST['employee_id'];
$claim_amount = $_POST['claim_amount'];
$claim_year = $_POST['claim_year'];
$sqlchkemp = db_query("SELECT COUNT(id) as count_id FROM schooling WHERE employee_id = '$employee_id' AND claim_year = '$claim_year'");
$empavailable = $sqlchkemp->fetchAssoc();
if('1' == $empavailable['count_id']){
$getlimit = db_query("SELECT limit_amount FROM schooling WHERE employee_id = '$employee_id' AND claim_year = '$claim_year'");
$limit = $getlimit->fetchAssoc();
$getemptotalclaim = db_query("SELECT claim_amount FROM schooling
WHERE employee_id = '$employee_id' AND claim_year = '$claim_year'");
$emptotalclaim = $getemptotalclaim->fetchAssoc();
$totalclaimed = array_sum($emptotalclaim);
$availability = $limit['limit_amount'] - $_POST['claim_amount'];
$sum = $totalclaimed['claim_amount'] + $claim_amount;
if ($sum <= $limit['limit_amount']){
$sqlinsert = db_query("UPDATE schooling SET claim_amount = '$sum' WHERE employee_id = '$employee_id'");
echo "values updated successfuly";
}
else{
echo "limit is over, you can avail total amount ".$availability." as per ".$limit['limit_amount']." alloted";
}
}
else{
echo "employee schoolig limit is not set";
}
}
?>
<html>
<body>
<form id='applylimit' action='' method='post' accept-charset='UTF-8'>
<fieldset>
<label>Apply Schooling Limit amount to Employee</label>
<label for='employee_id'>Employee Id</label>
<select name='employee_id'>
<option value="0">Please Select</option>
<?php
while($row = $getempnames->fetchAssoc())
{
?>
<option value = "<?php echo($row['field_employee_id_value'])?>">
<?php echo($row['field_employee_id_value']) ?>
</option>
<?php
}
?>
</select>
<label for='limit_amount'>Limit Amount</label>
<input type='number' name='limit_amount' id='limit_amount' maxlength="50" />
<label for='claim_year'>Claim Year</label>
<select type='number' name='claim_year' id='claim_year' maxlength="50">
<option value="2018-19">2018-19</option>
<option value="2019-20">2019-20</option>
</select>
<button type="submit" name="apply">Apply</button>
</fieldset>
</form>
<form id='schoolingentry' action='' method='post' accept-charset='UTF-8'>
<fieldset>
<label for='employee_id'>Employee Id </label>
<select name='employee_id'>
<option value="0">Please Select</option>
<?php
while($rowemp = $get->fetchAssoc())
{
?>
<option value = "<?php echo($row['field_employee_id_value'])?>" >
<?php echo($rowemp['field_employee_id_value']) ?>
</option>
<?php
}
?>
</select>
<label for='claim_amount'>Claim Amount</label>
<input type='number' name='claim_amount' id='claim_amount' maxlength="50" />
<label for='claim_year'>Claim Year</label>
<select name='claim_year' id='claim_year' maxlength="50">
<option value = "2018-19">2018-19</option>
<option value = "2019-20">2019-20</option>
</select>
<button type="submit" name="save">save</button>
</fieldset>
</form>
</body>
</html>
word of warning, do not put anything submitted from a $_POST straight into a database query. You should sanitize it all by passing in the parameters.
e.g.
$result = db_query('SELECT n.name FROM users n WHERE n.name = :name', array(':name' => $name));
If the first query isn't returning any results, it's likely those two parameters you are passing into the string are not what you expect, or not valid. Try echoing out the two variables, then running the SQL query manually.
Or if you want Drupal to be a bit more verbose, wrap it in a exception catcher..
e.g.
catch (\PDOException $e) {
$error = $e->getMessage();

How To Insert Many To Many Tabel Auto Increment

A B C
------- --------- ------------
id_A* id_B* id_C*
name id_A** name
address id_C**
I created a table as in the example above I've tried to do input in Table A, B then C, but what if I want to do the input of C then the input table B in conjunction with Table A, all tables in the auto increment primary key
<input type="text" name="id_A" />
<input type="text" name="id_B" />
<input type="text" name="name" />
<input type="text" name="address" />
<select class="form-control" name="id_C">
<?php
$query = "select * from C";
$r = mysql_query($query);
while ($row=mysql_fetch_array($r)) {
?>
<option value="<?php echo $row['id_C'];?>" name="id_C"><?php echo $row['name'];?></option>
<?php
}
?>
</select>
And Then
isset($_POST['submit'])) {
$id_A = $_POST['id_A'];
$name = $_POST['name'];
$address = $_POST['address'];
$q = "insert into A (id_A,name,address) VALUES('$id_A','$name','$address')";
$dq = mysql_query($q);
$id_B = $_POST['id_B'];
$query = mysql_query("insert into B(id_b,id_A,id_C) values('$id_b', '$id_A' ,'$id_C')");
please help me,
i' am a realy2 confuse

Unable to update database from form retrieved by SELECT OPTION

I couldn't figure out what is the problem with $updateApproval statement. Everything is fine and the $_POST is able to retrieve the data from the form. SQL statement works well on phpMyAdmin when I run it , substituting the variables so there should not be any mistakes.
Am I conflicting without knowing or there are some other reasons that my update statement is not working? Tried switching here and there but it just kept quiet and no slightest error is out. I provide you the information you need and sorry if it is tedious. Any help is greatly appreciated. Thank you.
This is my database:
Consent Table
consent
-----------------------------------------------------------------------------------------
consent_id | staff_id | approval_id | type_of_leave | consent_date_from | consent_date_to
Leave Type Table
leavetype
----------------------------
type_of_leave | leave_type |
Staff Table
staff
------------------------------------------------------------------
staff_id | role_id | staff_name | gender | staff_email | password |
Staff Leave table
staffleave
----------------------------------------------------------------------
leave_log | staff_id | annual_leave | sick_leave .....//other leaves and so on
The form is over here. I have actually put a select option into a form, thus there's the <td> <tr> tag.
<td>
<div class="form-group">
<form action="doApproval.php" method="post" name="register">
<input hidden name="getStaffId" value="<?php echo $staffId ?>" >
<input hidden name="getConsentId" value="<?php echo $consentId ?>" >
<input hidden name="getLeaveId" value="<?php echo $leaveId ?>" >
<div class="form-group">
<select class="form-control" onchange="this.form.submit()" id="select" name="getConsentChange">
<option value="1" <?php if ($getCurrentStatus == 1) echo "selected"; ?>>Approve</option>
<option value="2" <?php if ($getCurrentStatus == 2) echo "selected"; ?>>Reject</option>
<option <?php if ($getCurrentStatus == 3) echo "selected"; ?>>Pending</option>
</select>
</div>
<noscript><input type="submit" value="Submit"></noscript>
</form>
</div>
</td>
The POST will be over here. The query that saves the number of days staff take works well, but not the status of their leave.
$staffId = $_POST['getStaffId'];
$consentId = $_POST['getConsentId'];
$getConsent = $_POST['getConsentChange'];
$getLeaveId = $_POST['getLeaveId'];
$updateApproval = "UPDATE consent SET approval_id = $getConsent WHERE consent.staff_id = '$staffId' AND consent.consent_id = $getConsent"; //Update statement that is not working
$leaveCheckpoint = "SELECT * FROM consent, staffleave, staff WHERE staffleave.staff_id = staff.staff_id
AND staff.staff_id = consent.staff_id AND consent.consent_id = '$consentId'";
$checkpointQuery = (mysqli_query($link, $leaveCheckpoint)) or die("Retrieve checkpoint error " . mysqli_error($link));
if ($checkLeave = mysqli_fetch_array($checkpointQuery)) {
if ($checkLeave['staff_id'] = '$staffId' && $checkLeave['consent_id'] = '$consentId') {
//retrieving the number of leaves staff have took
if ($getLeaveId == 1 && $getConsent == 1) {
$updatedLeave1 = $chkAnnual + $dateDiff;
$recordLeave = "UPDATE staffleave SET annual_leave = '$updatedLeave1' WHERE staff_id = '$staffId'";
} else if ($getLeaveId == 2 && $getConsent == 1) {
$updatedLeave2 = $chkSick + $dateDiff;
$recordLeave = "UPDATE staffleave SET sick_leave = '$updatedLeave2' WHERE staff_id = '$staffId'";
} else if ......// so on when they meet the condition, it works fine and able to insert.
else {
?>
<script type="text/javascript">
alert("No data was updated in the process")
window.location = "manageStaffLeave.php";
</script>
}
<?php
}
$successConsent = mysqli_query($link, $recordLeave) or die("Insert Leave Date Error " . mysqli_error($link));
}
$approvalUpdate = (mysqli_query($link, $updateApproval)) or die("Update error " . mysqli_error($link));
mysqli_close($link);
?>
<!DOCTYPE html>
<body>
if ($approvalUpdate && $successConsent) {
?>
<script type="text/javascript">
window.location = "manageStaffLeave.php";
</script>
<?php
}
?>
</body>
I think you missed out ';'
<input hidden name="getStaffId" value="<?php echo $staffId; ?>" >
<input hidden name="getConsentId" value="<?php echo $consentId; ?>" >
<input hidden name="getLeaveId" value="<?php echo $leaveId; ?>" >
You are making a basic mistake :
$checkLeave['staff_id'] = '$staffId' && $checkLeave['consent_id'] = '$consentId
Here you are affecting the strings '$staffId' to the array $checkLeave['staff_id'] and $consentId to $checkLeave['consent_id']
Remove quote and and an equal for comparison :
$checkLeave['staff_id'] == $staffId && $checkLeave['consent_id'] == $consentId

Database does not get updated, But no error appears. MySQL and PHP

I'm making a website for a friend and basically I have 15 fields that are editable depending on the user type. Basically my code is echoing the row out on to the field, but when when I go to change it and update the database nothing happens. I don't receive any error messages, so i'm thinking it's something to do with my condition statements. My functions work fine, how ever my query doesn't seem to like me.
<?php
//end of function
}
// connect to the database
$server = 'localhost';
$user = 'root';
$pass = '';
$database = 'bubbles';
//Connect to the database
$connection = mysql_connect($server, $user, $pass) or die ("Could not connect to server ... \n" . mysql_error ());
//Select the database name
$select = mysql_select_db($database) or die ("Could not connect to database ... \n" . mysql_error ());
// check if the form has been submitted. If it has, process the form and save it to the database
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
//Get form data to make sure it's valid
$id = $_POST["id"];
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$dueDate = mysql_real_escape_string(htmlspecialchars($_POST['dueDate']));
$numOfPages = mysql_real_escape_string(htmlspecialchars($_POST['numOfPages']));
$numOfCopies = mysql_real_escape_string(htmlspecialchars($_POST['numOfCopies']));
$paperSize = mysql_real_escape_string(htmlspecialchars($_POST['paperSize']));
$paperColor = mysql_real_escape_string(htmlspecialchars($_POST['paperColor']));
$weight = mysql_real_escape_string(htmlspecialchars($_POST['weight']));
$finishing = mysql_real_escape_string(htmlspecialchars($_POST['finishing']));
$paymentMethod = mysql_real_escape_string(htmlspecialchars($_POST['paymentMethod']));
$printColor = mysql_real_escape_string(htmlspecialchars($_POST['printColor']));
$status = mysql_real_escape_string(htmlspecialchars($_POST['status']));
$comment = mysql_real_escape_string(htmlspecialchars($_POST['comment']));
// check that firstname/lastname fields are both filled in
if ($name == '' || $dueDate == '' || $numOfPages == '' || $numOfCopies == '' || $comment == '')
{
// generate error message
$error = 'Please fill in all required fields!';
//error, display form
displayForm($id,
$name,
$dueDate,
$numOfPages,
$numOfCopies,
$paperSize,
$paperColor,
$weight,
$finishing,
$paymentMethod,
$printColor,
$comment,
$status,
$error);
}
else
{
//Insert form data into the database or die if there is an error
print $sql;
$sql = ("UPDATE orders SET `name` = '".$name."',
due_date = '".$dueDate."',
numOfPages = '".$numOfPages."',
numOfCopies = '".$numOfCopies."',
paper_size = '".$paperSize."',
paper_color = '".$paperColor."',
weight = '".$weight."',
finishing = '".$finishing."',
payment_method = '".$paymentMethod."',
color = '".$printColor."',
comments = '".$comment."',
`status` = '".$status."' WHERE id = '".$id."'");
$result = mysql_query($sql) or die (mysql_error());
// once saved, redirect back to the view page
header("Location: http://localhost/Bubbles/view-orders.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
{
// if the form hasn't been submitted, get the data from the db and display the form
// get the 'id' value from the URL (if it exists), making sure that it is valid
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM orders WHERE id = '$id'") or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$id = $row['id'];
$name = $row['name'];
$dueDate = $row['due_date'];
$numOfPages = $row['numOfPages'];
$numOfCopies = $row['numOfCopies'];
$paperSize = $row['paper_size'];
$paperColor = $row['paper_color'];
$weight = $row['weight'];
$finishing = $row['finishing'];
$paymentMethod = $row['payment_method'];
$printColor = $row['color'];
$status = $row['status'];
$comment = $row['comments'];
// show form
displayForm($id,
$name,
$dueDate,
$numOfPages,
$numOfCopies,
$paperSize,
$paperColor,
$weight,
$finishing,
$paymentMethod,
$printColor,
$comment,
$status,
'');
}
else
{
// if no match, display result
echo "No results!";
}
}
else
{
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
echo 'Error!';
}
}
?>
Updated with HTML
<html>
<head>
</head>
<body>
<form action"" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div class="floatLeft">
<p>Name: <br /> <input type="text" name="name" value="<?php echo $name; ?>"/></p>
<p>Due Date (ex: yyyy-mm-dd): <br /> <input type="datetime" name="dueDate" value="<?php echo $dueDate; ?>" /></p>
<p># of Pages <br /> <input type="number" name="numOfPages" value="<?php echo $numOfPages; ?>"/></p>
<p># of Copies <br /> <input type="number" name="numOfCopies" value="<?php echo $numOfCopies; ?>"/></p>
</div>
<div class="floatLeft">
<p>Paper Size<br />
<select name = "paperSize" value="<?php echo $paperSize; ?>">
<option value="8.5 x 11in">8.5 x 11 inches</option>
<option value="8.5 x 14in">8.5 x 14 inches</option>
<option value="11 x 17in">11 x 17 inches</option>
</select>
</p>
<p>Paper Color<br />
<select name = "paperColor" value="<?php echo $paperColor; ?>">
<option value = "pulsar pink">Pulsar Pink</option>
<option value = "fireball fuchsia">Fireball Fuchsia</option>
<option value = "plasma pink">Plasma Pink</option>
<option value = "re-entry red">Re-entry Red</option>
<option value = "rocket red">Rocket Red</option>
<option value = "cosmic orange">Cosmic Orange</option>
<option value = "galaxy gold">Galaxy Gold</option>
<option value = "solar yellow">Solar Yellow</option>
<option value = "venus violet">Venus Violet</option>
<option value = "planetary purple">Planetary Purple</option>
<option value = "celestial blue">Celestial Blue</option>
<option value = "lunar blue">Lunar Blue</option>
<option value = "gamma green">Gamma Green</option>
<option value = "martian green">Martian Green</option>
<option value = "terra green">Terra Green</option>
<option value = "lift-off lemmon">Lift-off Lemon</option>
</select>
</p>
<p>Weight<br/>
<select name = "weight" value="<?php echo $weight; ?>">
<option value="20lbs">20lbs</option>
<option value="60lbs">60lbs</option>
<option value="65lbs">65lbs</option>
</select>
</p>
<p>Finishing<br />
<select name = "finishing" value="<?php echo $finishing; ?>">
<option value="none">None</option>
<option value="cutting">Cutting</option>
<option value="folding">Folding</option>
<option value="quaters">Quaters</option>
<option value="binding">Bindings</option>
</select>
</p>
<p>Payment method<br />
<select name = "paymentMethod" value="<?php echo $paymentMethod; ?>">
<option value="Cash">Cash</option>
<option value="Credit">Credit</option>
<option value="Check">Check</option>
<option value="Wilscard">Wilscard</option>
</select>
</p>
<p>Print BW/C<br />
<select name = "printColor" value="<?php echo $printColor; ?>">
<option value="Black">Black</option>
<option value="White">White</option>
<option value="Color">Color</option>
</select>
</p>
</p>
</div>
<div class="floatLeft">
<p>Status<br />
<select name = "status" value="<?php echo $row['status']; ?>">
<option value="Recieved">Received</option>
<option value="In Progress">In Progress</option>
<option value="Completed">Completed</option>
</select>
<p>Comment (Cannot exceed 200 characters):<br />
<textarea name="comment" value="<?php echo $comment; ?>"></textarea><br />
</p>
<input type="submit" value="Edit Order" />
</div>
</body>
</html>
UPDATE: I fixed the code, thanks everyone for all the help, but my error was that when I check the empty field, there was nothing written in the comment box so it was thinking all fields were empty when in reality they weren't. i updated the field check with this code and it works fine now.
I updated the if statement from this:
if ($name == '' || $dueDate == '' || $numOfPages == '' || $numOfCopies == '' || $comment == '')
To this:
if ($name == '' || $dueDate == '' || $numOfPages == '' || $numOfCopies == '')
It doesn't look like you're running the query after you create it in the $sql variable. You'll want to execute the query like you do later in the code:
$result = mysql_query($sql) or die(mysql_error());
This will return true on success or false (and die) on failure.
If you execute your UPDATE sql statement should give you some ERROR (since you forgot SET). However, you are not executing it. Once you fix that issue, you need to change your UPDATE statement to
$sql = "UPDATE orders
SET
`name` = '".$name."',
due_date = '".$dueDate."',
numOfPages = '".$numOfPages."',
numOfCopies = '".$numOfCopies."',
paper_size = '".$paperSize."',
paper_color = '".$paperColor."',
weight = '".$weight."',
finishing = '".$finishing."',
payment_method = '".$paymentMethod."',
color = '".$printColor."',
comments = '".$comment."',
`status` = '".$status."'
WHERE
id = '".$id."'";
Reference: https://dev.mysql.com/doc/refman/5.0/en/update.html
Note: I escaped name and status columns since their are reserved words
Use this query it may solve your problem:
$sql = "UPDATE orders set name ='".$name."' set due_date = '".$dueDate."' set numOfPages = '".$numOfPages."' set numOfCopies = '".$numOfCopies."' set paper_size = '".$paperSize."' set paper_color = '".$paperColor."' set weight = '".$weight."' set finishing = '".$finishing."' set payment_method = '".$paymentMethod."' set color = '".$printColor."' set comments = '".$comment."' set status = '".$status."' WHERE id = '".$id."' ";

Categories