Handling Nulls from form input to SQL - php

So,
I am trying to create dynamic SQL queries where we assume:
If the _GET or _POST doesn't have a variable set we call it NOT SET
If the _GET or _POST is set but the value is empty then we call it EMPTY
If the _GET or _POST is set but the value is not empty then we call it NON-EMPTY
Now we can easily store the EMPTY and NON-EMPTY variables in MySQL as they are (because we know the intention of the end user since the variables have been set)
OUR Mapping so far:
EMPTY & NON-EMPTY = whatever the value is...
(for date column in MySQL since it doesn't allow empty we put in 0000-00-00 00:00:00. We use this logic for both the INSERTS and UPDATES
NOT-SET in PHP = NULL in database? (since we don't know anything about the value)
Now this works perfectly for situations where data doesn't already exist for example INSERT statements, but what about UPDATE STATEMENTS?
What if the record already has a value?
I am thinking of using NOT SET variable as to be ignored in UPDATE statements?
So if, lets say POST["name"] is not set on INSERT, then we still insert it as a null
INSERT INTO person (name) VALUES (POST["name"]);
but, if it is an UPDATE statement, we ignore it completely.
UPDATE person
isNull(POST["name"]) ? SET name = POST["null"]
My dilemma is what do we do for INSERTS and UPDATES when these variables are NOT SET?

<html>
<body>
<form method="post">
<label for="field_1">Field 1</label>
<br />
<input type="text" name="field_1">
<br />
<br />
<label for="field_1">Field 2</label>
<br />
<input type="text" name="field_2">
<br />
<br />
<label for="field_1">Field 3</label>
<br />
<input type="text" name="field_3">
<br />
<br />
<input type="submit" name="submit" value="submit">
</form>
<?php
// BASIC IDEA:
// (This example assumes all incoming post values are strings,
// if you have, for example, integers, you'd need to remove the
// single quotes around the values in the SQL statement)
// Loop through POST array
// foreach _POST variable as key => value
foreach($_POST as $k => $v) {
// if not null, blank, or "submit"
if(!is_null($v)&& $v != ''&& $v != 'submit') {
if(!isset($strSQL)) {
// If this is the first value, start off the sql string w/ UPDATE
$strSQL = "UPDATE your_table " ."SET " .$k ." = '" .$v ."'";
} else {
// For subsequent values, include a comma and space before new value
$strSQL = $strSQL ."', SET " .$k ." = '" .$v ."'";
}
}
}
// Finish off SQL Command, if one was ever started
if(isset($strSQL)){
$strSQL = $strSQL ." WHERE some_field meets_your_conditions;";
// Run SQL Command (echo just used for example)
echo $strSQL;
}
?>
</body>
</html>

In case of no set:
Insert:
INSERT INTO person (name) VALUES (NULL);
Update:
Don't call update if no set as the value can either be :
1) Null : If null no need to update it
2) Not Null: If not null, then you will be loosing values if you assign it null.
PS: This is my suggestion as per understanding of the requirement, but
it may differ as per actual requirements.

Related

Updating to database using php

The only way I got this to work was if I used the empty. However, this is not what I want. I want to be able to leave something empty if I have to. Does anyone know how I should change the code for this to work?
Edit page:
<form name="homePage" action="update.php" method="POST">
<Strong>Change home title:</Strong>
<p>
<input style="width: 300px;" type="text" name="homeTitleChange" value="<?php echo $homeTitle ?>">
<input type="hidden" name="rowHomeID" value="<?php echo $getHomeID?>">
</p>
<Strong>Change home subtitle:</Strong>
<p>
<input style="width: 600px;" type="text" name="homeSubtitleChange" value="<?php echo $homeSubtitle ?>">
<input type="hidden" name="rowHomeID" value="<?php echo $getHomeID?>">
</p>
<input type="submit" class="btn btn-skin" name="homepage" value="save" />
</form>
Query Page:-
include("../conn.php");
include("../conn.php");
if(isset($_POST['homepage'])){
if(
!empty($_POST["homeTitleChange"])&&
!empty($_POST["homeSubtitleChange"]) &&
!empty($_POST["rowHomeID"])
){
$homeTitleUpdate = $_POST["homeTitleChange"];
$homeSubtitleUpdate = $_POST["homeSubtitleChange"];
$homeEditRow = $_POST["rowHomeID"];
$query = "UPDATE Home SET
title = '$homeTitleUpdate',
subtitle ='$homeSubtitleUpdate'
WHERE homeID = '$homeEditRow' ";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if ($result) {
echo "<p> - Success!</p>";
}else{
echo "<p> - Something went wrong</p>";
}
}
}
Thanks!
Precursors:
You have included your connection script twice.
You are including the hidden form field <input type="hidden" name="rowHomeID" value="<?php echo $getHomeID?>"> twice. This is inefficient.
Your form should have enctype='multipart/form-data' . Read Here
Without seeing your MySQL error we can't absolutely diagnose your problem, so instead I will give you the parts I know need to be fixed:
By default PHP string types will hold an empty string '' rather than a NULL value so I don't think your issue is empty values being inserted incorrectly (at least, not as described in your question).
$homeEditRow is the only required value. Because UPDATE table SET column=value WHERE column=<empty> will result in an error (or at the very least, no update).
Therefore replace:
if(
!empty($_POST["homeTitleChange"])&&
!empty($_POST["homeSubtitleChange"]) &&
!empty($_POST["rowHomeID"])
)
with:
if(!empty($_POST["rowHomeID"]){
//run MySQL Update query.
}
Also, if the value is meant to be an integer, you can simply do this:
$homeEditRow = (int)$_POST['rowHomeID']; //force to int.
if($homeEditRow > 0 ){
//run MySQL Update query.
}
Your other two values can be empty if you wish, that's fine.
BUT what these values can not contain is unescaped special characters in MySQL, typically (but by no means exclusively) ` , ', --, # characters.
So, it's best to clean unsafe characters from your user input.
Never Ever Trust User Input to be "safe"
$homeTitleUpdate = mysqli_real_escape_string($conn,$_POST["homeTitleChange"]);
$homeSubtitleUpdate = mysqli_real_escape_string($conn,$_POST["homeSubtitleChange"]);
//assuming to be integer required
$homeEditRow = (int)$_POST["rowHomeID"];
This means any single quotes, or other unsafe characters do not interefere with your query execution. using Prepared statements is much safer than this method and is the recommended way of doing these things, you can use either PDO or MySQLi and there are many, many fine examples on Stack Overflow of these systems.
If you reach this point and you are still having issues, then you need to read what your MySQL error output is saying to you :
//after your query regardless of outcome:
var_dump(mysqli_error($conn));
You may have issues such as you have a primary index column with two non-unique values (etc, etc). But we won't know for sure until you can output the MySQL error.
Finally, be careful with your IF statements checking if the Update Query was carried out because if nothing changed, there was no change to update, MySQL will not run the query, so could potentially return false when everything in fact ran correctly.
Without specifying your errors, we can only assume your problem. Only you can debug your program, so for future notice please execute the following lines of code at the top of your scripts and tell us your errors.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Moving on, your script contains a condition that checks the values at the index in $_POST is !empty() but doesn't wrap around your Query. This meaning, whether or not the values are empty or set, your query will execute.
Assuming you only want to the query to run when there are values set, you can wrap this with an if expression:
// an array of all the index's
$index = ['homeSubtitleChange', 'homeTitleChange', 'rowHomeID'];
// loop through each index and check they're not empty
foreach($index as $_index)
{
if( empty( $_POST[$_index] ) && !isset( $_POST['homepage'] ) )
{
// if empty - halt the program with an error
die("Expected POST index: $_index or homepage.");
}
}
unset($_index); //cleanup
// if it got here - all index's have values
// as Martin said in the comments, I assume you can wrap mysqli_real_escape_string()
// and intval() ensuring the value is type (int) to protect
// your database against SQL attacks
$subtitle = mysqli_real_escape_string($conn, $_POST[$index[0]]);
$title = mysqli_real_escape_string($conn, $_POST[$index[1]]);
$row_id = intval($_POST[$index[2]]);
// consider upgrading to a PDO driver and using prepare() statements
// this SQL statement is prone to SQL injections
$sql = "UPDATE Home SET title = '$title', subtitle = '$subtitle' WHERE homeID = '$row_id'";
if( mysqli_query( $conn, $query ) )
{
die("Success.");
}
die("Failed.");
If I understand correctly, you want to allow empty string as input.
If so, what you want is isset() instead of !empty().
So, this part in your code:
!empty($_POST["homeTitleChange"])&&
!empty($_POST["homeSubtitleChange"]) &&
!empty($_POST["rowHomeID"])
replace it with this:
isset($_POST["homeTitleChange"],$_POST["homeSubtitleChange"],$_POST["rowHomeID"])
and you're good to go.
As everyone else has said, please sanitize your user input; putting it directly into the database like that is very unsafe.
As for your question, from what I can understand you are trying to work out to make sure the values are set, but you also want to be able to pass an empty string!?
If so, I think you want isset.
//...
if(
isset($_POST["homeTitleChange"])&&
isset($_POST["homeSubtitleChange"]) &&
isset($_POST["rowHomeID"])
){
//...
This will make sure you POST values are set, which they should be anyway if they submitted the form; however it will also return true if the $_POST["rowHomeID"] = 0, which may not be what you want, so you may want to go back to using !empty for that which will mean it can't be an empty string or equal to 0.

default value for $_POST[];

I have a problem with default value for $_POST[];
So i have a html form with textboxes and the informations is sent to a php script. The php script has a sql query that is being sent to my database. But if my textbox in html form is empty the query doesnt have a value. So i want to set my post to a default value 0 so it returns a value atleast.
So here is an example of html form (This is not my actuall script. Just an example.
<form action="testscript.php" method="POST">
<input type="id" name="ID"/>
<input type="text" name="test"/>
<input type="submit" value="Send"/>
</form>
Ok so this script will send both id and test textboxes will always have a number value. And it sends the information to testscript.php
Here is testscript.php example
$conn = mysqli_connect('host', 'dbuser', 'dbpass', 'dbname');
$id = $_POST['id'];
$test = $_POST['test'];
$sql = "INSERT INTO test_table (id, test) VALUES ($id, $test)";
if (mysqli_query($conn, $query)) {
echo "Success";
} else {
echo "Failed" . mysqli_error($conn);
}
Alright so now if i submit my html form to php script without inserting any text to the textboxes the query will look like this
INSERT INTO test_table (id, test) VALUES ( , )
But the query should be like this
INSERT INTO test_table (id, test) VALUES (0, 0)
So. I know i can use value attribute in the html tag but then the value will be visible in the textbox and i dont want that.
And i know i can do an if statment to make a default value like this
if (isset($_POST['test'])) {
$test = $_POST['test'];
} else {
$test = 0;
}
But now the problem is that i would have to do that if statment for every textbox and my html form have more than 100 textboxes. So i dont want to make an if statment for every textbox because then my script will be way to big and it will take hours.
So is there any way to set a default value for all the textboxes without using if statment in php or value attribute in html form?
I know it seems like a pain but you MUST check that all inputs are valid. You can simplify the amount of code by using a ternary operator like this.
$id = isset($_POST['id']) ? $_POST['id'] : 0;
$test = isset($_POST['test']) ? $_POST['test'] : 0;
....
And no, it won't take hours even with hundreds of them.
To make this slightly less painful to code you can use the power of looping with PHP's variable variables
The most painful part will be creating an array with all your field names
$fields = array('id', 'test', 'extra', 'more', ..., 'one_hundred');
Then loop through that array creating variable names and at the same time escaping the strings - if they are there - otherwise set a value of 0 (zero). You might want/need to set this to "" (empty string)
foreach($fields as $field_name)
{
${$field_name} = isset($_POST[$field_name]) ? mysqli_real_escape_string($conn, $_POST[$field_name]) : 0;
}
You now have the variables $id, $test, $extra, $more, ...., $one_hundred available for your use.
If your checkboxes have unique names, then you'll need to check them on the server side to see if they actually have values in them one by one by using the ternary
isset($_POST["test"]) ? $_POST["test"] : 0
However, if your checkboxes are in array form:
<input type="checkbox" name="courses[]" value="1">
<input type="checkbox" name="courses[]" value="2 >
Then you could do the following:
foreach($_POST['courses'] as $course) {
echo $course; // etc etc etc
}
You can also set database defaults.
Another note, your code is prone to SQL injection. Although the question you have might simply be an example, you might just keep in mind there are better and safer ways of querying a database see PDO connections.
You can easily use null check and define your default value like this :
$name = $_POST['name'] ?? 'John';
in my case the default value is John if the name is not defined. It gives the same result like this :
$name = isset($_POST["name"]) ? $_POST["name"] : 'John';

Submitting Comments using PHP MySQL debug

Just wondering if anyone can point out where I'm going wrong with the code below. I'm trying to gather the text from the form and UPDATE a field within the database with the text.
I have tested the SQL statement alone and it is updating the column correctly, but seems to be an issue with the PHP syntax as when i click on the submit button, it only insets '1' into the columns.
PHP:
$SubmitComments = isset($_POST['SubmitComments']);
$AddComment = isset($_POST['AddComment']);
if ($SubmitComments){
mysql_query ("UPDATE `table` SET `column` = '$AddComment' WHERE `column` = '$.....'") or die(mysql_error());
echo 'Comment added';
}
HTML:
<tr>
<td>Add Comment</td>
<td align="center"><form name="form1" method="POST" action=""><input name="AddComment" type="text" id="AddComment" autocomplete="off" placeholder="Add comments..." size="45px"><br />
<input type="submit" name="SubmitComments" id="SubmitComments" value="Submit"></form></td>
</tr>
Right, from the top. isset returns a bool, so $SubmitComments would only equal true or false, it will never equal the POST variable (Same with $AddComment). Consider instead:
if(isset($_POST['SubmitComments'])&&isset($_POST['AddComment']))
{
$SubmitComments = $_POST['SubmitComments'];
$AddComment = $_POST['AddComment'];
//Rest of Code
}
Second, table and column names do not need single quotes around them. And finally, as addressed in the comments, think about using MySQLi instead as if your script does eventually work, one malformed comment will erase your entire database.
Example:
If their comment is even just butts';-- It will make the SQL:
UPDATE table SET column = 'butts';--' WHERE column = '$.....'
Which is the equivalent of:
UPDATE table SET column = 'butts';
Making all of your comments just the word "butts", and that's just a humorously childish attack, compared to stealing usernames/passwords, trashing the database etc

Splitting variables from $_POST

I wanted to split my variables from a form, and enter them into a Mysql Database one by one.
My table 4 fields would be: UserID, Status, HowLate, PassFail
In this example below the UserID would be 75 and 76, but can be any # from the user id in the future. I am confused on how I would be able to insert these dynamic variables into the database since I don't know what they will be each time. The only static pattern I have is when I loop through foreach ( $_POST as $key => $value ) any help
$results = print_r($_POST, true);
sample data from form
75=PRESENT
d75=on time
cc75=passed
76=LATE
d76=10 minutes
cc76=failed
I would want to write a query like:
insert into attendance (UserID, Status, HowLate, PassFail) values (76, 'Late', '10 minutes', 'failed')
also think of this as students in a class, so there is 20 records coming back at once
I'm guessing the reason you're doing this is because you're unaware that you can send multidimensional arrays in HTML forms. I suggest an approach such as.
<input name="users[1][userid]" />
<input name="users[1][status]" />
<input name="users[1][howlate]" />
<input name="users[1][passfail]" />
<input name="users[2][userid]" />
<input name="users[2][status]" />
<input name="users[2][howlate]" />
<input name="users[2][passfail]" />
Then in php you can access them in the following manner.
foreach( $_POST['users'] as $key => $user )
{
$userID = $user['userid']; // same for the other fields.
}
Assign your variables (if you are not using PDO, which you should to avoid SQL injection) for example:
$userId = $_POST['userId']; // assuming that is what your field id is from the html form
$status = $_POST['status'];
etc.
Then insert into the database table:
insert into attendance (UserID, Status, HowLate, PassFail) values ($userId, '$status' etc.

mysql_query in a while loop

I'm trying to execute
I have an html form in a page of this sort :
Name: <input type="text" id="namebox" value="" name="fields[]" /> <br />
Position: <input type="text" id="positionbox" value="" name="fields[]" /> <br />
<input type="hidden" name="createcard">
<input type="submit" value="Create">
.. and 3 other fields. I'm passing these 5 form fields by POST to a file process.php which has the following function to insert the array elements into a mysql DB.
if(isset($_POST['createcard'])){
$this->procCreateCardtheme1();
..
..
function procCreateCardtheme1(){
global $session;
$cardData = $_POST['fields'];
$username=$session->username;
$sno=1;
echo count($cardData);
while($sno < count($cardData))
{
$v=$cardData[$sno];
echo $v;
mysql_query("INSERT INTO carddata VALUES ('$username', $sno, '$v', 1)");
$sno++;
}
Now, the echo statement above returns the expected output, that is the five or so fields. But the mysql_query only executes once. It just stores the first entry in the DB, and nothing else. Even re-submitting the form does nothing at all. It's just the one entry that is stored in the DB.
Any ideas?
Do you have a unique constraint on username in the carddata table? This will cause the second insert to fail.
To debug this you should add some error checking to your program:
mysql_query("INSERT INTO carddata VALUES ('$username', $sno, '$v', 1)")
or trigger_error(mysql_error());
You might also need to use mysql_real_escape_string to avoid syntax errors or possible SQL injection vulnerabilities if the string data can contain quotes.
Single Loop iteration issue occurs when you have issue with variable for query ($query)
and Result Object ($result).
Try different name for variable inside the WHILE Loop or debug the variable inside the loop.

Categories