Updating only the submitted fields from account settings page - php

I have an account settings page which will detect any changed fields and submit those fields via jquery.ajax to a php file, the php file intakes it and validates each field on some different cases and if any of them throw an error it returns the error, exits, and requires user to reinput the field. That all works fine... however...
I'm having my problem with how to build a loop to only update the submitted fields. Currently the php file has this structure:
Check for ajax request {
Validate fields...
Update Fields...
}
My "Update Fields" code looks like this and yes it won't work this way, I know:
// grab all variables except passwords
$email = mysql_real_escape_string($_POST['email']);
$newpass = mysql_real_escape_string(md5($_POST['newpass']));
$bname = mysql_real_escape_string($_POST['bname']);
$bemail = mysql_real_escape_string($_POST['bemail']);
$sql = "UPDATE usertable SET email='$email', password='$newpass', bname='$bname', bemail='$bemail' WHERE username = '$user'";
mysql_query($sql);
$msg = "Account updated successfully.";
header('Cache-Control: no-cache, must-revalidate');
header('Expires: '.date('r', time()+(86400*365)));
header('Content-type: application/json');
echo json_encode(array(
'valid' => yes,
'msg' => $msg,
));
exit();
The line in question is the $sql = "Update usertable..." line. How can I write a php loop to grab all the posted variables as an array and somehow use those to build an update query string... if you need anything else let me know. Asking a lot, but I've been thinking for four hours and can't figure out a way to do it without lots of run around non-direct coding.
Also: Is there a way to return ALL the unvalidated fields? General idea, such as using an array and for each loop or something? Currently if let's say, the email field and password field don't validate, it only shows the email field as needing to be re-entered because it shows up first in the php file. I would prefer it to tell them ALL the fields that didn't validate. I know it just had to do with the position of my code and the way I'm just hand coding each validation (which is the long way) so any insight into this will help me a BILLION especially with future pages on the backend.
Thanks for any help guys!

This will only update the fields which are within the $_POST array and defined in $fieldsToUpdate (So you can exclude fields):
$user = mysql_real_escape_string($user);
$fieldsToUpdate = array('email', 'bname','bemail');
$set = array();
foreach($_POST as $key=>$value){
if(in_array($key,$fieldsToUpdate)){
$set[] = $key."='".mysql_real_escape_string($value)."'";
}
}
if(count($set) > 0){
$query = "UPDATE usertable SET ".implode(',',$set)." WHERE username = '$user'";
// rest of your code;
}
Also, mysql_real_escape_string() is deprecated, think about using PDO

Related

Two if(isset($_POST) arrays in one update query? [duplicate]

This question already has an answer here:
Update query with two post array's
(1 answer)
Closed 7 years ago.
I am trying to bring an id from a hidden form on a previous page and using it as a variable as part of an update query.
The path to this point is....:
Log in to admin area (using a different table)...
Search 'businesses' database for entry...
Entry displays with an update button, the update button has a hidden ID... value that gets posted to this page through "submit"...
if(isset($_POST["submit"]) && isset($_POST["submituname"]))
{
$id = $_POST["id"];
$name = $_POST["uname"];
}
$query = mysqli_query($db, "UPDATE businesses SET username='$name' WHERE id='$id'");
if($query)
{
$msguname = "<p>Your username has now been updated.</p>";
}
Thanks
You need to use isset() on both variables to check them both.
if(isset($_POST['submit']) && isset($_POST["submituname"]))
You're sql query is current open to injection attack, make sure you use PDO or mysqli_real_escape_string().
Few mistakes..
Is that all functions must be inside your IF.. (so they are triggered only when its a post request and etc.
You must set isset to both post params which you are checking
What will you do if id is not set ? In that case I am giving a small easy trick by using filter_input which return NULL on not set param (another thing is escaping but I will leave you small task to learn how to escape vars..)
Last thing is your if($query) .. this is wrong check if you have any success.
Here is a working copy
if(isset($_POST['submit']) && ($_POST["submituname"])) {
$id = filter_input(INPUT_POST, 'id');
$name = filter_input(INPUT_POST, 'name');
$query = mysqli_query($db, "UPDATE businesses SET username='{$name}' WHERE id={$id}");
if(mysqli_affected_rows($db) === 1){
$msguname = "<p>Your username has now been updated.</p>";
}
}

Updating database info from php, not saving

I have this code and it seems to be working. The values are updating, but when I reload the page the updated values are without any value. For example now I have set the title as "blablabla" and when I reload the page it's changing to "".
This is the code
<?php
$title = $_POST['title'];
$meta = $_POST['meta'];
$email = $_POST['email'];
$analytics = $_POST['analytics'];
$query = "UPDATE websettings SET title = '$title', meta = '$meta', email = '$email', analytics = '$analytics' WHERE id = '1'";
if(mysql_query($query)){
echo "success";
}
else {
echo "fail";
}
?>
Your code applies $_POST variables to the database, but doesn't check if the client actually posted anything. Better to check if $_POST contains array items (if a form was posted), and check if each of those is set (if the user filled in the right fields), and validate the user input before saving (phone numbers, emails etc formatted correctly).
And as was pointed out in the comments you are vulnerable to SQL injection attack - one of the first things you should address.
Try turning on more PHP errors too - these would flag as unset variables for quicker fixing.

Can't get php to post to mysql

Hello I cannot get my php to post to mysql. I get no errors when submitting, but entries are not showing up in my database. I appreciate anyone that can give me advice on how I can fix this. I tried to search around here but couldnt find a dirrect reason on why my php code is not working.
<?php
if (isset($_POST['submit'])) {
if (empty($_POST['element_1']) || empty($_POST['element_2'])) {
die("You have forgotten to fill in one of the required fields! Please make sure you submit your name, and paypal e-mail address");
}
$entry = htmlspecialchars(strip_tags($_POST['entry']));
$timestamp = htmlspecialchars(strip_tags($_POST['timestamp']));
$name = htmlspecialchars(strip_tags($_POST['element_2']));
$email = htmlspecialchars(strip_tags($_POST['element_1']));
$comment = htmlspecialchars(strip_tags($_POST['element_3']));
$comment = nl2br($comment);
if (!get_magic_quotes_gpc()) {
$name = addslashes($name);
$url = addslashes($url);
$comment = addslashes($comment);
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
die("The e-mail address you submitted does not appear to be valid. Please go back and correct it.");
}
mysql_connect('host', 'username', 'password') ;
mysql_select_db('database name');
$result = mysql_query("INSERT INTO payments (entry, timestamp, name, email, comment) VALUES ('$entry','$timestamp','$name','$email','$comment')");
header("Location: post.php?id=" . $entry);
}
else {
die("Error: you cannot access this page directly.");
}
?>
Thanks in advanced for your time, understanding, and knowledge. I greatly appreciate it.
advice on how I can fix this
use var_dump($_POST); after if(isset($_POST['submit']))
do $sql="" and var_dump($sql) and mysql_query($sql);
after query var_dump(mysql_insert_id());
and var_dump(mysql_error());
and dont forget: error_reporting(E_ALL); at the top of the file
Then look what happens
[optional] after first query use SHOW COUNT(*) WARNINGS
Things you should check:
I cant see your database design, so you'll have to make sure that your database columns and table match correctly with what is specified in your database.
echo your variables to make sure none are empty.
Ensure that you are not inserting a string in column of type int or vice versa.
Make sure your form method is POST and that your name attributes match what you have specified in your variables ie $_POST['name_attr'].
The order of your insert columns should be the same order as in your table.
Lastly, i hope host,username,password and database name are just placeholders for your real database info? if not, that's the problem.

Edit mysql database from "GET" index.php?id=XX

I'm currently learning PHP. I've code a simple bucketlist script with a admin panel, sessions etc just to see if I can do it.
The last page I am coding is the "edit.php" & "editone.php" I have a table which returns all data within the database "ID, Goal & Rating" my fourth column returns "EDIT" as a link which will link off to: editone.php?id=xx
editone.php currently is not a page. For the life of me I cannot figure out how I code the editone so I can grab the data and UPDATE mysql. I'm almost there just cannot piece together the puzzle.
Here's the core of my code for the edit page.
<?php
while ($query_row = mysql_fetch_array($query))
{
echo "<tr>";
echo "<td>".$query_row['id']."</td><td>". $query_row['goals']."</td><td><span class='label label-inverse'>". $query_row['rating']."</span></td><td><a href='editone.php?id=".$query_row['id']."'>Edit</a></td>";
echo "<tr>";
}
?>
Any assistance would be really appreciated.
Send all the parameters through POST method to editone page. I mean in your edit page, you are getting all the variables from database. You can show them in a form having a submit button and of type "POST". So now when someone submits, it goes to editone.php page.
Get all the variables first through $_POST method. Then write a update query.
$sql = "UPDATE tablename SET goals = '$goal', rating='$rating' WHERE id = $id";
make sure to escape your post variables as said in the comment.
This is how should be your PDO Update statement.
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$goals = 'Some goals';
$rating = 'whatever rating';
$id = 3;
// query
$sql = "UPDATE tablename
SET goals=?, rating=?
WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($goals,$rating,$id));
If I understood you correctly, what you want is a page that first displays a single row (so it can be edited) and then saves it once you're done. So you start out by writing the HTML form with no data in it.
Next, you read the ID from the query string:
<?php
$rowId = $_GET['id'];
and then query for the data:
// database connection example borrowed from Abhishek
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "SELECT goals, rating FROM tablename WHERE id = ?";
$query = $conn->prepare($sql);
$query->execute(array($rowId));
$row = $query->fetch();
Now, you can use the data to populate your form. This gets you about halfway there. :-)
You'll want the actual save to be in response to a POST request, not GET. There's a long and somewhat complicated explanation on why that is, but the simplified version is that you use POST whenever you're making changes for the user, and GET when you're just reading data -- there's a bunch of browser and proxy behavior and whatnot tied to these assumptions, so it's a good idea to start doing things the right way early on.
When you process the POST request -- you can do it on the same page -- you'll have the updated form values for grabs, and you can use them to update your database:
// This can be a hidden field on the form...
$rowId = $_POST['id'];
$goals = $_POST['goals'];
$rating = $_POST['rating'];
// database connection example borrowed from Abhishek
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "UPDATE tablename SET goals = ?, rating = ? WHERE id = ?";
$query = $conn->prepare($sql);
$query->execute(array($goals, $rating, $rowId));
After this, your database should be updated. To finish things off, you'll probably want to redirect back to the page to make sure the form can't be double-submitted accidentally.
I haven't covered quite everything here, a bit on purpose. It's more fun when there are some blanks to fill in. :-)
You probably want your second <tr> to be </tr>.
The most common solution is to use an html form. The input values of this form are a select with the id in query string. When a submit button is pressed to save this, make a update. But I want share with you a good and complete web 2.0 example.

Can you use $_POST in a WHERE clause

There are not really and direct answers on this, so I thought i'd give it a go.
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id = " .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
The above code is supposed to set the variable $myid as the posted content of id, the variable is then used in an SQL WHERE clause to fetch data from a database according to the submitted id. Forgetting the potential SQL injects (I will fix them later) why exactly does this not work?
Okay here is the full code from my test of it:
<?php
//This includes the variables, adjusted within the 'config.php file' and the functions from the 'functions.php' - the config variables are adjusted prior to anything else.
require('configs/config.php');
require('configs/functions.php');
//Check to see if the form has been submited, if it has we continue with the script.
if(isset($_POST['confirmation']) and $_POST['confirmation']=='true')
{
//Slashes are removed, depending on configuration.
if(get_magic_quotes_gpc())
{
$_POST['model'] = stripslashes($_POST['model']);
$_POST['problem'] = stripslashes($_POST['problem']);
$_POST['info'] = stripslashes($_POST['info']);
}
//Create the future ID of the post - obviously this will create and give the id of the post, it is generated in numerical order.
$maxid = mysql_fetch_array(mysql_query('select max(id) as id from repairs'));
$id = intval($maxid['id'])+1;
//Here the variables are protected using PHP and the input fields are also limited, where applicable.
$model = mysql_escape_string(substr($_POST['model'],0,9));
$problem = mysql_escape_string(substr($_POST['problem'],0,255));
$info = mysql_escape_string(substr($_POST['info'],0,6000));
//The post information is submitted into the database, the admin is then forwarded to the page for the new post. Else a warning is displayed and the admin is forwarded back to the new post page.
if(mysql_query("insert into repairs (id, model, problem, info) values ('$_POST[id]', '$_POST[model]', '$_POST[version]', '$_POST[info]')"))
{
?>
<?php
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id=" .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row = mysql_fetch_array($query))
{
$model = $row['model'];
$problem = $row['problem'];
}
//Select the post from the database according to the id.
$query2 = mysql_query('SELECT * FROM devices WHERE version = "'.$model.'" AND issue = "'.$problem.'";') or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query2) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row2 = mysql_fetch_array($query2))
{
$price = $row2['price'];
$device = $row2['device'];
$image = $row2['image'];
}
?>
<?php echo $id; ?>
<?php echo $model; ?>
<?php echo $problem; ?>
<?php echo $price; ?>
<?php echo $device; ?>
<?php echo $image; ?>
<?
}
else
{
echo '<meta http-equiv="refresh" content="2; URL=iphone.php"><div id="confirms" style="text-align:center;">Oops! An error occurred while submitting the post! Try again…</div></br>';
}
}
?>
What data type is id in your table? You maybe need to surround it in single quotes.
$query = msql_query("SELECT * FROM repairs WHERE id = '$myid' AND...")
Edit: Also you do not need to use concatenation with a double-quoted string.
Check the value of $myid and the entire dynamically created SQL string to make sure it contains what you think it contains.
It's likely that your problem arises from the use of empty-string comparisons for columns that probably contain NULL values. Try name IS NULL and so on for all the empty strings.
The only reason $myid would be empty, is if it's not being sent by the browser. Make sure your form action is set to POST. You can verify there are values in $_POST with the following:
print_r($_POST);
And, echo out your query to make sure it's what you expect it to be. Try running it manually via PHPMyAdmin or MySQL Workbench.
Using $something = mysql_real_escape_string($POST['something']);
Does not only prevent SQL-injection, it also prevents syntax errors due to people entering data like:
name = O'Reilly <<-- query will bomb with an error
memo = Chairman said: "welcome"
etc.
So in order to have a valid and working application it really is indispensible.
The argument of "I'll fix it later" has a few logical flaws:
It is slower to fix stuff later, you will spend more time overall because you need to revisit old code.
You will get unneeded bug reports in testing due to the functional errors mentioned above.
I'll do it later thingies tend to never happen.
Security is not optional, it is essential.
What happens if you get fulled off the project and someone else has to take over, (s)he will not know about your outstanding issues.
If you do something, finish it, don't leave al sorts of issues outstanding.
If I were your boss and did a code review on that code, you would be fired on the spot.

Categories