PHP MySQL UPDATE statement - php

I am making a website where after you have logged in and added all your contacts in the database you can also edit them. The way to go is the MYSQL UPDATE statement. I have written the code but sosmething does not seem to work and has been torturing me for hours. Here is the code
<?php
session_start();
$del_id = $_GET["id"];
$_SESSION["id"] = $del_id;
$del_name = $_GET["name"];
$del_phone = $_GET["phone"];
$del_address = $_GET["address"];
$del_email = $_GET["email"];
$name2 = $_POST["name"];
$address2 = $_POST["address"];
$number2 = $_POST["number"];
$email2 = $_POST["email"];
$query = "UPDATE `contacts` SET email = '$email2' AND phone = '$number2' AND address = '$address2' AND name = '$name2' WHERE id = '$del_id'";
$conn = mysqli_connect($servername,$username,$password,$dbname);
if(!$conn){
die("Connection failed: ".mysqli_connect_error());
}else{
echo "Connected successfully";
}
if(mysqli_query($conn,$query)){
echo "Contact edited";
}
?>
<html><head></head>
<body>
<form action="edit.php" method = "POST">
Add text only to the ones you want changed:<br><br>
NAME<input type="text" value="<?php echo $del_name?>" name="name"><br>
ADDRESS<input type="text" value="<?php echo $del_address?>" name="address"><br>
PHONE NUMBER <input type="text" value="<?php echo $del_phone ?>" name="number"><br>
EMAIL <input type="text" value="<?php echo $del_email ?>" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
What could be the problem because the contact in the database is not being updated after that?

Your UPDATE statement is wrong:
"UPDATE `contacts` SET email = '$email2' AND phone = '$number2' AND address = '$address2' AND name = '$name2' WHERE id = '$del_id'"
Try this instead
// Please sanitize the data
$email2 = filter_var( $email2, FILTER_SANITIZE_EMAIL );
$name2 = preg_replace( "#[^a-zA-Z ]#", '', $name2 );
$number2 = preg_replace( "#[^0-9 \-\+]#", '', $number2 );
$address = preg_replace( "[^\w \.\-\+]#", '', $address2 );
"UPDATE `contacts` SET email = '$email2', phone = '$number2', address = '$address2', name = '$name2' WHERE id = '$del_id' LIMIT 1"
Note
I added the limit clause LIMIT 1 to limit the number of rows that will be affected by the update statement. In this case, am setting it to 1 to make sure we're updating a single row. Am sure you would want that also.
* Please, consider using mysqli prepared query or PDO

Replace your $query line.
$query = "UPDATE `contacts`
SET email = '$email2', phone = '$number2', address = '$address2', name = '$name2'
WHERE id = '$del_id'";
AND can be used in WHERE clause.

$query = "UPDATE `users` SET `userpassword` = CONCAT(`userpassword`, 'a') WHERE `user_id` = 1";
READ THE GUIDELINES

Related

form updating fields that haven't been updated by user - PHP Query

I'm in need of some help with my PHP query. I'm essentially giving users the opportunity to update their own details once they have logged in. The form:
<div class="grid-2">
<p><b>UPDATE MY DETAILS</b></p>
<form action ="includes/update.inc.php" method ="post">
<label>S.Name</label>
<input name="update-surname" type="text" placeholder="Enter new surname...">
<label>Address</label>
<input name="update-houseno" type="text" placeholder="Enter house no' or name...">
<input name="update-ln1" type="text" placeholder="1st Line of Address...">
<input name="update-town" type="text" placeholder="Town...">
<input name="update-county" type="text" placeholder="County...">
<input name="update-postcode" type="text" placeholder="Postcode...">
<label>Contact Number</label>
<input name="update-number" type="text" placeholder="Contact Number...">
<label>Email</label>
<input name="update-email" type="text" placeholder="Email...">
<input type="submit" name="update-details" value="Update">
</form>
</div>
My php code which I have currently, if the user doesn't enter anything in the box, it updates the database with a blank input (which I don't want to happen), if there's no input I don't want that field in the table touched.
<?php
// Here we check whether the user got to this page by clicking the proper button.
if (isset($_POST['update-details'])) {
require 'dbh.inc.php';
// We grab all the data which we passed from the signup form so we can use it later.
$surname = $_POST['update-surname'];
$houseno = $_POST['update-houseno'];
$ln1 = $_POST['update-ln1'];
$town = $_POST['update-town'];
$county = $_POST['update-county'];
$postcode = $_POST['update-postcode'];
$email = $_POST['update-email'];
$number = $_POST['update-number'];
// We validate the updated email is correct if email has been updated.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../after-login.php?error=invalidmail=");
exit();
}
$query = "UPDATE `tblMember` SET `fldSName` = '$surname', `fldTelNum` = '$number', `fld1stLnAddress` = '$houseno', `fld2ndLnAddress` = '$ln1', `fld3rdLnAddress` = '$town', `fldCounty` = '$county', `fldPostcode` = '$postcode', `fldEmailAddress` = '$email' WHERE `tblMember`.`fldMemberID` = 1";
$result = $conn->query($query) or die ("error");
}
?>
Once the php form is loaded, the web page disappears and doesn't stay on the current webpage their on either.
So 2 things needed, help with the correct query and help with the page going blank and not staying on the webpage.
Please note that I know this is vulnerable to injection attack I'm just trying to get it physically working before I attempt to get my head around how I do prepared statements.
Thanks!
You need to check if data input field is non-empty/valid.
Steps to avoid blank fields update:
1) Take an empty array
2) Check if every posted variable is valid, if it valid append it to array.
3) Check if the array is not empty.
4) If its not empty, fire SQL.
<?php
// Here we check whether the user got to this page by clicking the proper button.
if (isset($_POST['update-details'])) {
require 'dbh.inc.php';
// We grab all the data which we passed from the signup form so we can use it later.
$ln1 = $_POST['update-surname'];
$houseno = $_POST['update-houseno'];
$ln1 = $_POST['update-ln1'];
$town = $_POST['update-town'];
$county = $_POST['update-county'];
$postcode = $_POST['update-postcode'];
$email = $_POST['update-email'];
$number = $_POST['update-number'];
// We validate the updated email is correct if email has been updated.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../after-login.php?error=invalidmail=");
exit();
}
$update = [];
if (! empty($surname)) {
$update['fldSName'] = "fldSName = '".$surname ."'";
}
if (! empty($number)) {
$update['fldTelNum'] = "fldTelNum='".$number ."'";
}
if (! empty($houseno)) {
$update['fld1stLnAddress'] = "fld1stLnAddress='".$houseno ."'";
}
if (! empty($ln1)) {
$update['fld2ndLnAddress'] = "fld2ndLnAddress='".$ln1 ."'";
}
if (! empty($town)) {
$update['fld3rdLnAddress'] = "fld3rdLnAddress='".$town ."'";
}
if (! empty($county)) {
$update['fldCounty'] = "fldCounty='".$county ."'";
}
if (! empty($postcode)) {
$update['fldPostcode'] = "fldPostcode='".$postcode ."'";
}
if (! empty($email)) {
$update['fldEmailAddress'] = "fldEmailAddress='".$email ."'";
}
if (! empty($update)) {
$query = "UPDATE `tblMember` SET ";
$query .= implode(', ', $update);
$query .= " WHERE `tblMember`.`fldMemberID` = 1";
$result = $conn->query($query) or die ("error");
}
}
?>
NOTE:
fldMemberID seems to be hard-coded.
For first concern you can edit your query as
UPDATE tblMember
SET fldSName = IF('$surname' = '', fldSName, '$surname'),
fldTelNum = IF('$number' = '', fldTelNum, '$number'),
fld1stLnAddress = IF('$houseno' = '', fld1stLnAddress, '$houseno'),
fld2ndLnAddress = IF('$ln1' = '', fld2ndLnAddress, '$ln1'),
fld3rdLnAddress = IF('$town' = '', fld3rdLnAddress, '$town'),
fldCounty = IF('$county' = '', fldCounty, '$county'),
fldPostcode = IF('$postcode' = '', fldPostcode, '$postcode'),
fldEmailAddress = IF('$email' = '', fldEmailAddress, '$email'),
WHERE
`tblMember`.`fldMemberID` = 1
For Second concern you have to remove die() and redirect to after-login.php as
$conn->query($query);
header("Location: ../after-login.php");
<?php
// Here we check whether the user got to this page by clicking the proper button.
if (isset($_POST['update-details'])) {
require 'dbh.inc.php';
// We grab all the data which we passed from the signup form so we can use it later.
$surname = $_POST['update-surname'];
$houseno = $_POST['update-houseno'];
$ln1 = $_POST['update-ln1'];
$town = $_POST['update-town'];
$county = $_POST['update-county'];
$postcode = $_POST['update-postcode'];
$email = $_POST['update-email'];
$number = $_POST['update-number'];
// We validate the updated email is correct if email has been updated.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../after-login.php?error=invalidmail=");
exit();
}
$query = "UPDATE `tblMember` SET ";
(!empty($surname))?: $query .= "`fldSName` = '$surname',";
(!empty($houseno))?: $query .= "`fldTelNum` = '$houseno',";
(!empty($ln1))?: $query .= "`fld1stLnAddress` = '$ln1',";
(!empty($town))?: $query .= "`fld2ndLnAddress` = '$town',";
(!empty($county))?: $query .= "`fld3rdLnAddress` = '$county',";
(!empty($postcode))?: $query .= "`fldCounty` = '$postcode',";
(!empty($email))?: $query .= "`fldPostcode` = '$email',";
(!empty($number))?: $query .= "`fldEmailAddress` = '$number'";
$query .= " WHERE `tblMember`.`fldMemberID` = 1";
$result = $conn->query($query);
header("Location: ../after-login.php"); //make sure of the path
}
Basically you are checking your input values and like that you build your query by concatenating the query blocks.
At the end added the header to redirect you to the page you want.

Get the value from previous page php, sql

I can't get the value of id from update.php and give to it another page which is update2.php
Here is the code of my update.php
<form method = "post" action = "update2.php ?id=".$row['0'].">
<p class = "head">Update Account Basic Info</p>
<p class = "form">
<input type = "text" class = "name" name = "f_name" placeholder = "First Name">
<input type = "text" class = "name" name = "l_name" placeholder = "Last Name">
<br>
<input type = "text" class = "other" name = "email" placeholder = "Email Address">
<br>
<input type = "numeric" class = "other" name = "mob_no" placeholder = "Mobile Number">
<br></br>
<input type = "submit" name = "save" value = "Update Account">
</p>
</form>
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("dbfacebook", $con);
$query = "SELECT id_no, f_name, l_name, email, mob_no FROM tblaccount WHERE id_no = '$_GET[id]'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo "<p class = 'sub'>Current Account Basic Info</p>";
echo "<p class = 'form'>ID Number: ".$row['0']."<br>";
echo "First Name: ".$row['1']."<br>";
echo "Last Name: ".$row['2']."<br>";
echo "Email: ".$row['3']."<br>";
echo "Mobile Number: ".$row['4']."</p>";
}
mysql_close();
?>
Here is my code of update2.php
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("dbfacebook", $con);
echo $_GET['id'];
mysql_query("UPDATE tblaccount SET f_name = '$_POST[f_name]', l_name = '$_POST[l_name]', email = '$_POST[email]', mob_no = '$_POST[mob_no]' WHERE id_no = '$_GET[id]'");
echo "<h1>Account Updated</h1>";
mysql_close($con);
?>
My problem is my $_GET[id] function in update2.php can't get the value of id_no in update.php
You wont get the right result when you use
action = "update2.php ?id=".$row['0']."
because, .$row['0']. is not php.. It is just HTML..
Instead, you will have to use
action = "update2.php?id=<?php echo $row['0']; ?>"
UPDATE
Since you are getting Undefined variable: row error, it means that $row is null.
Thus, Move
$con = mysql_connect("localhost","root","");
mysql_select_db("dbfacebook", $con);
$query = "SELECT id_no, f_name, l_name, email, mob_no FROM tblaccount WHERE id_no = '$_GET[id]'";
$result = mysql_query($query);
to the line before opening the <form>.
ie, Now, the code should be like
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("dbfacebook", $con);
$query = "SELECT id_no, f_name, l_name, email, mob_no FROM tblaccount WHERE id_no = '$_GET[id]'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
<form method = "post" action = "update2.php?id=<?php echo $row['0']; ?>">
}
?>

Cannot add values in Database using PHP

I am currently doing a project in adding values using database but I seem to have a problem. I am sure that my query is correct since I tried adding it manually in mysql. Only some of the fields seem to be able to get what I input. I get the error
"Error: INSERT INTO inventory (itemCode, dateReceived, typeOfFabric, details, unitOfMeasurement, amount, assignedOrderUse, section, row) VALUES ('', '', '', 'White', '', '5', '', 'C', 'C')"
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "gracydb";
if (isset($_POST['addInventory']))
{
if(isset($_POST['itemCode'])){ $itemcode = $_POST['itemCode']; }
if(isset($_POST['dateReceived'])){ $inventoryDateReceived = $_POST['dateReceived']; }
if(isset($_POST['typeOfFabric'])){ $fabric = $_POST['typeOfFabric']; }
if(isset($_POST['details'])){ $details = $_POST['details']; }
if(isset($_POST['unitOfMeasurement'])){ $measurement = $_POST['unitOfMeasurement']; }
if(isset($_POST['amount'])){ $amount = $_POST['amount']; }
if(isset($_POST['assignedOrderUse'])){ $order = $_POST['assignedOrderUse']; }
if(isset($_POST['section'])){ $section = $_POST['section']; }
if(isset($_POST['row'])){ $row = $_POST['row']; }
$conn = mysql_connect($host, $user, $pass);
$db_selected = mysql_select_db($db, $conn);
$sql = "INSERT INTO inventory (itemCode, dateReceived, typeOfFabric, details, unitOfMeasurement, amount, assignedOrderUse, section, row)
VALUES ('$itemcode', '$datereceived', '$fabric', '$details', '$measurement', '$amount', '$order', '$section', '$row')";
if (mysql_query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysql_error($conn);
}
mysql_close($conn);
//header ('Location: .php');
}
?>
<form action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method = "POST">
Item Code: <input type = "text" name = "itemcode"><br>
Date Received: <input type = "date" name = "inventoryDateReceived"><br>
Type of Fabric: <input type = "text" name = "fabric"><br>
Unit of Measurement:
<select name = "measurement">
<option value = "Grams">Grams</option>
<option value = "Kilograms">Kilograms</option>
</select><br>
Amount: <input type = "number" name = "amount"><br>
Assigned Order/Use: <input type = "text" name = "order"><br>
Section: <input type = "text" name = "section"><br>
Row: <input type = "text" name = "row"><br>
<input type = "submit" value = "submit" name = "addInventory">
</form>
These indexes not matched with your input form names:
$_POST['itemCode']
$_POST['dateReceived']
$_POST['typeOfFabric']
These should be:
$_POST['itemcode']
$_POST['inventoryDateReceived']
$_POST['fabric']
Check your form inputs:
<input type = "text" name = "itemcode">
<input type = "date" name = "inventoryDateReceived">
<input type = "text" name = "fabric">
I don't see any sense in this part of the code:
if(isset($_POST['itemCode'])){ $itemcode = $_POST['itemCode']; }
if(isset($_POST['dateReceived'])){ $inventoryDateReceived = $_POST['dateReceived']; }
if(isset($_POST['typeOfFabric'])){ $fabric = $_POST['typeOfFabric']; }
if(isset($_POST['details'])){ $details = $_POST['details']; }
if(isset($_POST['unitOfMeasurement'])){ $measurement = $_POST['unitOfMeasurement']; }
if(isset($_POST['amount'])){ $amount = $_POST['amount']; }
if(isset($_POST['assignedOrderUse'])){ $order = $_POST['assignedOrderUse']; }
if(isset($_POST['section'])){ $section = $_POST['section']; }
if(isset($_POST['row'])){ $row = $_POST['row']; }
Your are just setting values (if isset) to new variables - but if they not exists you will still use undefined variables. Also there is no escaping to prevent sql-injections and validation of the given values!
I think you will get this error because of a missing variable.

Undefined offset from my checkbox form

The following function works fine despite having the "Undefined offset" error but i need to debug it still. Can someone help me spot where the error is?
This is the form :
$query = "SELECT * FROM application WHERE Shortlist_status = 1 AND Interview_datetime != '' AND Email_checked ='' ORDER BY Candidate_id ASC";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
while ($row = mysqli_fetch_array($result)) {
<input type="hidden" name="can_id[]" value=<?php echo $canid ?>>
<input type="hidden" name="job_id[]" value=<?php echo $jobid ?>>
(Some codes)
<input name="email[]" id="id" type="checkbox" value="1">
}
This is the form handling:
foreach ($_POST['can_id'] as $i => $candidate_id) {
$job_id = $_POST['job_id'][$i];
$email = $_POST['email'][$i];
$insertQuery = "UPDATE application SET Email_checked = '$email' WHERE Candidate_id = $candidate_id AND Job_id = $job_id";
$inserted = mysqli_query($link, $insertQuery) or die(mysqli_error($link));
}
if($inserted)
{
$message = 'Application successfully update <br>Manage Candidate';;
}
else
{
$message = 'Application failed <br>Manage Candidate';
}
echo $message;
Based on how you described the error in your comments, I would guess that the problem can be solved like this:
$email = isset($_POST['email'][$i]) ? $_POST['email'][$i] : "otherValue";
Replace "otherValue" with whatever you need if it is not set (probably "0")
$email = isset($request->email[$i]) ? $request->email[$i] : 0;

undefined index id,fname,lastname in php

<html><head>
<title>Add record to my_database/my_table</title></head>
<body>
<?php
$self = $_SERVER['PHP_SELF'];
$id = $_POST['id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
?>
<form action="<?php echo( $self ); ?>" method="post">
ID: <input type="text" name="id" size="3">
First Name: <input type="text" name="fname" size="8">
Last Name: <input type="text" name="lname" size="8"><br>
<input type="submit" value="Submit">
</form>
<?php
if( $id and $fname and $lname)
{
$conn=#mysql_connect( "localhost", "root", "" ) or die( "Err:Conn" );
select the specified database
$rs = #mysql_select_db( "add_record", $conn) or die( "Err:Db" );
create the query
$sql = "insert into my_table ( id, first_name, last_name ) values ( $id, \"$fname\", \"$lname\" )";
execute query
$rs = mysql_query( $sql, $conn );
if( $rs )
{
echo( "Record added:$id $fname $lname" );
}
}
?>
</body></html>
here am getting erro as undefined index id,fname,lastname and when i enter values in this am getting db error
At first when your page load $_POST['id'] value is empty because u ve'nt posted any value in $_POST[];
if(isset($_POST['submit'])){
//all your php code here like below
$self = mysql_real_escape_string($_SERVER['PHP_SELF']);
$id = mysql_real_escape_string($_POST['id']);
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
}
AND
$sql = "insert into my_table ( id, first_name, last_name ) values ( '$id', '$fname', '$lname' )";
By the way what is your db error??
Those POST values will only be set when the form is POSTed. You can use isset()
$id = isset($_POST['id'])? $_POST['id'] : NULL;
Same for others.
This happens because you have no conditions on that PHP code that will prevent it from executing the first time when the form is loaded. They should only execute when the form is submitted. You can wrap that PHP with
if(isset($_POST))
{
// Your existing database code here
}

Categories