I'm trying to add some simple user data into a database via a webpage written in PHP, but the following code (more specifically, line three) breaks the page. Am I using the wrong MySQL function? I'm pretty sure my query is formatted correctly.
mysql_query("CREATE TABLE stats ( userAgent CHAR(20) )");
$userAgent = $_SERVER["HTTP_USER_AGENT"];
mysql_query("INSERT INTO stats VALUES ("$userAgent"));
The PHP error can be fixed like this (note the dot, it's used to "glue" the strings together):
mysql_query("INSERT INTO stats VALUES (".$userAgent.")");
Also, you should do some SQL Injection protection, the user-agent string is user-defined (there are tools to modify it), so it needs to be sanitized. Further, the user-agent is a string so you need to put it in between single quotes.
mysql_query("INSERT INTO stats VALUES ('" . mysql_real_escape_string($userAgent) . "')");
Another important thing would be error handling - echoing the error description is necessary to find bugs in your SQL syntax.
mysql_query("INSERT INTO stats VALUES ('" . mysql_real_escape_string($userAgent) . "')")
or die("MySQL Error: " . mysql_error());
Should be:
mysql_query("INSERT INTO stats VALUES (".$userAgent.")");
Eton B. has the right answer, but please note that the code you've written will leave you at the mercy of little Bobby Tables.
DON'T DO THIS
Are you escaping your $userAgent variable?
Data must be "cleaned" before going anywhere near your database.
<?php
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
OR die(mysql_error());
// Clean
$userAgent = mysql_real_escape_string($_SERVER["HTTP_USER_AGENT"]);
// Query
mysql_query("INSERT INTO stats VALUES ($userAgent)");
?>
Related
I'm trying to add information to a MySQL table using the following PHP code. (The input the name and text from an HTML5 basic web form.) Probably a syntax issue?
<?php
include "dbinfo.php"; //contains mysqli_connect information (the $mysqli variable)
//inputs
$name = $_GET["name"];
$text = $_GET["text"];
$sqlqr = 'INSERT INTO `ncool`.`coolbits_table` (`name`, `text`, `date`) VALUES ("$name", "$text", CURRENT_TIMESTAMP);'; //the query. I'm pretty sure that the problem is a syntax one, and is here somewhere.
mysqli_query($mysqli,$sqlqr); //function where the magic happens.
?>
No error is thrown. A blank screen results, and a row with "$name" and "$text" is added to the MySQL table.
First of all: you should use mysqli prepared statements to prevent SQL injection attacks. It is not safe to use user input within a query without proper escaping. Prepared statements are useful to prevent this.
Second: you should learn how string quoting works in PHP, single quoted strings and double quoted strings are different
I would recommend to read the PHP documentation about string quoting.
This is how your code should look (with added SQL Injection protection):
<?php
include "dbinfo.php"; //contains mysqli_connect information (the $mysqli variable)
//inputs
$name = mysqli_real_escape_string($_GET['name']);
$text = mysqli_real_escape_string($_GET['text']);
$sqlqr = "INSERT INTO `ncool`.`coolbits_table` (`name`, `text`, `date`) VALUES ('" . $name . "', '" . $text . "', CURRENT_TIMESTAMP);";
mysqli_query($mysqli,$sqlqr); //function where the magic happens.
?>
Take a look at what I've done. Firstly I've escaped the user input you're retrieving into the $name and $text variables (this is pretty much a must for security reasons) and as others have suggested you should preferably be using prepared statements.
The problem is that you weren't surrounding string values with single quotes ('), which is a requirement of the SQL syntax.
I hope this helps to answer your question.
So , am creating a password change table
When some 1 changes pass , i insert his username, newpass and the confirmation code in PassChange table, (so i send him a confirmation e-mail after) the idea is simple and here's the code i use
$insertResult=mysql_query("INSERT INTO TempChangePass (UserName, NewPass, ConfirmationCode) VALUES ('$UserName', '$newPass', '$code')") or die (mysql_error());
though i get 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 'username'', '4da59df8d4007807e7230e0881fbf774', '16585482')' at line 1
NOTE: All the columns format in the table is set to varchar.
The connection to mysql database is fine, the table name is currect.
This problem is driving me crazy , i just can't figure out where the problem is, if anyone here can help me will be very thankful :)
and thanks in advance.
EDIT:
I actually got it solved, and just for people who visit this post by searching for solutions, if you got similar problem with your sql command, try echo it, and see how exactly the string is moved to the database :-) , happy coding everyone.
And sorry if I wasted any of your time :) am just very new to php & mysql :D
Remove the single quotes around your variables. PHP is interpreting them as strings.
$insertResult=mysql_query("INSERT INTO TempChangePass (UserName, NewPass, ConfirmationCode) VALUES ('" . $UserName. "', '" . $newPass. "', '" . $code . "')") or die (mysql_error());
Additionally, you might want to do something like this:
$sql = "INSERT INTO TempChangePass (UserName, NewPass, ConfirmationCode) VALUES ('" . $UserName. "', '" . $newPass. "', '" . $code . "')";
echo $sql;
Take that echo, and try to manually run it.
Looks something like sql inyection. I'm quite sure your $username is $username = "username'". Look at the single quote. So the query became:
$insertResult=mysql_query("INSERT INTO TempChangePass (UserName, NewPass, ConfirmationCode) VALUES ('username*''*, '4da59df8d4007807e7230e0881fbf774', '16585482')") or die (mysql_error());
Did you try to do the Query one column by one ?
i mean :
INSERT INTO TempChangePass (UserName) values ( '$UserName' );
then add it up ?
Works for me mostly when I get errors ;)
Just an idea.
It looks like you have single quotes in your actual username -- you're actually passing in 'username' instead of just username. Try removing those, see if it will work after that.
The recommended way to deal with this issue (and prevent SQL injection) is to use prepared statements, however if you really want to, you could probably do this inline using mysql_real_escape_string($UserName) (reference)
Try this:
$insertResult=mysql_query("INSERT INTO TempChangePass(UserName, NewPass, ConfirmationCode) VALUES('$UserName', '$newPass', '$code')") or die (mysql_error());
You have some extra spaces in your SQL.
try using a sanitizing script before you make the query.
use
mysql_real_escape_string()
EDIT
You should now use the MySQLi version
mysqli_real_escape_string()
or OOP method
mysqli::real_escape_string()
Why use MySQLi instead of MySQL?
Here is my code - I'm attempting to attach a bunch of user_id 's to a piece of content.
if (empty($errors)) // If everything's OK.
{
foreach($_POST['userId'] as $row)
{
$query = " ('".$row[learner_id]."', '".$postId."', '".$id."' ),";
}
$query = substr_replace($query,"",-1);
$mysql_return = mysqli_query("INSERT INTO subs (userId, postId, account_id ) VALUES ".$query) or die(mysql_error());
}
Would love any help you could give - it's not working...
And how's it not working? Syntax error? Silently puking? You're not escaping your POST data, so if any of those contain at least one single quote, that'll cause a syntax error right there, plus leaving you wide open for sql injection attacks.
Or maybe a foreign key check is failing... many possibilities, but you haven't given us nearly enough info to tell. What error message(s) are you getting?
Ok, I see several issues:
You are not using parameters or escaping, opening yourself up WIDE to sql injection attacks. See mysqli_real_escape_string.
What are you possibly sending to $_POST['userId'] that would make itself an array?
Unless learner_id is a constant, then this is a syntax error. If it is an array key, put it in quotes.
Where are $postId and $id coming from ?
The first parameter to mysqli_query is the identifier returned by mysqli_connect, whereas you're just giving it the query directly.
It should be like this,
$link = mysqli_connect("host", "user", "pass", "db");
$mysql_return = mysqli_query($link, "INSERT INTO subs (userId, postId, ac...
Please don't send me a link to php.net referencing mysql_real_escape_string as the only response. I have read through the page and while I understand the general concepts, I am having some trouble based on how my INSERT statement is currently built.
Today, I am using the following:
$sql = "INSERT INTO tablename VALUES ('',
'$_SESSION['Member1FirstName'],
'$_SESSION['Member1LastName'],
'$_SESSION['Member1ID'],
'$_SESSION['Member2FirstName'],
'$_SESSION['Member2LastName'],
'$_SESSION['Member2ID'] ....)
and the list goes on for 20+ members with some other values entered. It seems most people in the examples already have all their data stored in an array.
On my site, I accept form inputs, action="" is set to self, php validation takes place and if validation passes, data is stored into SESSION variables on page 2 then redirected to the next page in the process (page 3) (approximately 8-10 pages in the whole process).
You seem to already know that you should be using mysql_real_escape_string but I guess you don't know how to use. You need to apply it for each user supplied string you insert into your SQL. The following example should clarify this:
$sql = "INSERT INTO tablename VALUES ('', '" .
mysql_real_escape_string($_SESSION['Member1FirstName']) . "', '" .
mysql_real_escape_string($_SESSION['Member1LastName']) . "', '" .
etc..
Or alternatively look into prepared statements and bind parameters for an easier (and faster) solution.
1) you're missing your closing single-quote and vars aren't replaced inside of single quotes.
2) mysql_real_escape_string is the answer, but try it with sprintf:
$sql = sprintf("INSERT INTO tablename VALUES ('', '%s', '%s', '%d' )",
mysql_real_escape_string( $_SESSION['Member1FirstName']),
mysql_real_escape_string( $_SESSION['Member1LastName']),
$_SESSION['Member1ID']); // %d forced it as a digit
http://us2.php.net/manual/en/function.sprintf.php
Why can't you use mysql_real_escape_string?
You can also use a regexp to only allow certain characters that would be expected in a name
In accessing my database, I have the user fill out a form, and in the target page, the posted values are used in the resulting MySQL query.
$query = mysql_query("SELECT pass FROM database WHERE user='$_POST[user]'");
However, for some reason or another, MySQL doesn't like my using a $_POST variable in the command, and it only works if I define (for example) $user = $_POST['user'];, and then put $user directly in the SQL command.
On the other hand, I can use $_POST values in INSERT statements where specific column names are not required:
$query = mysql_query("INSERT INTO database VALUES ('foo', 'bar', '$_POST[user]'");
If I try an INSERT statement where attributes are defined (e.g. user='foo'), then the same problem appears.
What am I doing wrong in my SQL query that causes the command to error out when run, but works with the specific method of formatting an INSERT command?
Hopefully, it's not "tough luck, looks like you have to assign all of your posted values". Heh.
First of, watch out for SQL Injections!
Now, to answer your question try doing this instead:
$query = mysql_query("SELECT `pass` FROM `database` WHERE `user` LIKE '" . mysql_escape_string($_POST['user']) . "';");
You were doing a couple of things wrong:
using the = operator instead of LIKE operator
not enclosing the value in the SQL query with '
not enclosing the user index in the $_POST array with '
PS: You should use mysql_real_escape_string() instead of mysql_escape_string()!
You're simply inserting a variable into a string, so it shouldn't matter which command you're putting it into.
There are a few issues to point out.
One, you might want to use the {} format for array variables. You don't use quotes around the arrray key names in this format.
$query = mysql_query("SELECT pass FROM database WHERE user='{$_POST[user]}'")
Two, you'd never want to make a query like that because you are open to sql injection holes. Consider, what if $_POST['user'] was "cow';drop table database;--"?
You must either run mysql_real_escape_string on the POST input before putting it into your query, or check out using PHP PDO with prepared statements.
One way to do format your string which provides a bit of structure is to use sprintf.
$query=mysql_query(sprintf("SELECT pass FROM database WHERE user='%s'",mysql_real_escape_string($_POST['user'])));
Use PDO - it provides much better API to communicate with DB.
If you're using mysql_*() functions always remember to filter (mysql_real_escape_string()) any data that comes from untrusted source (like user)
Pay more attention to how your code looks like. Just compare the following listings:
$query = mysql_query("INSERT INTO database VALUES ('foo', 'bar', " . mysql_real_escape_string($_POST['user']) . ", " . mysql_real_escape_string($_POST['user']) . ", " . mysql_real_escape_string($_POST['user']) . ", " . mysql_real_escape_string($_POST['user']) . ")");
$query = sprinf('INSERT INTO database VALUES ("foo", "bar", "%s", "%s", "%s")',
mysql_real_escape(...), ...);
Do I have to explain which one is better to read, modify or understand?
Why not check and see what mysql_error() has to say about it? If your query is invalid, mysql_error() will return a nice blob of text telling you exactly what went wrong.
As for MySQL not liking the POST var if you insert it directly for some runs, but not others, then you should make sure you're using consistent data and setups for each test. If some test are done using a GET, then your POST vars will be empty. If you're using different user names for each test, then see if what's consistent between the ones that fail.
And as mentioned above, read up about SQL injection and how your query is just begging to be subverted by a malicious user.
Try
$query = mysql_query("SELECT pass FROM database WHERE user=" . mysql_real_escape_string($_POST['user']));
and
$query = mysql_query("INSERT INTO database VALUES ('foo', 'bar', " . mysql_real_escape_string($_POST['user']) . ")");
Its always a good idea to sanitize anything received through $_GET or $_POST