I am trying to use PHP variables in an INSERT SQL statement. Ive seen previous answers to this but can not get mine to work. Here is the code..
mysql_query("INSERT INTO message (message_id, from, content) values ('', " . $uid . ", 'test message content')");
The main problem is that from is a reserved word and should be in backticks.
mysql_query("INSERT INTO message (message_id, `from`, content) VALUES ...");
But I'd also advise you to stop using the deprecated mysql_* functions. I'd recommend that you take a look at PDO and prepared statements with parameters.
If message_id is primary key, you don't need to include it in the query unless you have a value..
mysql_query("INSERT INTO message (`from`, `content`) values (" . $uid . ", 'test message content')");
There are at least three issues in your query. Two of them are syntax errors and one is a huge vulnerability.
To make the query work, you should write it as follows:
mysql_query("INSERT INTO message (message_id, `from`, content) values ('', '" . $uid . "', 'test message content')");`
Here's a summary of the errors:
- As another user indicated, "from" is a keyword and you should not use it to name table columns. If you really want to use such name, you must use backticks to indicate it in the query.
- The value of $uid should be enclosed by single quotes.
- The third, and most important error, is that your query is vulnerable to SQL Injection. You should use prepared statements, which would protect you from such attacks.
Related
I'm getting the following error :
2016-04-26 15:11:56 --- DEBUG: Error ocurred where inserting user data to the legacy db :Database_Exception [ 0 ]: [1064] 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 ')' at line 1 ~ APPPATH/classes/database/mysqli.php [ 179 ]
For the php query :
$result = $usdb->query(Database::INSERT, "INSERT INTO users (id, `password`, group_id , active, created, updated) VALUES ({$user['id']}, {$user['password']}, {$user['group_id']}, {$user['active']}, {$user['created']}, {$user['updated']})");
Here are the column types :
id : int AI PK
password : varchar
group_id : int
active : tinyint
created : int
updated : int
You need to have single quotes ' around your values in your SQL query, assuming they're strings (not integers) in the database.
Columns and table references can be encapsulated with backticks, though they don't have to, assuming they're not using a reserved keyword. Values, on the other hand, generally need single quotes around them (unless, of course, you're preparing your values through prepared statements; or if you're certain the database schema uses the integer type).
Putting single quotes around integers works just as well, so it's probably safe just to surround any value with a single quote, like so:
$result = $usdb->query(
Database::INSERT,
"INSERT INTO users (id, `password`, group_id , active, created, updated)
VALUES (
'{$user['id']}',
'{$user['password']}',
'{$user['group_id']}',
'{$user['active']}',
'{$user['created']}',
'{$user['updated']}'
)
"
);
Note:
You should ALWAYS be using parameterized queries (prepared statements). It is extremely unsafe to inject raw PHP variables into a SQL query. If you have a variable with a single quote, it will break the logic of your SQL statement.
You can read more about prepared statements in the PHP manual.
So what your SQL should really look like is this:
$sql = "
INSERT INTO users (id, `password`, group_id , active, created, updated)
VALUES (
:id,
:password,
:group_id,
:active,
:created,
:updated
)
";
And then bind your actual values into the prepared statement.
Since the password column is of type VARCHAR the value $user['password'] should be encapsulated in single quotes. And since the rest of the columns are of type INT or TINYINT single quotes aren't necessary.
So your query should be like this:
$result = $usdb->query(Database::INSERT, "INSERT INTO users (`id`, `password`, `group_id` , `active`, `created`, `updated`)
VALUES (" . $user['id'] . ", '"
. $user['password'] . "', "
. $user['group_id'] . ", "
. $user['active'] . ", "
. $user['created'] . ", "
. $user['updated']
. ")");
You should use backticks (`) for table and column names, single quotes (') for strings. Backticks are only needed when your table name or column name is a MySQL reserved word, but it's a best practice to avoid reserved words.
Sidenote: Use PDO prepare to prevent your database from any kind of SQL Injection.
From the PDO::prepare
Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.
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 have an error with my insert into line, it's about this bad boy
mysql_query("INSERT INTO accounts('username', 'password', 'firstname', 'lastname', 'email')
VALUES($username, $password, $firstname, $lastname, $email)")
or die("Could not create account! <br/>" . mysql_error());
the error I am supplied with is the following:
Could not create account!
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', 'password', 'firstname', 'lastname', 'email') VALUES(test, test,' at line 1
I suspect it has something to do with the variables not being called correctly?
There are a variety of problems, so I'll summarize them:
INSERT INTO t1 ('col' -- note that 'col' is wrapped in quotes. This means that it attempts to insert into the string literal "col1" rather than the column name. Remove the quotes and replace them with backticks (or nothing)
The values themselves are not wrapped in quotes. You have VALUES(test -- this semantically means insert the value of column "test," which makes no sense. You actually need to wrap this one in quotes.
I'd venture to guess that none of the input parameters are properly escaped. You should use properly parameterized queries with PDO or mysqli.
My friend the fields in the querys shouldn't be quoted. Try this:
mysql_query("INSERT INTO accounts (username, password, firstname, lastname, email) VALUES($username, $password, $firstname, $lastname, $email)") or die("Could not create account!" . mysql_error());
Good luck
you don't have to use quotes ' in the query but backtick `
mysql_query("INSERT INTO `accounts` (`username`, `password`, `firstname`, `lastname`, `email`) VALUES('".$username."', '".$password."','". $firstname."', '".$lastname."', '".$email."')") or die("Could not create account! " . mysql_error())
insert into documentation
I would like to also to remember you that mysql_ functions are deprecated so i would advise you to switch to mysqli or PDO for new projects.
mysql_query is not recommended, soon to be deprecated. Probably best to use PDO or mysqli instead.
http://php.net/manual/en/function.mysql-query.php
But to answer your question, I believe it's because your column names are in single quotes(rather than backticks).
It's your values that need to be within single-quotes. You'll probably want to run mysql_real_escape_string on those variables too, to prevent SQL injection. Or just use PDO prepared statements instead.
http://php.net/manual/en/pdo.prepared-statements.php
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.
I'm by no means experienced in mysql and keep getting an error in this lines of code:
$sql= "INSERT INTO songs (unique_show_id, artist, date, year, city, state, venue, taper, transfered_by, source, mic_loc, lineage, uploaded_by, uploaded_on, show_notes, show_xml)
VALUES('$showId', '$artist', '$showDate', '$year, '$city', '$state', '$venue', '$taper', '$transferer', '$source', '$mic_loc', '$lineage', '$uploader', NOW(), '$show_notes', '$show_xml')";
//check to see if the query went through
if (!mysql_query($sql,$con)){
echo "query fail";
die('Error: ' . mysql_error());
}
I'm sure it's something simplistic, but I can't see where the error is. The error message I get is:
query failError: 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 'ipuhgbi', 'CA', '', '', '', '', '', '', 'danwoods', NOW(), '', '<show id=\'gm198' at line 2
Some of the values I'm inserting are NULL, but from what I've read I don't think that should be a problem. Any ideas?
Missing quote after $year.
When MySQL issues such an error (near bla di bla), the error is usually immediately before the string it mentions. In this case 'ipuhgbi' maps to $city, so you know it's right before '$city', and what do we see there? Voila, a missing quote.
You need to use mysql_real_escape_string() in each and every single one of your $variables.
Also, read this StackOverflow question carefully regarding SQL Injections.
It looks like the last single quote on the error line is not escaped.
you need to remember to sanitize all of the strings going into the query.
There are quite few things you need to be sure about:
You don't insert primary keys through queries (eg unique_show_id in your code)
For numbers you don't use single quotes.
It is better to use the set variant of inserting records which avoids count problems eg:
Use intval for numbers and mysql_real_escaps_string for strings to avoid injections issues as well as single quotes query erros.
insert into table set field='field_value', field2='field_value' // and so on