Update mysql database and skip empty fields - php

I have two pages, edit.php and editdone.php.
On the edit.php I am able to fill information, which is being sent to editdone.php. That page is then running a query that updates data in the mysql database.
The problem is; if I leave an input field on edit.php empty, editdone.php will then replace the current information in the database with empty data(nothing).
What I want to do is to make the editdone.php update data if something was written in the fields of edit.php. So if I choose to leave some fields empty and for example only fill one field in the form, I want to only update the filled fields with the filled data and NOT replace the not filled field with empty data. Those field should then, if I haven't filled any data in edit.php, keep the already existing data.
edit.php
<?php
if (!empty($error_msg)) {
echo $error_msg;
}
$cn = $_POST['cname'];
?>
<form action="editdone.php" method="POST" enctype="multipart/form-data" name="editdone" onsubmit="return validateForm()">
<input type="hidden" name="namec" value="<?php echo htmlspecialchars($cn); ?>">
<br>
Fyll i Företagets namn: <br>
<input type="text" name="company_name" id="company_name">
<br><br>
Lägg till en logga:
<input type="file" name="image" id="image">
<br><br>
Description:<br>
<textarea name="description" id="description" rows="4" cols="50"></textarea>
<br>
<br>
Fyll i välkomnings meddelande:<br>
<textarea name="welcome_text" id="welcome_text" rows="5" cols="50"></textarea>
<br>
<br>
Fyll i ett tack meddelande:<br>
<textarea name="thanks_message" id="thanks_message" rows="5" cols="50"></textarea>
<br>
<br>
<input type="submit" name="submit" value="Nästa" />
</form>
editdone.php
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if(mysqli_connect_errno())
{
echo mysqli_connect_error();
}
$namenamec = $_POST['namec'];
$company_name = $_POST['company_name'];
$description = $_POST['description'];
$welcome_text = $_POST['welcome_text'];
$thanks_message = $_POST['thanks_message'];
$image = addslashes (file_get_contents($_FILES['image']['tmp_name']));
$logo = getimagesize($_FILES['image']['tmp_name']);
$image_type = $logo['mime'];
$q = "UPDATE project SET project_name='$company_name', description='$description', image='$image', image_type='$image_type', welcome_text='$welcome_text', thanks_message='$thanks_message' WHERE project_name='$namenamec' ";
$r = mysqli_query($mysqli,$q);
if($r)
{
echo "<br>Information stored successfully";
}
?>

For every input/textarea in edit.php, insert a <input type="hidden" value="company_name_old> etc... with the previous value. Then in editdone.php, check if the value in POST is empty or not.
<?php
$company_name = $_POST['company_name'];
if($company_name==""){
$company_name=$_POST['company_name_old'];
}
...
?>

1 cheap "hack" is to assign the current value of the field to the value of the input field and then concat the two strings or values together then save that var. to the database.

<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if(mysqli_connect_errno())
{
echo mysqli_connect_error();
}
$company_name = "";
$description = "";
$welcome_text = "";
$thanks_message = "";
$image = "";
$logo = "";
$image_type = "";
$namenamec = $_POST['namec'];
$company_name = $_POST['company_name'];
$description = $_POST['description'];
$welcome_text = $_POST['welcome_text'];
$thanks_message = $_POST['thanks_message'];
if( isset($_FILES) )
{
if( !empty($_FILES) )
{
if( isset($_FILES['image']['tmp_name']) )
{
if( $_FILES['image']['tmp_name'] != "" && !empty($_FILES['image']['tmp_name']) )
{
$image = addslashes (file_get_contents($_FILES['image']['tmp_name']));
if( $image != "" && !empty($image) )
{
$logo = getimagesize($_FILES['image']['tmp_name']);
$image_type = $logo['mime'];
}
}
}
}
}
$update_values = array();
if($company_name != "")
$update_values[] = "project_name='".$company_name."'";
if($description != "")
$update_values[] = "description='".$description."'";
if($image != "")
$update_values[] = "image='".$image."'";
if($image_type != "")
$update_values[] = "image_type='".$image_type."'";
if($welcome_text != "")
$update_values[] = "welcome_text='".$welcome_text."'";
if($thanks_message != "")
$update_values[] = "thanks_message='".$thanks_message."'";
$update_values_imploded = implode(', ', $update_values);
if( !empty($update_values) )
{
$q = "UPDATE project SET $update_values_imploded WHERE project_name='$namenamec' ";
$r = mysqli_query($mysqli,$q);
if($r)
{
echo "<br>Information stored successfully";
}
}
?>

Try replacing your query like this.
$q = "UPDATE project SET ";
$q .= $company_name ? "project_name='$company_name', " : "";
$q .= $description ? "description='$description', " : "";
$q .= $image ? "image='$image'," : "";
... so on(all fields)
$q .= "WHERE project_name='$namenamec'";
Make sure you remove , for last value

you can do like this here i have made only one variable you can check for each posted variable and append the $q variable as on
$q = "UPDATE project SET";
if(isset($_POST['namec']) && $_POST['namec']!=""){
$q.=" project_name='".$_POST['namec']."' ,";
}
$q=rtrim(',',$q);
$q.="WHERE project_name=".$namenamec;

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.

Can't update form data

I am trying to edit form data by displaying the previous saved data on the form and then update it. It shows the data on the form which is saved in database but when i enter the new data it does not get the id of the row. I echo the update query, it shows the changed values but it shows id equals to empty. Here is my code for edit record and update; Edit record is working but update isn't:
<?php
include('connection.php');
$id = '';
if( isset( $_GET['id'])) {
$id = $_GET['id'];
}
$udfname = mysql_real_escape_string($_POST["udfname"]);
$udlname = mysql_real_escape_string($_POST["udlname"]);
$udpwd = mysql_real_escape_string($_POST["udpwd"]);
$udeml = mysql_real_escape_string($_POST["udeml"]);
$udnum = mysql_real_escape_string($_POST["udnum"]);
$query="UPDATE form
SET fname = '$udfname', lname = '$udlname', pwd = '$udpwd', eml = '$udeml', num = '$udnum'
WHERE id='$id'";
$res= mysql_query($query);
if($res){
echo "<p> Record Updated<p>";
}else{
echo "Problem updating record. MY SQL Error: " . mysql_error();
}
?>
Form for editing record:
<?php
include('connection.php');
$id = (int)$_GET['id'];
$query = mysql_query("SELECT * FROM form WHERE id = '$id'") or die(mysql_error());
while($row = mysql_fetch_array($query)) {
echo "";
$fname = $row['fname'];
$lname = $row['lname'];
$pwd = $row['pwd'];
$eml = $row['eml'];
$num = $row['num'];
}
?>
<html>
<head>
<title>Edit</title>
<script>
'
'
Jquery code here
'
'
</script>
</head>
<body>
<form action="update.php" method="post">
<input type="hidden" name="ID" value="<?=$id;?>">
First Name: <input type="text" name="udfname" value="<?=$fname;?>"><br>
Last Name: <input type="text" name="udlname" value="<?=$lname?>"><br>
Password: <input type="text" name="udpwd" value="<?=$pwd?>"><br>
Email: <input type="text" name="udeml" value="<?=$eml?>"><br>
Contact Number: <input type="text" name="udnum" value="<?=$num?>"><br>
<input type="Submit">
</form>
</body>
</html>
At update time your form is submitted using POST request. So you need to get ID using POST method. So to get ID of hidden field change your code as below:
$id = '';
if( isset( $_POST['ID'])) {
$id = $_POST['ID'];
}
Please try below code
if( isset( $_POST['id']) && $_POST['id']!=null) {
$id = $_POST['id'];
}
Dear i think the problem with your method you are sending the data using post method and its very simple instead of this code
if( isset( $_GET['id'])) {
$id = $_GET['id'];
}
write
if( isset( $_POST['id'])) {
$id = $_POST['id'];
}
and one more thing that is you are using the mysql deprecated function for database kindly use the pdo for this or new mysqli functions.

How to make form values remain in form

I'm developing a simple PHP website. I have a form for updating values. When that form is accessed via PHP(website) , It should have previous values, But it hasn't. How to do that ?
Because, Otherwise, It shows all fields empty and when one or two are updated, Other gets updated as empty. Please help !
<?php
require_once('../includes/config.php');
require_once('../includes/functions.php');
require_once('../includes/session.php');
require_once('../includes/database.php');
require_once('../includes/user.php');
require_once('../includes/photograph.php');
if (!$session->is_logged_in()) { redirect_to("login.php"); }
?>
<?php
// START FORM PROCESSING
if (isset($_POST['submit'])) { // Form has been submitted.
$errors = array();
// perform validations on the form data
$required_fields = array('lives_in', 'belongs_to', 'college', 'works_at', 'grade', 'grade2', 'hobbies', 'zodiac', 'phone_no', 'facebook', 'company', 'bio');
$errors = array_merge($errors, check_required_fields($required_fields, $_POST));
$lives_in = trim($database->escape_value($_POST['lives_in']));
$belongs_to = trim($database->escape_value($_POST['belongs_to']));
$college = trim($database->escape_value($_POST['college']));
$works_at = trim($database->escape_value($_POST['works_at']));
$grade = trim($database->escape_value($_POST['grade']));
$grade2 = trim($database->escape_value($_POST['grade2']));
$hobbies = trim($database->escape_value($_POST['hobbies']));
$zodiac = trim($database->escape_value($_POST['zodiac']));
$phone_no = trim($database->escape_value($_POST['phone_no']));
$facebook = trim($database->escape_value($_POST['facebook']));
$company = trim($database->escape_value($_POST['company']));
$bio = trim($database->escape_value($_POST['bio']));
if (empty($errors) ) {
$query = "UPDATE users
SET lives_in = '{$lives_in}',
belongs_to = '{$belongs_to}',
college = '{$college}' ,
works_at = '{$works_at}',
grade = '{$grade}',
grade2 = '{$grade2}',
hobbies = '{$hobbies}',
zodiac = '{$zodiac}',
phone_no = '{$phone_no}',
facebook = '{$facebook}',
company = '{$company}',
bio = '{$bio}'
WHERE id = 23
LIMIT 1";
$result = mysql_query($query, $database->connection);
if ($result) {
$message = "Account Updated";
} else {
$message = mysql_error();
}
} else {
if (count($errors) == 1) {
$message = mysql_error();;
} else {
$message = "There were " . count($errors) . " errors in the form.";
}
}
} else { // Form has not been submitted.
$lives_in = "";
$belongs_to = "";
$college = "";
$works_at = "";
$grade = "";
$grade2 = "";
$hobbies = "";
$zodiac = "";
$phone_no = "";
$facebook = "";
$company = "";
$bio = "";
}
?>
It's very easy, just print out the previous values in the form when you create it with php.
For example:
<input type="text" name="field_name" value="<?php echo $previous_value;?>" />
Or, if it's a select, let's say:
<select name="field_name">
<?php foreach($posible_values as $value){ ?>
<option value="<?php echo $value;?>"
<?php echo ($value==$previous_value)?'selected="selected"':'';?> >
<?echo $value?>
</option>
<?php } ?>
</select>

$_POST array empty php update fails

I am trying to build admin side of small website which consists of 2 pages: index.php and update php. On index.php I run query, that per-fills html form with data from database, which works fine.
Then I send data via $_POST to update.php page, where I try to get those values into variables and then make an update query. Which fails. I suspect something is wrong with $_POST array - some values are messed up or empty, but I don't understand why.
Here is the code for index.php:
<?php
if (!isset($page_id)) {
echo " <p>Please select page to be edited:</p>";
$query = mysql_query("SELECT page_id, title FROM pages");
$res = mysql_fetch_array($query);
do {
printf("<p><a href='index.php?page_id=%s'>%s</a></p>", $res['page_id'], $res['title']);
} while ($res = mysql_fetch_array($query));
} else { $query = mysql_query("SELECT * FROM pages WHERE page_id = '$page_id'");
$res = mysql_fetch_array($query);
require_once 'parts/form.php';}
?>
This is code for update.php:
<?php
//Here I try to get POST values and assign them to variables for update
//Ths is validation that those values are not empty,
require_once 'parts/guard.php';
if (isset($_POST['page_id'])) {
$page_id = $_POST['page_id'];
}
if (isset($_POST['title'])) {
$title = $_POST['title'];
}
if ($title == '') {
unset($title);
}
if (isset($_POST['description'])) {
$description = $_POST['description'];
}
if ($description == '') {
unset($description);
}
if (isset($_POST['keywords'])) {
$keywords = $_POST['keywords'];
}
if ($keywords == '') {
unset($keywords);
}
if (isset($_POST['text'])) {
$text = $_POST['text'];
}
if ($text == '') {
unset($text);
}
//variables are set
require_once 'parts/meta.php';
?>
<?php
//Here is all the values exist, the query is executed.
//Obviousely this query works in phpmyadmin, but not here - some fields come empty or messed up????
if (isset($title) && isset($keywords) && isset($description) && isset($text) && isset($page_id)) {
$query = mysql_query("UPDATE pages SET title = '$title', description = '$description', keywords = '$keywords', text = '$text' WHERE page_id = '$page_id' ");
if ($query == TRUE) {
echo "<p>Page Updated</p>";
echo "<p><a href = 'http://localhost:8888/travel.ru/admin/index.php'>
Edit Another Page</a></p>";
} else {
echo "<p>Page Is Not Updataed</p>";
}
} else {
echo "<p>You Left Some Fields Empty. Page Will Not Be Updated.</p>";
}
?>
And this is the form I use:
<form name="update" action = "update.php" method= "post">
<p> Page Name<br>
<input value = "<?php echo $res['title']; ?>" type = "text" name = "title"></p>
<p> Page Description<br>
<input value = "<?php echo $res['description']; ?>" type = "text" name = "title"></p>
<p> Page Keywords<br>
<input value = "<?php echo $res['keywords']; ?>" type = "text" name = "title"></p>
<p> Page Content<br>
<textarea type = "text" name ="text" cols = "68" rows = "15"><?php echo $res['text']; ?>
</textarea></p>
<input type = "hidden" name="page_id" value =$res[page_id]>
<p><input type = "submit" name ="submit" value ="Save Changes" id="submit"</p>
</form>
Any help will be most appreciated as I dont have a clue why I have this problem?
Most of your form fields are named title. Thus you don't actually have a field called description or page_id or keywords.
Mate also raises a valid point.
Try added php tag to your input value
<input type = "hidden" name="page_id" value ="<?php echo $res['page_id']; ?>" />
As mentioned Amadan , also check the names for all controls in your form.

SQL insert into table not working

I'm trying to insert status update into my database in table called blabbing, but it's not working.
my php code
$thisRandNum = rand(9999999999999,999999999999999999);
$_SESSION['wipit'] = base64_encode($thisRandNum); // Will always overwrite itself each time this script runs
// ------- POST NEW BLAB TO DATABASE ---------
$blab_outout_msg = "";
if (isset($_POST['status']) && $_POST['status'] != "" && $_POST['status'] != " "){
$blabWipit = $_POST['blabWipit'];
$sessWipit = base64_decode($_SESSION['wipit']);
if (!isset($_SESSION['wipit'])) {
} else if ($blabWipit == $sessWipit) {
// End Delete any blabs over 20 for this member
$status = $_POST['status'];
$status = stripslashes($status);
$status = strip_tags($status);
$status = mysql_real_escape_string($status);
$status = str_replace("'", "'", $status);
$sql = mysql_query("INSERT INTO blabbing (mem_id, profile_id, the_blab, blab_date) VALUES('$logOptions_id','$logOptions_id','$status', now())");
$blab_outout_msg = "";
}
}
my html code
<div style="background-color:#f2f2f2; border:#ebebeb 1px solid; padding:8px;">
<form action="home.php" method="post" enctype="multipart/form-data" name="blab_from">
<textarea name="status" id="status" rows="3" style="width:99%;"></textarea>
<input name="submit" type="submit" class="btn" value="Blab" /> Limit: <script>displaylimit("","status",255)</script>
<input name="blabWipit" type="hidden" value="<? print $thisRandNum;?>" />
</form>
</div>
any help appreciated
$thisRandNum = rand(9999999999999,999999999999999999);
$_SESSION['wipit'] = base64_encode($thisRandNum); // Will always overwrite itself each time this script runs
// ------- POST NEW BLAB TO DATABASE ---------
$blab_outout_msg = "";
if (isset($_POST['status']) && $_POST['status'] != "" && $_POST['status'] != " "){
$blabWipit = $_POST['blabWipit'];
$sessWipit = base64_decode($_SESSION['wipit']);
// if (!isset($_SESSION['wipit'])) {
//} else if ($blabWipit == $sessWipit) {
// End Delete any blabs over 20 for this member
$status = $_POST['status'];
$status = stripslashes($status);
$status = strip_tags($status);
$status = mysql_real_escape_string($status);
$status = str_replace("'", "'", $status);
$sql = mysql_query("INSERT INTO blabbing (mem_id, profile_id, the_blab, blab_date) VALUES('$logOptions_id','$logOptions_id','$status', now())");
$blab_outout_msg = "";
// }
}
Try this if it works then else if ($blabWipit == $sessWipit) { this condition is not true

Categories