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.
Related
What I want to achieve : if a user pass a PHP parameter to the server, it will return the same parameter value back to the user, instead of returning the value from the database itself.
while($row = mysqli_fetch_assoc($result)){
$classId = $row['classId'];
if($obj['classId'] != ""){
$classId = $obj['classId'];
}
...
}
For some reason, I found out that the $classId still using the $row['classId'] value, even if the user had inserted the classId parameter. It seems that the PHP has ignored/skipped the if statement.
if($obj['classId'] != ""){..} //SKIPPED?
The code works fine right now and I do get the return of the same parameter value. Only one user out of hundreds got this issue and I assumed that the he/she had sent the parameter when the server was busy.
Questions:
1.Can if-statement being ignored/skipped for some reason?
2.How to make the if-statement more reliable even if the server in a high-traffic?
Excuse me for posting here. I don't find the right keywords for googling myself.
Thank you.
You could try having your if statement more strict.
if($obj['classId'] != ""){
$classId = $obj['classId'];
} else {
$classId = $row['classId'];
}
I'd also recommend using isset instead of checking for an empty string.
if(isset($obj['classId'])) { }
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.
I am attempting to create a function that will insert items (and will do the same to edit) items in a database through a form. I have the form and the PHP - and when I run the function, I get the correct database name to pull and the variable names to pull along with the values I input, but I then see a database error? Any help would be great (I'm still newer to PHP really and pulling out some hair)
Config File:
$hostname = 'localhost';
$username = 'DEFINED';
$password = 'DEFINED';
$database = 'DEFINED';
$table = 'recipes';
require('../config.php');
$link = mysql_connect($hostname,$username,$password);
mysql_select_db($database,$link);
/* Get values and submit */
$rid = mysql_real_escape_string($_POST['rid']);
$name = mysql_real_escape_string($_POST['name']);
$category = mysql_real_escape_string($_POST['category']);
$tags = mysql_real_escape_string($_POST['tags']);
$search_tags = mysql_real_escape_string($_POST['search_tags']);
$description = mysql_real_escape_string($_POST['description']);
$description2 = mysql_real_escape_string($_POST['description2']);
$recipeAbout = mysql_real_escape_string($_POST['recipeAbout']);
$ingredients_1 = mysql_real_escape_string($_POST['ingredients_1']);
$directions_1 = mysql_real_escape_string($_POST['directions_1']);
$query = "INSERT INTO $table (name, category, tags, search_tags, description,description2, recipeAbout, ingredients_1,directions_1) VALUES ('$name','$category','$description','$description2' $tags','$search_tags','$description','$recipeAbout','$ingredients_1','$directions_1')";
echo $query;
Besides the missing comma in '$description2' $tags' => '$description2', $tags' which you said had been added afterwards, and signaled by Ryan: there's also a missing quote, so change it to '$description2', '$tags' and having 2x '$description' variables, remove one.
VALUES
('$name','$category','$tags','$description','$description2', '$search_tags','$recipeAbout','$ingredients_1','$directions_1')";
However, the most important part to querying, is that you must use mysql_query() which you are not using => mysql_query() which is why data isn't being inserted, once you've fixed the syntax errors.
mysql_query() is the essential part.
Add the following to your code:
if(mysql_query($sql,$link)){
echo "Success";
}
else{
echo "Error" . mysql_error();
}
Plus, use prepared statements, or PDO with prepared statements.
You're using a deprecated library and open to SQL injection..
Plus make sure you have assigned $table to the table you wish to enter data into. It's not shown in your question.
You also did not show what your HTML form contains. Make sure that you are using a POST method and that all elements are named with no typos.
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);
Sidenote: Error reporting should only be done in staging, and never production.
EDIT: and using mysqli_
As a quick test, try the following and replacing the values in the line below with your own.
<?php
$link = mysqli_connect("host","username","password","database")
or die("Error " . mysqli_error($link));
$table = "recipes";
$name = mysqli_real_escape_string($link,$_POST['name']);
mysqli_query($link,"INSERT INTO `$table` (`name`) VALUES ('".$name."')")
or die(mysqli_error($link));
?>
If that still does not work, then you need to check your database, table, column name(s), including types and column lengths.
Lot's of stuff wrong here...
You're missing a quote on the second of these two items, as well as either a string concat or a comma: '$description2' $tags'
You've also got your order messed up for tags, search tags, and description 1/2.
$description is in there twice (you have 9 columns defined and 10 values in your statement)
You don't seem to have declared a value for $table
As Fred -ii- has pointed out in his answer, you're missing mysql_query() to actually run it. I assumed you have it further down in your code, but it's missing from the post, which is causing some confusion...
Also, consider updating to use mysqli instead of mysql functions.
what are you echoing $query for?
You do not have any reason to do that except if you just want to use it as a string variable.
it should be mysql_query($query);
What is the exact "database error" error you are getting?
I suggest reading this article about PDO
If you can't insert the data correctly, this might be your problem too.
I'm also getting this error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' , , '',128745)' at line 1
I've already used isset() and !empty() functions. All my variables are being declared before being used. I've also searched a lot and still couldn't solve this problem. PLease please help me. I'm stuck here. Any help will be of great use to me. Thanks.
Here's the code:
<?php
$authorized = false;
session_start();
include('config.php');
if(isset($_SESSION['crnumbers']) && isset($_SESSION['passwords']))
{
$authorized = true;
if(isset($_POST["submit"]) && !empty($_POST["submit"]))
{
$ScdDate = mysql_real_escape_string($_POST['ScdDate']);
$ScdMonth = mysql_real_escape_string($_POST['ScdMonth']);
$ScdYear = mysql_real_escape_string($_POST['ScdYear']);
$DName = mysql_real_escape_string($_POST['DName']) ;
$ScdTime = mysql_real_escape_string($_POST['ScdTime']);
}
$crnumber = mysql_real_escape_string($_SESSION['crnumbers']);
$sql = mysql_query("INSERT INTO schedule(ScdDate,ScdMonth,ScdYear,ScdTime,crnumber,DName)VALUES($ScdDate, $ScdMonth, $ScdYear, '$ScdTime', $crnumber, '$DName')");
if(!$sql)
{
die('There is some error. Damn it! ' .mysql_error());
}
header("location: http://localhost/Alok/Health%20Care%20Project\GUI\patientGUI2.php");
}
else if(!$authorized)
{
header("location:");
exit();
}
?>
The problem, as it seems, is that the variables used in the INSERT query aren't containing valid data and might be set to empty and therefore breaking the INSERT query.
There are 2 options that you can use here:
A] Try to use the below assignment syntax; it sets the given value if it is not-empty otherwise sets it to 0
$ScdDate = (!empty($_POST['ScdDate'])) ? mysql_real_escape_string($_POST['ScdDate']) : 0;
$ScdMonth = (!empty($_POST['ScdMonth'])) ? mysql_real_escape_string($_POST['ScdMonth']): 0;
$ScdYear = (!empty($_POST['ScdYear'])) ? mysql_real_escape_string($_POST['ScdYear']) : 0;
$DName = (!empty($_POST['DName'])) ? mysql_real_escape_string($_POST['DName']) : '';
$ScdTime = (!empty($_POST['ScdTime'])) ? mysql_real_escape_string($_POST['ScdTime']) : '';
B] Enclose all your values in single-quotes in the query
$sql = mysql_query("INSERT INTO schedule(ScdDate,ScdMonth,ScdYear,ScdTime,crnumber,DName)VALUES('$ScdDate', '$ScdMonth', '$ScdYear', '$ScdTime', '$crnumber', '$DName')");
Hope the above helps!
By the way, the error given in the question isn't perhaps in sync with the query; the last value in the query is $DName enclosed in single quotes but the last value in the error isn't enclosed in single-quotes. I might be incorrect though ;-)
You're checking $_POST["submit"] existence, but not $_POST["ScdTime"]'s. That's why the notice remains. Concerning your MySQL error, the comments let on your question quite answer it.
You need to use isset() on every variable that might be used later in the code :)
<?php
if(isset($_POST["submit"])) &&
isset($_POST['ScdDate']) &&
isset($_POST['ScdMonth']) &&
isset($_POST['ScdYear']) &&
isset($_POST['DName']) &&
isset($_POST['ScdTime']))
// We're good!
The correct way would be:
if(array_key_exists('crnumbers', $_POST)) {}
Also make sure you check ALL array keys. That's causing the second error.
I have a problem with this line of code - I have spent most of the day trying to get this resolved - can any one help?
Here is the code that is causing the problem form what I can see! The problem is around the $qry...
$qry = "INSERT INTO members (employer, flat) VALUES('$employ','$address') WHERE login='$_login'";
$result = #mysql_query($qry);
//Check whether the query was successful or not
if($result) {
header("location: member-profile.php");
exit();
}else {
die("Query failed");
}
?>
ERROR showing is:
( ! ) Notice: Undefined variable: _login in C:\wamp\www\123456\update.php on line 67
Thanks all.
First variable $_login is Undefined, and second, it seems you are trying to update.
You do not user WHERE for SELECT query.
If you want to update, it then your query should very much like this:
$sql = 'UPDATE table SET username = '$username' WHERE id = $_login;
variable $_login means, pretty much, the variable $_login is not defined. You must give it a value, before you can you expect it to work in your query.
INSERT doesn't allow the WHERE attribute, you need to use UPDATE instead
"UPDATE members SET employer='$employ', flat='$address' WHERE login='$_login'"
Be sure to prevent SQL injections and since mysql_* functions are deprecated you should switch to MySQLi or PDO
As for the error itself, you need to check if the variables are defined that you are using
if (!isSet($_login))
// do sth