Update values in database using php - php

I have displayed the data in a form edit.php and again paas the truk_id in url on update page to update.php the data of the fields but it's not working. Can anyone check this
PHP Code
<?php
$truck_id=$_GET['truck_id'];
print_r($truck_id);
include("assets/database_con.php");
if (isset($_POST['submit']))
{
$truck_id=$_POST['truck_id'];
$truck_number= mysql_real_escape_string(htmlspecialchars($_POST['truck_number']));
$truck_model= mysql_real_escape_string(htmlspecialchars($_POST['truck_model']));
$truck_make= mysql_real_escape_string(htmlspecialchars($_POST['truck_make']));
$truck_type= mysql_real_escape_string(htmlspecialchars($_POST['truck_type']));
$truck_tierweight= mysql_real_escape_string(htmlspecialchars($_POST['truck_tierweight']));
$truck_gvm= mysql_real_escape_string(htmlspecialchars($_POST['truck_gvm']));
$truck_regodate= mysql_real_escape_string(htmlspecialchars($_POST['truck_regodate']));
$truck_inspectaiondate= mysql_real_escape_string(htmlspecialchars($_POST['truck_inspectaiondate']));
$sql1 ="UPDATE add_truck SET truck_number='$truck_number', truck_model='$truck_model', truck_make='$truck_make', truck_type='$truck_type', truck_tierweight='$truck_tierweight', truck_gvm='$truck_gvm', truck_regodate='$truck_regodate', truck_inspectaiondate='$truck_inspectaiondate' where truck_id='$truck_id'";
echo $sql1;
$results=$conn->query($sql);
if($results)
{
print 'Success! record updated';
}else{
print 'no! record updated';
}
}
?>

You are assigning values to fields in single quotes.
The main string is enclosed within single quotes.
Variables inside single quotes are not parsed (value is not calculated).
This is called variable interpolation.
Use double quotes for whole string and single quotes for values.
Corrected SQL:
$sql = "UPDATE add_truck
SET truck_number='$truck_number', truck_model='$truck_model',
truck_make='$truck_make', truck_type='$truck_type',
truck_tierweight='$truck_tierweight',
truck_gvm='$truck_gvm', truck_regodate='$truck_regodate',
truck_inspectaiondate='$truck_inspectaiondate' where truck_id='$truck_id'";

you are using GET for the truck id and POST for all other variables - is this intentional?
$truck_id=$_GET['truck_id'];
should it be
$truck_id=$_POST['truck_id'];
or should all the other variables be from the GET array?

$truck_id=$_GET['truck_id'];
Here is your problem part you can't get values from get method when you submit. So you need to add some hidden field into your form like this
<input type="hidden" name="truck_id" value="<?php echo $_GET['truck_id']; ?>">
Change your code like this
if (isset($_POST['submit']))
{
$truck_id=$_POST['truck_id'];
}
I changed your code please look at this
//Your code starts now
<?php
include("header.php");
include("assets/database_con.php");
$truck_id= $_GET['truck_id'];
//print ($truck_id);
?>
<?php
//submit part in top that is better
if (isset($_POST['submit']))
{
$truck_id=$_POST['truck_id'];
$truck_number= mysql_real_escape_string(htmlspecialchars($_POST['truck_number']));
$truck_model= mysql_real_escape_string(htmlspecialchars($_POST['truck_model']));
$truck_make= mysql_real_escape_string(htmlspecialchars($_POST['truck_make']));
$truck_type= mysql_real_escape_string(htmlspecialchars($_POST['truck_type']));
$truck_tierweight= mysql_real_escape_string(htmlspecialchars($_POST['truck_tierweight']));
$truck_gvm= mysql_real_escape_string(htmlspecialchars($_POST['truck_gvm']));
$truck_regodate= mysql_real_escape_string(htmlspecialchars($_POST['truck_regodate']));
$truck_inspectaiondate= mysql_real_escape_string(htmlspecialchars($_POST['truck_inspectaiondate']));
$sql1 ="UPDATE add_truck SET truck_number='$truck_number', truck_model='$truck_model', truck_make='$truck_make', truck_type='$truck_type', truck_tierweight='$truck_tierweight', truck_gvm='$truck_gvm', truck_regodate='$truck_regodate', truck_inspectaiondate='$truck_inspectaiondate' where truck_id='$truck_id'";
echo $sql1;
die();
$results=$conn->query($sql);
if($results)
{
print 'Success! record updated';
}else{
print 'no! record updated';
}
}
?>
And changed some thing in here(added action="")
<form role="form" method="post" action="">
And changed some thing in here also(added name="submit")
<div class="form-group">
<input type="hidden" name="truck_id" value="<?php echo $_GET['truck_id']; ?>">
<input type="submit" value="submit" name="submit" class="btn_full" id="submit-booking">
</div>
No need for another div for hidden because it is 'hidden'

Used a new code as solution :
<?php
if (isset($_POST['submit']))
{
$truck_id=$_POST['truck_id'];
...
}
and one hidden value with the submit name of attribute :
<input type="hidden" name="truck_id" value="<?php echo $_GET['truck_id']; ?>">
<input type="submit" value="submit" name="submit" class="btn_full" id="submit-booking">

Related

PHP / MySQL: Insert multiple data from checkbox and save it to multiple row in a table

I'm new to PHP Programming and MySQL. Regarding my question, I have 3 checkboxes. I need to select the data and save it to the database. if I choose 2 data, thus need to save the data 1 by 1, which means will insert two row of data. Below is my code example:
index.php
<!DOCTYPE html>
<html>
<body>
<h1>Show Checkboxes</h1>
<form action="save.php" method="POST">
<input type="checkbox" name="club[]" value="Chelsea">
<label for="Chelsea"> Chelsea</label><br>
<input type="checkbox" name="club[]" value="Liverpool">
<label for="Liverpool"> Liverpool</label><br>
<input type="checkbox" name="club[]" value="Arsenal">
<label for="Arsenal"> Arsenal</label><br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
save.php
<?php
include("connect.php");
$club = implode(',',$_POST['club']);
$query = "INSERT INTO bpl_club (club_name) VALUES ('$club')";
$sql = $conn->prepare($query);
$sql->execute();
if($sql){
echo "<script>alert('Record inserted successfully!')</script>";
echo "<script>window.location = 'index.php'</script>";
}else{
echo "<script>alert('Something went wrong. Please try again!')</script>";
}
?>
Can anyone know how to fix it? Thank you so much..
Use foreach function to print your check box one one by from $_POST['club'] array
$ClubArray=array();
$ClubArray=$_POST['club'];
foreach($ClubArray as $ClubName)
{
//your Insert code here with the insert query ie INSERT INTO bpl_club (club_name) VALUES ('$ClubName')
}

Multiple forms and multiple submissions with one submit button

At the moment, I'm using a loop to read the 'questions' and 'answers' fields from my postgresql "PDPC".considerations table and reflecting them on the form. I'd like to update them all with one submit button.
I refered to PHP MySQL Multiple Forms and Multiple Submits on single page and tried using the <input type="hidden">, arrays and while loop but the form either does not execute or it does not correctly update all the forms.
I think the error is around the $_POST (at the top) and the HTML form (at the bottom). (Sorry if the codes are messy, it is my first time with PHP, HTML and Postgres). Thank you!
<?php
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$question = $answer = "";
$question_err = $answer_err = "";
// Processing form data when form is submitted
if(isset($_POST["consideration_no"]) && !empty($_POST["consideration_no"])){
$counter = 0;
// Get hidden input value
//$consideration_no = $_POST['consideration_no'];
$dg_no = $_POST['dg_no'];
$consideration_no = $_POST['consideration_no'];
$answer = $_POST['answer'];
// Check input errors before inserting in database
if(empty($answer_err)){
while ($counter<5){
// Validate address address
$input_answer = trim($_POST["answer"]);
if(empty($input_answer)){
$answer_err = "Please enter an answer.";
} else{
$answer1[$counter] = $input_answer;
}
// Prepare an update statement
$sql = 'UPDATE "PDPC".consideration SET answer=:answer WHERE consideration_no = :consideration_no';
if($stmt = $pdo->prepare($sql)){
$stmt->bindParam(":answer", $param_answer);
$stmt->bindParam(":consideration_no", $param_consideration_no);
//Set Parameter
$param_answer = $answer1[$counter];
$param_consideration_no = $consideration_no[$counter];
// Attempt to execute the prepared statement
$stmt->execute();
$counter++;
}
}
if($stmt->execute()){
// Records updated successfully. Redirect to landing page
header("location: home1.php?dm_no=".$_GET["dm_no"]);
exit();
} else{
echo "Something went wrong. Please try again later.";
}
// Close statement
unset($stmt);
}
// Close connection
unset($pdo);
} else{
// Check existence of dg_no parameter before processing further
if(isset($_GET["dg_no"]) && !empty(trim($_GET["dg_no"]))){
// Get URL parameter
$dg_no = trim($_GET["dg_no"]);
// Prepare a select statement
$sql = 'SELECT * FROM "PDPC".consideration WHERE (dg_fkey = :dg_no AND code_no = 1)';
if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":dg_no", $param_no);
// Set parameters
//$param_no = $dg_no;
$param_no = trim($_GET["dg_no"]);
// Attempt to execute the prepared statement
if($stmt->execute()){
if($stmt->rowCount() > 0){
SubSection($subsection1_1); //Collection Purpose Section
while($row = $stmt->fetch()){
// Retrieve individual field value
$consideration_no = $row["consideration_no"];
$question = $row["question"];
$answer = $row["answer"];
echo "<a href='considerationupdate.php?consideration_no=". $row['consideration_no'] ."' title='Update Data Map' data-toggle='tooltip'><span class='glyphicon glyphicon-pencil'></span></a>";
//...time to show the questions and answers with the while loop...
?>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group <?php echo (!empty($answer_err)) ? 'has-error' : ''; ?>">
<label><?php echo $question; ?></label>
<input type="text" name="answer" class="form-control" value="<?php echo $answer; ?>">
<span class="help-block"><?php echo $answer_err;?></span>
<input type="hidden" name="answer1[]" id = "$answer1" value="<?php echo $answer; ?>"/>
<input type="hidden" name="consideration_no[]" id = "consideration_no" value="<?php echo $consideration_no; ?>"/>
<input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
<?php
}
?>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
<?php
}
}
else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
unset($stmt);
// Close connection
unset($pdo);
}
else{
// URL doesn't contain dg_no parameter. Redirect to error page
header("location: error.php");
exit();
}
}
?>
It should read the questions and answers from the DB table, show it on the forms as the label and text fields (working), and the user should be able to update the form after editing the text fields and clicking submit (Not working properly).
Since is your form and you are using SQL to get and the objective is to update the data with one submit?
Why not just use one form?. I belive you can do all you need with just one and multiple input.
Your branch if(isset($_GET["dg_no"]) && !empty(trim($_GET["dg_no"]))){ depends on get parameters, however, your <form method="post"> of <input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/> uses post parameters.
Therefore the branch will never be executed unless the page is requested by another GET-request like a link or another form.
If the parameters can occur in both methods, POST and GET as well, you might want to check the $_REQUEST array instead. Be aware that the parameters listed in $_REQUEST can vary depending on the .ini settings request_order and variables_order.
According to your comment 'Because each form is for one table row.' in another answer, this might be an XY problem.
Consider to take the common way not generating multiple forms but array parameters similar as you did in
<input type="hidden" name="answer1[]" id = "$answer1" value="<?php echo $answer; ?>"/>
Here you rely on keys getting generated automatically. As well you can specify an individual key:
<input type="text" name="some_parameter[<?php echo $answer; ?>]">
Further more
There is an HTML line in the loop having a static id on an element:
<input type="hidden" name="consideration_no[]" id="consideration_no" value="<?php echo $consideration_no; ?>"/>
This will not break PHP, however, it is against the HTML specs saying an id has to be unique per document.
I have fixed the issue! It was the logical flow of the script. Specifically, the POST variable at the top should be changed to dg_no, add the dg_no parameters along with it, loop the parameters instead of the entire preparation script and include the execute script in the whie loop too.
Thanks for the help and guidance, they were much appreciated!

Session variable not working

I am using one session variable in my php page. As per my infomation, it is accessible throughout the program and it is, but problem is that it is showing different value for the same variable at different place in php page?
the code is as follows
<html><body>
<?php session_start();
if(!isset($_SESSION['x']))
$_SESSION['x']=1;
echo "X=". $_SESSION['x'];
?>
<form>
<input type="submit" name="save" value="save" />
</form>
<?php
if (isset($_GET['save']))
{
if(isset($_SESSION['x']))
$_SESSION['x'] = $_SESSION['x']+1;
echo $_SESSION['x']."<br>";
}
else
echo "no submit";
?>
</body></html>
value becomes different before and after submit button click? Please tell me why it is so?
thanks in advavnce.
You are redeclaring the value of session variable 'x' here
$_SESSION['x'] = $_SESSION['x']+1;
This is why its appearing 1 greater than its initial value.
it is due to the code itself
if(isset($_SESSION['x'])) //It is set
$_SESSION['x'] = $_SESSION['x']+1; //Add 1 to the value
echo $_SESSION['x']."<br>"; return value with +1
Solution
The reason the output is different is the order you echo and update
//Echo
//Update Value
//Echo again
Simple solution would be to move this
if (isset($_GET['save']))
{
if(isset($_SESSION['x']))
$_SESSION['x'] = $_SESSION['x']+1;
echo $_SESSION['x']."<br>";
}
else
echo "no submit";
to above this
if(!isset($_SESSION['x']))
$_SESSION['x']=1;
echo "X=". $_SESSION['x'];
Also note set the method and the action in the form to make sure it calls itself
<form method="GET" action="[url to itself]">
<input type="submit" name="save" value="save" />
</form>
Do it like this :
<html><body>
<?php session_start();
if(!isset($_SESSION['x']))
$_SESSION['x']=1;
echo "X=". $_SESSION['x'];
?>
<form method="GET" action="">
<input type="submit" name="save" value="save" />
</form>
<?php
if (isset($_GET['save']))
{
if(isset($_SESSION['x']))
echo $_SESSION['x']."<br>";
}
else
echo "no submit";
?>
</body></html>
this way the code prints out the same value after submit as it did before.
Either way you try if you print value and change after or change value and print after, when page reloads it will change value. you could add another button called increment and add the following code inside the php :
if (isset($_GET['inc']))
{
if(isset($_SESSION['x']))
$_SESSION['x'] = $_SESSION['x']+1;
}
and this one inside the form:
<input type="submit" name="inc" value="inc" />
this way youre variable increment when you press the inc button

PHP get selected value from select box?

This is my code for get database data to select box and i wanna get the seleceted value.I tries many ways but im missing something. help me
<form id="search" action="" method="post" >
<select name="owner" id="owner">
<?php
$sql = mysql_query("SELECT designation FROM designation");
while ($row = mysql_fetch_array($sql)){
echo '<option value="'.$row['designation'].'">'.$row['designation'].'</option>';
}
?>
</select>
<input type="submit" value="Search">
</form>
As you didn't specify an action for your form, the default will be to send the post values to the same page.
See this for more information about action value.
So, in the same page you have the form, you should add a
if(isset($_POST['owner']))
{
// Do some stuff
}
else
{
// Print the form
}
First make sure to include the action. Secondly to get a POST request of a select tag all you have to do is the following:
$_POST["owner"];
$_POST['owner'] contains the value of select box once you submit the form.And $_POST contains all the value of input elements you submitted via the form.if you print_r($_POST); it will show you all the values submitted through the form.
If you
echo $_POST['owner'];//Will display the value of your selected value in the select box.
<form id="search" action="" method="post" >
<select name="owner" id="owner">
<?php
$owner="rejayi"
$sql = mysql_query("SELECT designation FROM designation");
while ($row = mysql_fetch_array($sql)){
if($row['designation'] == $owner){
echo '<option value="'.$row['designation'].'" selected="selected">'.$row['designation'].'</option>';
}else{
echo '<option value="'.$row['designation'].'">'.$row['designation'].'</option>';
}
}
?>
</select>
<input type="submit" value="Search">
</form>
Put Double quotes (") outside and single quotes (') inside
eg:
echo "<option value='".$row['designation']."'>".$row['designation']."</option>";

Update checkbox data in SQL-database with PHP

As the title reveals I got an issue with how to update a checkbox that already has data in my SQL database.
My code looks like following:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Name <input type"text" name="inputName" value="<?php echo $hemsida['Namn']; ?>" /> </br>
Commentar <input type"text" name="inputComment" value="<?php echo $hemsida['Comment']; ?>" />
<br/>
</br><input type="checkbox" name="inputAll" value="checked" <?php echo $hemsida['All']; ?>/>Alla
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>" />
<input type="submit" name="submit" value="Redigera">
<?php
if(isset($_POST['submit'])) {
$u = "UPDATE hemsida SET `Namn`='$_POST[inputName]', `Comment`='$_POST[inputComment]', `ALL`='$_POST[inputALL]' WHERE ID = $_POST[id]";
mysql_query($u) or die(mysql_error());
echo "User has been modified";
header("Location: ..//sokh.php");
}
?>
The echo $hemsida['Namn'],['Comment'], and ['All'] just brings up and shows the old data thats in the database, but I do not understand what to do to update the checkbox. I have looked everywhere but I am stuck. Thank you in advance!
If I understand your question correctly, you are looking for a way to have a checkbox be either checked or not checked depending on database info. If so, I would try something like this. At the top of your code where you get your database info, put
if($conditionForCheck){
$inputAll = ' checked="checked"';
}
Then in your form
<input type="checkbox" name="inputAll"<?php echo $inputAll; ?> />
your question is not clear but i think you have a column in your database named "all" ? and perhaps this column can take only 1 value (true or false) !!
then you can test this value in your form, if the value is true : checkbox will be checked, else : checkbox will not be checked :
<input type="checkbox" name="inputAll" checked="<?php if($hemsida['All'] == true) echo checked; ?>" />Alla
dont use value="", use checked instead, then test value of $hemsida['All'] if it's true echo checked else anything to do
for your php code and server side of your application you can just test if checkbox is checked and then you have choice for what do you want to assign to your column in database, for example if checkbox is checked create a variable (for example $value_of_checkbox) and assign a value ("true" for exampel) to this variable, then include this variable in your sql code for update database column :
if (isset($_POST['inputALL'])) {
$value_of_checkbox = true;
}
else {
$value_of_checkbox = false;
}
if(isset($_POST['submit'])) {
$u = "UPDATE hemsida SET `Namn`='$_POST[inputName]', `Comment`='$_POST[inputComment]', `ALL`='$value_of_checkbox' WHERE ID = $_POST[id]";
mysql_query($u) or die(mysql_error());
echo "User has been modified";
header("Location: ..//sokh.php")
note : i change also sql code in this part : ALL='$value_of_checkbox'

Categories