one field keeping SQL UPDATE statement from working - php

This has consumed my Saturday. Please help.
I have a large form that I need to update a record in a MySQL database table hosted on a GoDaddy shared account. There are 18 records I'm trying to update when the form is submitted, but so far I've only gotten 17 to do so. The 2nd to last field, "blackTowellCount", causes problems when I include it in the UPDATE statement.
If I exclude the field in question from the SQL statement, ALL 18 fields successfully POST the data to the PHP file and the 17 listed in the SQL statement upload just fine. When I include the blackTowellCount field, the UPDATE stops working and the form no longer POSTS the data to the PHP form. WTF?!
You'll also notice that there's a nearly identical field, "whiteTowellCount" that updates just fine.
portion of the form:
<div class="well">
<div class="row">
<div class="col-md-1">
</div>
<div class="col-md-2">
<label for="blackTowellCount" class="pull-right">Black Towells</label>
</div>
<div class="col-md-3">
<input type="text" class="form-control" id="blackTowellCount" name="blackTowellCount" placeholder="black towell #"/>
</div>
<div class="col-md-2">
<label for="whiteTowellCount" class="pull-right">White Towells</label>
</div>
<div class="col-md-3">
<input type="text" class="form-control" id="whiteTowellCount" name="whiteTowellCount" placeholder="white towell #"/>
</div>
<div class="col-md-1">
</div>
</div>
</div>
Functional SQL:
$addIntakeSQL = mysqli_query($link,"UPDATE Act SET w9FilePath='".$w9Upload_destination."', riderFilePath='".$riderUpload_destination."', hospRiderFilePath='".$hospRiderUpload_destination."', inputFilePath='".$inputListUpload_destination."', stageFilePath='".$stagePlotUpload_destination."', backlineFilePath='".$backlineUpload_destination."', bathTowellCount='".$bathTowellCount."', breakfastCount='".$breakfastCount."', lunchCount='".$lunchCount."', dinnerCount='".$dinnerCount."', breakfastRestriction='".$breakfastRestriction."', lunchRestriction='".$lunchRestriction."', dinnerRestriction='".$dinnerRestriction."', arrivalDate='".$arrivalDate."', arrivalTime='".$arrivalTime."', needTransport='".$needTransport."', whiteTowellCount='".$whiteTowellCount."' WHERE actID='".$actID."'") or die (mysqli_error());
Broken SQL:
$addIntakeSQL = mysqli_query($link,"UPDATE Act SET w9FilePath='".$w9Upload_destination."', riderFilePath='".$riderUpload_destination."', hospRiderFilePath='".$hospRiderUpload_destination."', inputFilePath='".$inputListUpload_destination."', stageFilePath='".$stagePlotUpload_destination."', backlineFilePath='".$backlineUpload_destination."', bathTowellCount='".$bathTowellCount."', breakfastCount='".$breakfastCount."', lunchCount='".$lunchCount."', dinnerCount='".$dinnerCount."', breakfastRestriction='".$breakfastRestriction."', lunchRestriction='".$lunchRestriction."', dinnerRestriction='".$dinnerRestriction."', arrivalDate='".$arrivalDate."', arrivalTime='".$arrivalTime."', needTransport='".$needTransport."', blackTowellCount='".$blackTowellCount."', whiteTowellCount='".$whiteTowellCount."' WHERE actID='".$actID."'") or die (mysqli_error());
portion of .PHP file:
$bathTowellCount = $_POST['bathTowellCount'];
$breakfastCount = $_POST['breakfastCount'];
$lunchCount = $_POST['lunchCount'];
$dinnerCount = $_POST['dinnerCount'];
$breakfastRestriction = $_POST['breakfastRestriction'];
$lunchRestriction = $_POST['lunchRestriction'];
$dinnerRestriction = $_POST['dinnerRestriction'];
$arrivalDate = $_POST['arrivalDate'];
$arrivalTime = $_POST['arrivalTime'];
$needTransport = $_POST['needTransport'];
$blackTowellCount = $_POST['blackTowellCount'];
$whiteTowellCount = $_POST['whiteTowellCount'];
$addIntakeSQL = mysqli_query($link,"UPDATE Act SET w9FilePath='".$w9Upload_destination."', riderFilePath='".$riderUpload_destination."', hospRiderFilePath='".$hospRiderUpload_destination."', inputFilePath='".$inputListUpload_destination."', stageFilePath='".$stagePlotUpload_destination."', backlineFilePath='".$backlineUpload_destination."', bathTowellCount='".$bathTowellCount."', breakfastCount='".$breakfastCount."', lunchCount='".$lunchCount."', dinnerCount='".$dinnerCount."', breakfastRestriction='".$breakfastRestriction."', lunchRestriction='".$lunchRestriction."', dinnerRestriction='".$dinnerRestriction."', arrivalDate='".$arrivalDate."', arrivalTime='".$arrivalTime."', needTransport='".$needTransport."', whiteTowellCount='".$whiteTowellCount."' WHERE actID='".$actID."'") or die (mysqli_error());
}

Hi First of all as all suggested your code is open to SQL injections, Use PDO instead . Second php has its functions to display errors include them if you got nothig to do.
add these lines at top of your page
error_reporting(E_ALL);
ini_set('display_errors',1);
also you have not given mysqli_error() its parameter
Replace die(mysqli_error()); with die(mysqli_error($link));

There was a space in front of "blackTowellCount" in the database. I hate programming.

Related

PHP form validation not functioning having copied the tutorial code

I am hoping the community can give me a little insight into what is not working with my code, I am following a Udemy course. I have followed the accompanying video which developed an undefined variable error, which after doing some research I believe I have fixed by declaring variables as empty strings being able to be over-ridden by the form data.
The form sends data to the database if both are completed, and if one of the fields is empty then it doesn't, which is as it should be.
If one of the fields is empty it should return a statement asking the user to enter data into the respective field, but nothing is being sent.
The only difference between the tutorial and my code is I have used the materialize framework, where the tutorial used bootstrap, but I can't see that being the issue.
I have attached my code, and commented out redundant parts.
<?php
include('php/connection.php');
//validates data for create user form
if( isset( $_POST["createUserBtn"])){
$createUsername = "";
$createUserPassword = "";
function validateFormData( $formData ) {
$formData = trim( stripcslashes( htmlspecialchars( $formData)));
return $formData;
}
if( !$_POST["createUsername"]){
$createUsernameError = "Enter a username <br>";
} else {
$createUsername = validateFormData( $_POST["createUsername"]);
}
if( !$_POST["createUserPassword"]){
$createUserPasswordError = "Enter a Password <br>";
} else {
$createUserPassword = validateFormData( $_POST["createUserPassword"]);
}
if( $createUsername && $createUserPassword) {
$query = "INSERT INTO users (user_id, userName, userPassword) VALUES (NULL, '$createUsername', '$createUserPassword')";
// if( mysqli_query( $connection, $query)){
// echo "New User added";
// } else {
// echo "Error: ".$query."<br>".mysqli_error($connection);
// }
}
}
?>
<!DOCTYPE html>
<html lang="en">
<?php require('static/header.php'); ?>
<?php
$createUsernameError = "";
$createUserPasswordError = "";
?>
<div class="col s8 m8 l5 valign-wrapper">
<div class="container">
<form action="<?php echo htmlspecialchars( $_SERVER["PHP_SELF"] ); ?>" method="post">
<div class="row">
<div class="col s12">
<span><h4>Create your user account - create user.php</h4></span>
<div class="row form-font">
<div class="col s12">
<div class="input-field">
<a class="red-text"><?php echo $createUsernameError; ?></a>
<input placeholder="Enter your username" type="text" name="createUsername">
<label for="email">Username</label>
</div>
<div class="input-field">
<a class="red-text"><?php echo $createUserPasswordError; ?></a>
<input placeholder="Enter your password" type="password" name="createUserPassword">
<label for="password">Password</label>
</div>
<div class="row left-align">
<div class="col s2"></div>
<div class="col s8">
<button class="btn-flat waves-effect waves-custom" type="submit" name="createUserBtn"><i class="material-icons left">create</i>Create Account</button>
</div>
<div class="col s2"></div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<?php require('static/footer.php'); ?>
</html>
Look carefully at your code and the places where you make use of - for example - the $createUsernameError variable.
If there's an error, you set a message in it with this line: $createUsernameError = "Enter a username <br>";. Great, just what you wanted.
However, later on in the code, you run $createUsernameError = "";, which resets it to empty again. And that happens in all circumstances, whether an error was identified or not. And it happens before you try to echo that variable onto the page.
So basically you're setting the value and then immediately blanking it again before you output it. You need to make sure it's only set blank in situations where there's no error. It's the same problem for the password error message.
An easy way to do that would simply be to set the value blank before you run the error checks. Then it'll stay blank if there's no error, but it won't overwrite any error messages which do get set.
So just move these lines:
$createUsernameError = "";
$createUserPasswordError = "";
to the top of your script.
P.S. Please pay attention to the security warnings posted in the comments and urgently fix your code to remove these vulnerabilities before using this code in any kind of live environment. Even if you don't plan to use this code for real, you should still fix these issues so that you learn to do things the correct, safe, reliable way and don't get into bad habits. If you copied this code from a course online, I suggest finding a better course.

sending form data to mySQL using get

I want to send user entered form data to mysql via php using get.
<form action="formtosql.php" method="get">
<div class="row">
<div class="form-group col-md-4">
<label for="001">Student name:</label>
<input type="text" class="form-control" id="001" name="sname">
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="002">Status:</label>
<input type="text" class="form-control" id="002" name="sstatus">
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
php code looks like this:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET'){
$name = $_GET['sname'];
$stat = $_GET['sstatus'];
// Connecting to the Database
$servername = "localhost";
$username = "root";
$password = "";
$database = "exam";
// Create a connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Die if connection was not successful
if (!$conn){
die("Sorry we failed to connect: ". mysqli_connect_error());
}
else{
$sql = "INSERT INTO `estatus` (`name`, `status`, `date`) VALUES ('$name', '$stat', current_timestamp())";
$result = mysqli_query($conn, $sql);
?>
In php im getting an error while using get:
Notice: Undefined index: sname in C:\xampp\htdocs\helloworld\formtosql.php
Notice: Undefined index: sstatus in C:\xampp\htdocs\helloworld\formtosql.php
This error does not occur if I am using Post.
I am assuming that you have both the generation of the form, and the processing of the submitted value, in the same script here?
This error does not occur if I am using Post.
You checked the REQUEST_METHOD to determine if you are dealing with the case, that the form was submitted.
When you use method="post" on your form, you can do that - the initial request that loaded the page containing the form was used making the GET method, submitting it will use POST - so these two cases can be distinguished between using that method.
But if you use method="get", then both requests - the one used to initialy load the page, and the one used to submit the form data - are of the same method, and therefor you can not use that any more, to differentiate between the two cases.
If you give your submit button a name, then you could check (using isset/empty), whether the corresponding parameter exists - and use that to determine, which of the two cases you are dealing with.
But as already mentioned in comments - for requests that create data on the server side, you should generally use POST, not GET. Under When do you use POST and when do you use GET? you can find a more in-depth explanation of that.

Html form to sql database with php

I am trying to make a site which users can upload phrases. Basically there is a text field and then it gets uploaded to the mysql database. Here is what I have tried so far.
HTML::
<form class="form-horizontal" action="drop.php" method="post">
<fieldset>
<!-- Form Name -->
<legend>Submit a Billboard</legend>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="textinput">What will your Billboard Say?</label>
<div class="controls">
<input name="text" type="text" placeholder="What you going to say?" class="input-xlarge">
</div>
</div>
<br>
<!-- Button -->
<div class="control-group">
<div class="controls">
<button id="singlebutton" name="singlebutton" class="btn btn-primary">Drop Your Billboard</button>
</div>
</div>
</fieldset>
</form>
PHP::
<?php
//Connecting to sql db.
$connect = mysqli_connect("localhost","mod","","bill");
//Sending form data to sql db.
mysqli_query($connect,"INSERT INTO submit (submission)
VALUES ('".$_POST['text']."')
?>
Besides your SQL injection, your button doesn't do anything really, not without any JS which if you're using, you haven't shown it. Therefore, this answer is based on what you posted
It would require an type="submit" in order for your button to fire up anything.
I'm taking a blind stab at this, but I'm prrrrretty sure that's what's "not" going on here.
Plus and more importantly (and not a blind stab), you're missing a closing bracket, a quote and semi-colon in: (a major syntax error)
mysqli_query($connect,"INSERT INTO submit (submission)
VALUES ('".$_POST['text']."')
^^^ missing bracket/quote/semi-colon
so do
mysqli_query($connect,"INSERT INTO submit (submission)
VALUES ('".$_POST['text']."')");
^^^ missing/added
Escape your data:
if(!empty($_POST['text'])){
$text = mysqli_real_escape_string($connect, $_POST['text']);
mysqli_query($connect,"INSERT INTO submit (submission) VALUES ('".$text."')");
}
However, you really should use a prepared statement for that SQL injection:
https://en.wikipedia.org/wiki/Prepared_statement
Check for errors.
Consult these following links http://php.net/manual/en/mysqli.error.php and http://php.net/manual/en/function.error-reporting.php
and apply that to your code.
If your entire code is inside the same page, you will receive undefined index notice.
Error reporting will tell you that.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
As well as or die(mysqli_error($connect)) to mysqli_query().
If so, then you will need to use !empty() for the POST array.
http://php.net/manual/en/function.empty.php
You could have also used:
$connect = mysqli_connect("localhost","mod","","bill")
or die(mysqli_error($connect)); // check if successful or not
if(!empty($_POST['text'])){
$text = mysqli_real_escape_string($connect, $_POST['text']);
$query = "INSERT INTO submit (submission) VALUES ('".$text."')";
$result = mysqli_query($connect, $query);
if (!$result)
{
throw new Exception(mysqli_error($connect));
}
else{ echo "Success."; }
}
You can try isset() function to insert the input into your database.
if(isset($_POST['singlebutton']))
{
$text= $_POST['text'];
$query= $connect->prepare ( "INSERT INTO submit(submission) VALUES (?)");
$query -> bind_param("s",$text );
if ($query->execute())
{
echo"<center><strong>Text added! </strong></center>";
} // display when text is added
else{
echo"Error in adding text!"; // display when there is error
}
}

MySQL stores only "1" (as a value) no matter what numbers I submit in the form

I am trying to create a simple bootstrap form in php and mysql (I use xampp with default settings). Everything is done in 1 file called index.php.
Here is my form:
<form class="form-horizontal" role="form" method="post" action="index.php" >
<div class="form-group">
<label for="inputLongitude" class="col-lg-2 control-label">Longitude</label>
<div class="col-lg-10">
<input type="number" class="form-control" id="inputLongitude" placeholder="longitude" name="inputLongitude">
</div>
</div>
<div class="form-group">
<label for="inputLatitude" class="col-lg-2 control-label">Latitude</label>
<div class="col-lg-10">
<input type="number" class="form-control" id="inputLatitude" placeholder="latitude" name="inputLatitude">
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" name="submit" class="btn btn-primary">Save</button>
</div>
</div>
</form>
The form is very simple, it takes 2 values and stores them in the db. And here my php code I use to store values in mysql (in the same file - index.php):
$conn = mysqli_connect('localhost', 'root', '', 'android_app') or die("bla");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$longti = isset($_POST['inputLongitude']);
$lati = isset($_POST['inputLatitude']);
$sql = "INSERT INTO `table`(`key_primary`, `lati`, `longti`) VALUES (`key_primary`,$lati,$longti)";
mysqli_query($conn,$sql);
Until now almost everything works fine. The both values are saved.
Here is my setting for db: http://i.imgur.com/hyuNJsj.jpg
NOW my problem: Values, which are supposed to be saved (= which I want to submit and store in the db) , are not stored. So instead of storing e.g. "50,5" mysql stores only "1" - always, no matter what I sent in the form. Take a look here http://imgur.com/brjFn5e.
What is really interesting is that if I use SQL in phpmyadmin and insert values there ("manual way") it is ok. No problem at all. Do you an idea how I can solve that? Is my db setting wrong ? Or it is somewhere in the code ?
Your problem occurs here:
$longti = isset($_POST['inputLongitude']);
$lati = isset($_POST['inputLatitude']);
This block is assigning the truth value of isset(...) to $longti and $lati instead of your intended values from $_POST. If you're completely assured of the security of these $_POST values (which you should not be), then you should have:
$longti = isset($_POST['inputLongitude']) ? $_POST['inputLongitude'] : null;
$lati = isset($_POST['inputLatitude']) ? $_POST['inputLatitude'] : null;
If these values are coming from untrusted sources (as $_POST values usually are) then you should also perform some validation on the values before outputting them to your db.
Edit: I just noticed $out = isset($in) ? $in : null; pattern looks (and is) redundant: $out = $in; would perform exactly the same. My usual is to include basic validation/filtering within this step. For instance, if all you're expecting/allowing is a numeric value (since your <input> type is 'numeric'):
$longti = isset($_POST['inputLongitude']) && is_numeric($_POST['inputLongitude'])
? $_POST['inputLongitude'] : null;
or integers only:
$longti = isset($_POST['inputLongitude']) ? (int) $_POST['inputLongitude'] : null;
These are simplistic examples that don't include feedback to the user of invalid form content, etc.
You are using the isset function
$longti = isset($_POST['inputLongitude']);
the above code does not set the value of $_POST['inputLongitude'] but rather whether $_POST['inputLongitude'] exists... 1 would mean that it exists.
You can simply use:
$longti = $_POST['inputLongitude'];
$lati = isset($_POST['inputLatitude']);
This is always 0 or 1 :isset or not.Use if isset blah=someotherblah
if (isset($_POST["inputLatitude"])) {
$lati = $_POST['inputLatitude'];
}else{
echo "N0, inputLatitude is not set";
}

PHP and ADODB - ADODB throwing an error when uploading content

I have the following code (truncated a touch as the css is irrelevant) that I am trying to submit to my MSSQL server. Problem is, it just throws up an error every thing I try. The code is split over 2 PHP pages. Page 1 has the form and Page 2 has the connection data and string.
Page 1 (I have a js function that duplicates the text in the span sections so you get a preview of it before you submit which is why theres the extra at the bottom):
<form action="create.php" name="frmAdd" method="post">
<div class="news"><a id="news1"></a>
<div class="newstitle">
<h3>
<input id="headline" type="text" maxlength="50" name="headlinetxt" />
</h3>
</div> <em><h5>
<input id="timestamp" type="text" name="timestamptxt" />
</h5></em>
<div class="divider"></div>
<p>
<textarea id="news" type="text" name="newstxt"></textarea>
</p>
</div>
</div>
<div class="news"><a id="news1"></a>
<div class="newstitle">
<h3>
<span id="headlinedisp" /></span>
</h3>
</div> <em><h5>
<span id="timestampdisp" /></span>
</h5></em>
<div class="divider"></div>
<p><span id="newsdisp" /></span>
</p>
</div>
</div>
<div id="button" onClick="document.forms['frmAdd'].submit();">Submit</div>
</form>
Page 2:
<head>
<title>News Edit</title>
</head>
<body>
<?php
include('/adodb5/adodb.inc.php');
$db = NewADOConnection('odbc_mssql');
$dsn = "Driver={SQL Server};Server=sage;Database=live;";
$db -> Connect($dsn,'user','pass');
$strSQL = "INSERT INTO website_news VALUES ('".$_POST["headlinetxt"]."','".$_POST["timestamptxt"]."','".$_POST["newstxt"]."') ";
$upld = $db->Execute($strSQL);
If($upld)
{
echo("Complete");
}
else
{
echo("Error");
}
$db->Close();
$db = null
?>
</body>
Does anyone have any ideas as to why this may not be connecting? I assume it is an issue with line 10 of my page 2 (where it compiles the SQL) as this was giving me seperate errors earlier in my debug. I do have a unique ID in column 1, but this should be auto-populated in theory although dont know if I will need to add this in with something like ...IDENTITY,'".$POST_["headline.... etc. as really that should not be necessary. Is there a better way to debug different parts of the code rather than just showing Error too? (EDIT: Found out last night I can use objErr the same way I can use Err in VB. Didn't think of it at all. Will test that and see what I get)
(PS. A slight side question that I will post seperately if requested. I have the duplicate function working fine in theory (i.e. it works in JSFiddle), but as soon as I take it and put it into place I cannot get it to work on the site itself, running in Chrome, running the same spec jQuery as the fiddle. Fiddle is here: http://jsfiddle.net/bmgh1985/XcScd/)
Never mind. I figured it out (realised I could use Err.Description as in VB)

Categories