I'm using this Code, to insert the data which is sent with POST into my database.
mysql_query("INSERT INTO pending
(name, alter, mail, kd, steam, spiele)
VALUES
('$_POST["name"]', '$_POST["alter"]', '$_POST["mail"]', '$_POST["kd"]', '$_POST["steam"]', '$_POST["spiele"]')");
but PHP keeps throwing the following error:
PHP Parse error: syntax error, unexpected '"', expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in /var/www/bewerben.php on line 34
I cant see the problem there, because i think the '"' is needed there?
You have a bad quote ordering. You can use curly bracers, to escape the variables:
mysql_query("INSERT INTO pending
(name, alter, mail, kd, steam, spiele)
VALUES
('{$_POST['name']}', '{$_POST['alter']}', '{$_POST['mail']}', '{$_POST['kd']}', '{$_POST['steam']}', '{$_POST['spiele']}')");
From the docs:
Complex (curly) syntax
This isn't called complex because the syntax is complex, but because
it allows for the use of complex expressions.
Any scalar variable, array element or object property with a string
representation can be included via this syntax. Simply write the
expression the same way as it would appear outside the string, and
then wrap it in { and }.
To further explain, we have two variables:
$fruit = 'Orange';
$sentence = "$fruits are my favorite fruit";
What I'm trying to get is: Oranges are my favorite fruit. However, this won't work. PHP will instead be looking for a variable called $fruits, and when it doesn't find it, it'll show an error.
So to complete the task properly, we have to wrap the variable in curly braces { }:
$fruit = 'Orange';
$sentence = "{$fruit}s are my favorite fruit";
Great! Now PHP will know where the variable name ends and the string starts.
P.S. I recommend using mysqli.
I'm not quite sure I have the rights to write this here, but I looked at your code & I noticed a problem:
You are using mysql_* which is deprecated since PHP 5.5.0.
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future.
Instead of mysql_* you can use PDO or MySQLi.
Here is a simple example of using MySQLi:
$mysqli = mysqli_init();
$mysqli->real_connect($db_host, $db_user, $db_pass, $db_name);
Then you can prepare your query:
$stmt = $mysqli->prepare("insert into table values(?, ?)");
Bind the params:
$stmt->bind_param("is", $param1, $param2);
We say that the first variable $param1 is an integer and $param2 is a string.
The last thing we need to do is to assign to those variables some values and execute the statement.
$param1 = 1;
$param2 = "somestring";
$stmt->execute();
You should wrap you $_POST variables in {} or escape double quotes in its' keys with \:
mysql_query("INSERT INTO pending
(name, alter, mail, kd, steam, spiele)
VALUES
('{$_POST["name"]}', '{$_POST["alter"]}', '{$_POST["mail"]}', '{$_POST["kd"]}', '{$_POST["steam"]}', '{$_POST["spiele"]}')");
or you can try this :
mysql_query("INSERT INTO pending
(name, alter, mail, kd, steam, spiele)
VALUES
('".$_POST["name"]."', '".$_POST["alter"]."', '".$_POST["mail"]."', '".$_POST["kd"]', '".$_POST["steam"]."', '".$_POST["spiele"]."')");
Try this
INSERT INTO pending
(name, alter, mail, kd, steam, spiele)
VALUES
($_POST["name"], $_POST["alter"], $_POST["mail"], $_POST["kd"], $_POST["steam"], $_POST["spiele"])
NEVER INSERT POSTED VALUES WITHOUT VALIDATION / SANITIZING INTO THE DB
Read about SQL injection : http://www.php.net/manual/en/security.database.sql-injection.php
Why don't you create a function so your code is more reusable?. It's always good to make a single place for reoccurring processes, like adding quotes to strings.
$sql = "INSERT INTO pending SET
name = ".quote($_POST['name']).",
alter = ".quote($_POST['alter']).",
mail = ".quote($_POST['mail']).",
kd = ".quote($_POST['kd']).",
steam = ".quote($_POST['steam']).",
spiele = ".quote($_POST['spiele']);
mysql_query($sql);
function quote($val) {
return "'".$val."'";
}
Also, I prefer using the SET colname = value method for sql, it makes for much more readable code.
Related
I'm using a developer to help me build a site - and I'm getting an error relating to a webform when I use the text: I'm
Further details:
“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 'm', team_member_pic = ''' at line 7”
that he can't solve. He's suggesting it's the version of MySQL (5.5.23) on my webhost (Hostgator) - because the code seems to work okay on his server with MYSQL 5.5.xx at (GoDaddy)
The code he's applying is as follows:
$insert = "INSERT INTO ".TABLE_PREFIX."host_manager_team_members SET
user_id = '".$_REQUEST['id']."',
team_member_firstname =
'".addslashes($_REQUEST['team_member_firstname'])."',
team_member_surname =
'".addslashes($_REQUEST['team_member_surname'])."',
team_member_email =
'".addslashes($_REQUEST['team_member_email'])."',
team_member_phone =
'".addslashes($_REQUEST['team_member_phone'])."',
team_member_desc =
'".mysql_real_escape_string($_REQUEST['team_member_desc'])."',
team_member_pic = '".$filepath."'";
mysql_query($insert) or die(mysql_error());
Can anyone give some guidance on what could be causing this error? Would really appreciate any thoughts/ideas you would have.
Use sprintf like this
$insert = sprintf("INSERT INTO ".TABLE_PREFIX."host_manager_team_members SET
user_id = '%s',
team_member_firstname =
'%s',
team_member_surname =
'%s',
team_member_email =
'%s',
team_member_phone =
'%s',
team_member_desc =
'%s',
team_member_pic = '%s'",$_REQUEST['id'],addslashes($_REQUEST['team_member_firstname']),addslashes($_REQUEST['team_member_surname']),addslashes($_REQUEST['team_member_email']),addslashes($_REQUEST['team_member_phone']),mysql_real_escape_string($_REQUEST['team_member_desc']),$filepath);
mysql_query($insert) or die(mysql_error());
Your code is just about as vulnerable as it can be:
Don’t use $_REQUEST, as you don’t know where the data is coming from. It is a combination of $_GET, $_POST and $_COOKIE, and it makes it very easy for a user to inject their own additional data by simply appending ?evilstuff=hahaha to the URL.
Don’t use mysql_ functions. They are deprecated and removed in PHP7. That’s good because MySQL4, for which the original functions were created, did not have the more secure features implemented later.
Don’t use addslashes. It a poor attempt to escape strings against the possibility of SQL injection. If you must do it the old way, use one of the real_escape_string functions. Better still:
Always use prepared statements when accommodating user data. Preparing the statement results in interpreting the SQL before data has been injected, so any additional data, even if it looks like SQL, will be treated as pure data only.
Finally,
It is much easier to use PDO, which has been available since PHP 5.
Here is an alternative using PDO & prepared statements:
$table=TABLE_PREFIX.'host_manager_team_members';
$insert = "INSERT INTO $table SET user_id = ?, team_member_firstname = ?,
team_member_surname = ?, team_member_email = ?, team_member_phone = ?,
team_member_desc = ?, team_member_pic = ?";
$prepared=$pdo->prepare($insert);
$prepared->execute(array(
$_REQUEST['id'],
$_REQUEST['team_member_firstname'],
$_REQUEST['team_member_surname'],
$_REQUEST['team_member_email'],
$_REQUEST['team_member_phone']
$_REQUEST['team_member_desc'],
$filepath
));
The SQL statement is much easier to debug when you can see it by itself.
Note that you do not put quotes around the string values in a prepared statement. This is because quotes are only required for strings when they are constructed in code. By the time the prepared statement gets the data, the string has already been constructed.
I have also used a double quoted string to allow the interpolation of a variable which is not user-generated.
I see that you’re using a quirky MySQL extension to the INSERT statement, which is by no means universally supported. Perhaps you should try the more standard syntax:
$insert = "INSERT INTO $table user_id (team_member_firstname,
team_member_surname, team_member_email, team_member_phone,
team_member_desc, team_member_pic)
VALUES(?,?,?,?,?,?)";
Finally, to answer your question, it is quite possible that the error is caused by the data itself. What you need to do is print the contents of your string generated string, and then run that though MySQL directly (possibly using the SQL tab in PHPMySQL).
So, even without doing any of the above, you should try:
print $insert;
exit;
Perhaps you could try this and post the results here.
Hello i'm a beginner so please at least try to give me a hint,a example.
English isn't my main language so please endure it.
If somebody type " Hello my name is J'hon ' the text don't insert in database, but if he type 'Hello my name is jhon' it does. I think it is something about '
Ok so i'm having the problem that if someone types
'Hello my name is J[color=#FF0000]'[/color]hon J'onz. ' is not inserted in the database..
This is the script:
mysqli_query($DB_H, "INSERT INTO tickets (name, continutscurt, continut,type,status) VALUES ('".$_SESSION['username']."', '".$_POST['titlu']."', '".$_POST['continut']."', $numar, 0)");
You should really use prepared statements when dealing with any kind of user-input. If you for any weird reason isn't using prepared statements, take a look at the function mysqli::real_escape_string. This will deal with special characters, such as ', which may break the SQL.
With using prepared statements, your code would look like
if ($stmt = $DB_H->prepare("INSERT INTO tickets (`name`, continutscurt, continut, `type`, `status`) VALUES (?, ?, ?, ?, ?)")) {
$stmt->bind_param("ssssi", $_SESSION['username'], $_POST['titlu'], $_POST['continut'], $numar, 0);
$stmt->execute();
$stmt->close();
} else {
echo mysqli_error($DB_H);
}
If you however want to use mysqli::real_escape_string, you'll need to bind the SESSIONs and POSTs to a variable where in you insert instead, like this (you can also do it directly in the query, but this makes for cleaner code).
$username = mysqli_real_escape_string ($DB_H, $_SESSION['username']);
$titlu = mysqli_real_escape_string ($DB_H, $_POST['titlu']);
$continut = mysqli_real_escape_string ($DB_H, $_POST['continut']);
$numar = mysqli_real_escape_string ($DB_H, $numar);
if (!mysqli_query($DB_H, "INSERT INTO tickets (`name`, continutscurt, continut, `type`, `status`) VALUES ('$username', '$titlu', '$continut', '$numar', 0")) {
echo mysqli_error($DB_H);
}
I also put backticks ` around name, status and type, as these are keywords in SQL. This isn't strictly necessary, but it's good practice with words that are listed as either reserved words or keywords, more info on this list of keywords.
You shouldn't take for granted that your queries are successful, so I added an if-block around them. Errors shouldn't be displayed unless in production/development.
References:
http://php.net/manual/en/mysqli.real-escape-string.php
http://php.net/manual/en/mysqli.prepare.php
How can I prevent SQL injection in PHP?
https://dev.mysql.com/doc/refman/5.7/en/keywords.html
The issue is SQL Injection.
You have potentially unsafe values being included within the SQL text.
To see this, break up the code a little bit.
$sql = "INSERT INTO tickets ...'" . $val . "' ... ";
echo $sql;
The echo is there just as a way to see what's going on, for you to examine the contents of the string containing the SQL text. And then take that string over to another client, and test it. And you will see what the the problem is.
... VALUES ( ..., 'J'onz. ', ...
isn't valid. That single quote is ending the string, so the string is just 'J', and the next part, MySQL is going to try to interpret as part of the SQL, not the string value. (This is a nefarious vulnerability. Cleverly constructed strings and wreak havoc on your application and your database.)
One approach to fixing that is to sanitize the values, so they can be safely included.
... VALUES ( ..., 'J\'onz. ', ...
^^
... VALUES ( ..., 'J''onz. ', ...
^^
As a simple demonstration try these queries:
SELECT 'J\'onz. '
SELECT 'J''onz. '
SELECT 'J'onz. '
(The first two will return the string you expect, and the third will cause an error.)
The take away is that potentially unsafe values that are going to included in the text of a SQL statement need to be properly escaped. Fortunately, the MySQL client library includes mysqli_real_escape_string function. Variables that may potentially contain a single quote character can be run through that function, and the return from the function can be included in the SQL text.
$sql = "INSERT INTO tickets ...'"
. mysqli_real_escape_string($DB_H,$val)
. "' ... ";
Again, echo out the $sql and you can see that a single quote has been escaped, either by preceding it with a backslash character, or replacing it with two sinqle quotes.
There's a much better pattern than "escaping" strings. And that's to use prepared statements with bind placeholders.
The SQL text can be a static string:
$sql = 'INSERT INTO mytable (mycol) VALUES ( ? )'
And then you msyqli_prepare the statement.
And then supply values for the placeholders with a call to mysqli_bind_param.
And then call mysqli_execute.
With this pattern, we don't need to mess with running the "escape string" function to sanitize the inputs.
I'm getting the error: Column count doesn't match value count at row 1
I think, normally this error occurs if the count of the columns and the values aren't equal, but in my code they are...(3).
This is my php code:
$tempsongtitel = $_POST['songtitle'];
$tempinterpret = $_POST['interpret'];
$templink = $_POST['link'];
$query = mysql_query("insert into tMusic (Songtitel, Interpret, Link) values ('$tempsongtitel, $tempinterpret, $templink')") or die(mysql_error());
You missed some quotes. Should be:
$query = mysql_query("insert into tMusic (Songtitel, Interpret, Link) values ('$tempsongtitel', '$tempinterpret', '$templink')") or die(mysql_error());
Otherwise, you were trying to insert all three POST values into the first field.
Moreover, the mysql_ extension has been deprecated and is on the way out and is highly discouraged, especially if you are creating new software.
AND I'll presume you are first sanitizing your data? You're not really taking user input and placing it directly into the database, are you? Even if you don't do any data validation, you should escape your data in the query... easiest and most foolproof way to do that is by using parameterized queries.
The root cause is that your values are all in one set of quotes instead of quoted individually. I think this is a pretty common error, and in my experience it is an easy mistake to make, but not immediately obvious when scanning over your code. You can fix it like this (quick fix, still using deprecated mysql, but with post values escaped):
$tempsongtitel = mysql_escape_string($_POST['songtitle']);
$tempinterpret = mysql_escape_string($_POST['interpret']);
$templink = mysql_escape_string($_POST['link']);
$query = mysql_query("insert into tMusic (Songtitel, Interpret, Link)
values ('$tempsongtitel', '$tempinterpret', '$templink')") or die(mysql_error());
If you can, it would be much better to update your code to use PDO. You could use a prepared statement like this:
$stmt = $pdo->prepare("INSERT INTO tMusic (Songtitel, Interpret, Link) VALUES (?, ?, ?)");
$stmt->bindValue(1, $tempsongtitel);
$stmt->bindValue(2, $tempinterpret);
$stmt->bindValue(3, $templink);
$stmt->execute();
Among the many benefits of using this database extension rather than the old mysql functions it should not be possible to make an error like this in your code. In the prepared statement, there are no quotes around the parameter markers, so if you have VALUES ('?, ?, ?'), or even VALUES ('?', '?', '?') You would get bind errors when trying to bind the values, and the problem would become apparent pretty quickly.
I've found that, even though it's not 100% necessary and it's more time consuming, properly quoting and backticking EVERYTHING helps prevent this from happening.
$myQuery = "INSERT INTO `tMusic` (
`Songtitel`,
`Interpret`,
`Link`
) VALUES (
'$tempsongtitel',
'$tempinterpret',
'$templink'
);";
$runQuery = mysqi_query($DBi, $myQuery) or die(mysqli_error($DBi));
The formatting you use is up to you but this helps me make sure I have a one to one relationship and that I've quoted everything.
Of course that's using mysqli_* in place of the deprecated mysql_* functions AND that's assuming you've set $tempsongtitel, $tempinterpret and $templink properly.
I'm trying to add data to a database using SQLite3 in PHP. I got it working without prepared statements but now I'm trying to make it safer. I'm not using PDO.
So far the following code doesn't work. It just inserts the words ":name" and ":email" into the database, instead of what their bound values should be:
$smt = $db->prepare("insert into names (name, email) values (':name', ':email')");
$smt->bindValue(':name', $var_name);
$smt->bindValue(':email', $var_email);
$var_name = ($_POST[post_name]);
$var_email = ($_POST[post_email]);
$smt->execute();
So I thought at first that this was because I have single quotes around :name and :email in the prepared statement. So I took those out. Now when I post the form, it just puts blank entries into the database, it doesn't insert the values of $var_name and $var_email
The statement is executing, it's just not binding the variables properly I don't think. What have I done wrong?
You managed to confuse binding functions.
It is bindParam have to be used if you don't have your variable assigned yet.
While bindValue have to be used with existing value only.
Also, you should turn error reporting ON
You don't need intermediate variables, you must do this:
$smt = $db->prepare("insert into names (name, email) values (':name', ':email')");
$smt->bindValue(':name', $_POST['post_name'], SQLITE3_TEXT);
$smt->bindValue(':email', $_POST['post_email'], SQLITE3_TEXT);
$smt->execute();
As documented in SQLite3Stmt::bindValue() value is binded instantly, not as SQLite3Stmt::bindParam() that gets the value of the variable at execute() time. So the problem is that that variables are empty when the statement is executed.
Remember:
You don't need to add parentheses on variable assignment: $a = ($b); -> $a = $b;
You MUST quote variable key name. Otherwise PHP will try to look for a constant with this name and will throw a warning if it doesn't exists... but will assign a erroneous key value if it exists!! $_POST[post_name] -> $_POST['post_name']
I'm not sure why this has stumped me. I have the following code
$website = "http://www.google.com";
$name = "Person";
if(!empty($website) {
$name = "[url=$website]$name[/url]";
}
Then i try to insert that into mysql. I tried adding mysql_real_escape_string to both $website and $name (after the if statement), thinking the "/url" might also cause problems.
$name = mysql_real_escape_string($name);
Still no luck though. Any advice? What am I missing? It's giving me this error
"Parse error: syntax error, unexpected '/', expecting T_STRING or T_VARIABLE or T_NUM_STRING"
try
if(!empty($website)) {
$name = "[url={$website}]{$name}[/url]";
}
then use,
mysql_real_escape_string ($name);
This is a PHP syntax problem.
The parser thinks $name[ is the start of a array reference you have to add curly bracelets to tell the parser where the variable name starts and end:
"[url={$website}]{$name}[/url]"
There wont be any problem at all. When reading from database you should then put stripslashes() around your value.
e.g.
$query = "SELECT field FROM table";
$row = mysql_fetch_array(mysql_query($query));
echo(stripslashes($row['field']));
And your output will be the same like YOUR input.
Make sure you're quoting values you send into a query, like so:
$sql = "INSERT INTO table (column) VALUES ('$value')";
Whatever is in $value gets passed into the query. If you leave out the quotes, bad things may happen even if you use mysql_real_escape_string(). Inside strings, forward slashes do not have any special meaning in MySQL, and so mysql_real_escape_string() leaves them intact. This is not a bug, but the documented, correct behaviour. Basically, you need to quote all values in your query.
However, the best solution IMHO is to use PDO and its parametrized queries instead of the mysql_XXX API. It's a bit more complicated (not much though), and it allows you to pass parameters into a query through an associative array, doing all the escaping and quoting you need for you.
Are you putting quotes around the value you want to insert? This will work
INSERT INTO table_name (column_name)
VALUES ('[url=$website]http://www.google.com[/url]')
This will fail
INSERT INTO table_name (column_name)
VALUES ([url=$website]http://www.google.com[/url])
So you might have in you php
$query = "INSERT INTO table_name (column_name) VALUES ('$name')";
// DO MYSQL_QUERY