Updating database info from php, not saving - php

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.

Related

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.

php and mysql code

I have checked and rechecked my code for a tutorial that I am doing, and I still cannot figure out what is wrong with it. A bit of help would be appreciated.
I am building a page that processes the form data from another page. The part of the markup that I am having trouble with is below.
<pre>
if (isset($_POST['submit'])) {
// Process the form
$subject_id = $_GET["subject"];
$pageName = $_POST["pageName"];
$pagePosition = $_POST["pagePosition"];
$pageVisible = $_POST["pageVisible"];
$pageContent = $_POST["pageContent"];
if (!empty($errors)) {
$_SESSION["errors"] = $errors;
redirect_to("new_page.php");
}
$query = "INSERT INTO pages ( subject_id, menu_name, position, visible, content ) VALUES ('{$subject_id}' , {$pageName}, {$pagePosition} ,{$pageVisible} ,{$pageContent} )";
$result = mysqli_query($connection, $query);
if ($result) {
// Success
$_SESSION["message"] = "Page created.";
redirect_to("manage_content.php");
} else {
// Failure
$_SESSION["message"] = "Page creation failed.";
redirect_to("new_page.php?subject={$subject_id}");
}
</pre>
I have checked out the page that submits to the form processing page and the form submits correctly. I've also checked all the external functions that I reference and all of them work. Additionaly, the first variable that uses the $_GET superglobal works just fine. The problem is in the query somehow not being able to pull in the 4 $_POST variables. If I substitute all the variable values with hard-code values, the query goes through fine and creates a new row in my table.
Any help with this would be appreciated, as I have checked and rechecked this so many times, and I am sure I'm missing something very small, but it's driving me crazy.
Thanks.
You're missing quotes around your string values:
$query = "INSERT INTO pages ( subject_id, menu_name, position, visible, content ) VALUES ('{$subject_id}' , '{$pageName}', {$pagePosition} ,{$pageVisible} ,'{$pageContent}' )";
This would have been obvious if you checked for errors using mysqli_error().

Php message updater clearing row instead of updating it

I am using the following script to process a form that updates a message on my website, the problem I am having is that it is clearing the row instead of updating it for some reason. I have copied the query from Phpmyadmin so I know its correct, and I have also tried echoing the posted values and they all echo out just fine too, but for some unknown reason when I click submit in the form it just wipes the contents of the record instead of updating it.
<?php
include("connectmysqli.php");
if (isset($_POST['OnOff'])) {$OnOff = $_POST['OnOff'];}else {$OnOff = '';}
if (isset($_POST['title'])) {$title = $_POST['title'];}else {$title = '';}
if (isset($_POST['message'])) {$message = $_POST['message'];}else {$message = '';}
$stmt = $db->prepare("UPDATE `itsnb_chronoforms_data_urgentform` SET `title` = '$title',`message` = '$message',`OnOff` = '$OnOff' WHERE `cf_id` =1;");
if (!$stmt) trigger_error($db->error);
$stmt->execute();
echo 'Message Updated !';
echo '<p>Back To Main Menu</p>';
?>
This is the table :
did you echo the generated query?
there are exactly to ways I see this can happen:
your form input names do not match the post keys you check in the three if statements
you're not sending the form with method="post"
also you should only execute the update query if all three post fields are set and valid. like title and message must not be blank/empty and that onOff variable should eighter contain "on" or "off". otherwise echo an errormessage so the user knows what's wrong with his input.

Updating only the submitted fields from account settings page

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

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