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.
Related
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';
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
I have checkboxes that represent the condition of a product. When a user checks for example Excellent, the value 1 is stored in a GET-variable like this:
...index.php?condition=1
Now, when the user checks multiple boxes (which has to be possible), it looks like this:
...index.php?condition=1,2,3
Obviously, I have to query my database in order to show the products corresponding to the user's choice(s).
if the user only checks one box, the statement is simple:
if (!empty($_GET['condition'])){
$sql = $sql . " AND (Condition = '".$_GET['condition']."')";
}
But what if the user checks multiple boxes? How would the statement have to look? (is it even possible to solve it this way?
thanks!
This is the script that creates the address:
<script>
$('#condition_select input:checkbox').change(function() {
var condition = $("#condition_select input:checkbox:checked").map(function() {
return this.value;
}).get().join(',');
$("#submit_checkboxes").find("a").attr('href', 'index.php?condition=' + condition);
}).change();
</script>
HTML:
<div class="mutliselect" id="condition_select">
<form method="POST" action="">
<ul>
<li><input type="checkbox" id="d1" value="1"'; if(strpos($_GET['condition'],'1') !== false){ echo 'checked="checked"';} echo'/><label for="d1" class="checkbox_title">Neu</label></li>
<!-- and 6 more of these -->
Is there a way to solve this without having to create a separate GET-variable for each checkbox?
UPDATE (once more updated accrding to comments and questions updates):
Question updated, so I will update my answer to. Use explode (http://php.net/manual/en/function.explode.php), to get all values, and implode to formulate query:
$values = explode(',', $_GET['condition']);
// VALIDATE each of values to match Your type.
if (!empty($values)) {
// $values = [1, 2, 3]
foreach ($values as $key => $value) {
$values[$key] = '(condition = \''.$value.'\')';
}
// $values = ['(condition = \'1\')', '(condition = \'2\')', '(condition = \'3\')']
$query = implode(' OR ', $values);
// $query = '(condition = \'1\') OR (condition = \'2\') OR (condition = \'3\')',
$sql = $sql . ' AND ( '.$query.' )';
}
This is Your solution I think (MYSQL multiples AND: http://forums.mysql.com/read.php?10,250552). Example of explode working:
$string = '1,2,3,4,asd,fgh';
$array = explode(',', $string);
print_r($array[0]); // 1
print_r($array[3]); // 4
print_r($array[5]); // 'fgh'
This is a fragment of answer before edits, but I think it is worth to left it here:
Hoverwer, there are many security holes in it!!!
YOU MUST verify the user data. If someone pass in the address for example:
index.php?condition=; SHOW TABLES FROM database;
It can potentialy show some data. As You can see, user can also go to address with delete statemant, or INSERT INTO users... etc.
So in that case YOU SHOULD switch to PDO (for example) http://php.net/manual/en/pdo.prepare.php, and make prepared statements. Verify user data so if You need the number, he can pass only number.
You can use isset also: isset vs empty vs is_null. It is not a must, but sometimes can be useful. With each form you can also check for isset ($_POST['submit']) as many robots that spam POST forms, sometimes just ommit the submit button. It will decrease the amount of requests I think.
Remember that using POST and GET forms ALWAYS allow user to send his own POST / GET requests. In that case, server side verification is a MUST.
PS. Sorry for capital letters, they are used only to make it really STRONG. Verify user data ;).
Best regards.
I'm getting the following error when I run this code:
Parse error: syntax error, unexpected ',', expecting ')' in /Applications/XAMPP/...results.php on line 43
Line 43 corresponds to the query line below.
Here is my code. The variables are related to form inputs from a questionnaire page. $source_of_fund_1 and $source_of_fund_1 are related to radio button form inputs. The other variables are related to text fields/areas. I'm using validation of isset for the radio button variables and !empty for the text field/areas.
<?php
$source_of_fund_1 = $_POST['source_of_fund_1'];
$source_of_fund_2 = $_POST['source_of_fund_2'];
$repayment_date = $_POST['repayment_date'];
$do_differently = $_POST['do_differently'];
require_once 'connect.inc.php';
$query = "INSERT INTO tablename
(source_of_fund_1, source_of_fund_2, repayment_date, do_differently)
VALUES
('$source_of_fund_1', '$source_of_fund_2', '$repayment_date', '$do_differently')";
$result = #mysqli_query($link, $query);
if (($result) && !empty($repayment_date, $do_differently)
&& isset($source_of_fund_1, $source_of_fund_2)) {
echo 'Thank you for your submission.';
} else {
echo 'We were unable to process your information.'.mysqli_error($link).'Please ensure all required fields were filled out.';
}
mysqli_close($link);
?>
Any help at all would be much appreciated! Thank you!
Your problem is with the empty call. It does not take more than one parameter:
!empty($repayment_date, $do_differently)
should be:
!empty($repayment_date) && !empty($do_differently)
The immediate issue is, I think, because you're using empty with multiple parameters - unlike isset, it only takes one.
There are a couple of other issues, though.
Don't suppress any errors with the # - if something goes wrong,
you want to know about it, so you can handle it appropriately.
You're passing content from $_POST directly into your SQL with no sanity checking. This is not safe. At the least you should be using mysqli_real_escape_string - but if you're using mysqli, why not make it into a prepared statement, and bind the variables instead? It's much, much safer.
I'm trying to creat a form dynamically depending on the number of rows of a table in a database. I tried this and it's nor working:
require_once('mysqli_connect.php');
//I select the colum w_spanish from the table selected by the user
$q="SELECT w_spanish FROM ".$_GET['name'];
$r=#mysqli_query($dbc, $q);
echo '<FORM METHOD="POST" ACTION="Correction.php">';
echo '<TABLE BORDER="1">';
//Here is where I generate dinamically a table that can be filled by user
while ($row=mysqli_fetch_array($r, MYSQLI_ASSOC)){
$aux=$row['w_spanish'];
echo '<TR><TD>'.$aux.'</TD><TD><INPUT TYPE="TEXT" NAME="Sol_'.$aux.'" SIZE="20"></TD></TR>';
}
echo '</TABLE>';
echo '<P><INPUT TYPE="SUBMIT" VALUE="Submit" ></P></FORM>';
mysqli_close($dbc);
So when I press submit, the information is not sent to "Correction.php", and I think it's because I creating the HTML form inside php code. How could I do it right??
First off - remove the # from the #mysqli statement as it is masking any errors that maybe happening.
Secondly take the generated code and paste it into http://validator.w3.org/#validate_by_input and see if there are any HTML errors and adjust where necessary.
Thirdly, since the user can select which table to read then your data needs to be super-sanitised as you certainly don't want sql injection attacks here.
The problem may be the query you are running. Without knowing more information, my guess would be your query isn't getting anything. Try dumping the row in each iteration and see what spits out. You may be looking for something like:
$q="SELECT w_spanish FROM tableName WHERE name = " . $_GET['name'];
If that's not it, it could also be the fact that since you are only grabbing one column from the database, you don't need access the information with $aux=$row['w_spanish'];. You can just use:
$aux=$row;
That I'm not 100% on though. Try dumping each row with var_dump() and see what pops out.
First declare $row, then use a do-while loop.
$row = mysqli_fetch_array($r, MYSQLI_ASSOC) do{
$aux=$row['w_spanish'];
echo '<TR><TD>'.$aux.'</TD><TD><INPUT> TYPE="TEXT"NAME="Sol_'.$aux.'" SIZE="20"></TD></TR>';
}while ($row=mysqli_fetch_array($r, MYSQLI_ASSOC))