Why do you need a specific syntax to insert data into postgresql - php

I have found a way to insert data into a postgresql database using php. Therefore, I used the following syntax:
$sql = "INSERT INTO genes
(id,gene,plasmid,accessionnumber,plasmidname)
VALUES ('".$var_id."','".$var_gene."','".$var_ACC."','".$var_PN."')";
Why do you have to use quotes within quotes and adding a point before and after the variable?

The answer on the question is point concatenates your string, quotes you use to separate literal from variables. (Vao Tsun)

Related

How to properly add apostrophes into a mySQL INSERT command

I am trying to add some data into a MySQL database using a text area. However, when someone adds in an apostrophe it breaks the INSERT command because it acts as a single quote. How can this be fixed?
Here is what the command would look like if you stipped out all the variables that I am using.
INSERT INTO skills09 (name, birthday, skills) VALUES ('Tom Haverford', '31_02_1987', 'Being Awesome, Announcing cool things, Treatin' Yo Self, Failing');
As I was looking at this I had a thought.
Is it as simple as using double quotes around my variable names rather than single quotes? This seems like an easy fix but I have always used single quotes in MySQL.
you can escape the ' with a preceding '
INSERT INTO skills09 (name, birthday, skills) VALUES ('Tom Haverford', '31_02_1987', 'Being Awesome, Announcing cool things, Treatin'' Yo Self, Failing');
it's basically a dupe of
How do I escape a single quote in SQL Server?
if you gave more information on the language you're using or exactly how this sql statement is being formed by the users, I could give more information. for example, you would basically run the user's input through a function that would replace ' with '' (2 single quotes) right before sending it to the sql server.. in the sql server it will be correctly stored as just '
"escaping" the character is just a way for it to not count as the ending single quote, and allows it to be added in the insert.
PHP How to replace customers text area apostrophes with a escape character
$lastname = "O'Reilly";
$_lastname = mysqli_real_escape_string($lastname);
$query = "SELECT * FROM actors WHERE last_name = '$_lastname'";

Database syntax error escaping characters in Codeigniter 3

What is the best way to escape unwanted characters in order to avoid further database syntax errors when executing insert/update queries when submitting forms?
eg. $note = $this->db->escape( $data['note'] );
INSERT query renders a further syntax error.
ie.
$this->db->query("INSERT INTO notes (note_id, note) VALUES ('$note_id','$note')");
as it mentioned in Codeignitier documentation when using query builder class
All values are escaped automatically producing safer queries.
so its safer to use query builder class for both error handling and security
Escaping Queries
It’s a very good security practice to escape your data before submitting it into your database. CodeIgniter has three methods that help you do this:
$this->db->escape() This function determines the data type so that it can escape only string data. It also automatically adds single quotes around the data so you don’t have to:
$sql = "INSERT INTO table (title) VALUES(".$this->db->escape($title).")";
$this->db->escape_str() This function escapes the data passed to it, regardless of type. Most of the time you’ll use the above function rather than this one. Use the function like this:
$sql = "INSERT INTO table (title) VALUES('".$this->db->escape_str($title)."')";
$this->db->escape_like_str() This method should be used when strings are to be used in LIKE conditions so that LIKE wildcards (‘%’, ‘_’) in the string are also properly escaped.
$search = '20% raise';
$sql = "SELECT id FROM table WHERE column LIKE '%" .
$this->db->escape_like_str($search)."%' ESCAPE '!'";
Note:
The escape_like_str() method uses ‘!’ (exclamation mark) to escape special characters for LIKE conditions. Because this method escapes partial strings that you would wrap in quotes yourself, it cannot automatically add the ESCAPE '!' the condition for you, and so you’ll have to manually do that.

MYSQL, PHP: Insert records from one database to another

I have a necessity to insert some record from one table1 in database1 to another table2 in database2.
So far I have this..
$records_r = mysqli_fetch_assoc(mysqli_query($conn_r, "SELECT * FROM `export` WHERE ID < 100"));
$columns_r = implode(",",array_keys($records_r));
$values_r = implode(",",array_values($records_r));
$import = mysqli_query($conn_i,"INSERT INTO NOTimport ($columns_r) values ($values_r)");
if (!$import) {
printf("Error: %s\n", mysqli_error($conn_i));
exit();}
It gives me the error:
Error: You have an error in your SQL syntax;
This is how the syntax looks:
INSERT INTO `NOTimport` ('xx,xx,xx,xx,xx,xx,xx,xx') values ('11,'11,E,2079,1931,xx,xx,x')
I am 99% sure that single quotes are causing the error, but why are there?
As per your original post https://stackoverflow.com/revisions/31116693/1 and completely overwriting your original post without marking it as an edit:
You're using the MySQL import reserved word
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
It needs to be wrapped in ticks
INSERT INTO `import` ($columns_r) values ($values_r)
or rename that table to something other than a reserved word.
Plus, $values_r may require to be quoted and depending on what's being passed through $columns_r, you may need to use ticks around that.
I.e.:
INSERT INTO `import` (`$columns_r`) values ('".$values_r."')
Even then, that is open to SQL injection.
So, as per your edit with these values values ('11,'11,E,2079,1931,xx,xx,x'), just quote the values since you have some strings in there. MySQL will differentiate between those values.
Escape your values:
$values_r = implode(",",array_values($records_r));
$values_r = mysqli_real_escape_string($conn_r, $values_r);
or $conn_i I'm getting confused as to which variable is which here. Be consistent if you're using the same db.
Edit:
As stated in comments by chris85, use prepared statements and be done with it.
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements
import is a reserved word in MYSQL. So, you need to use backticks (``) around it in your query.
So rewrite as follows:
$import = mysqli_query($conn_i,"INSERT INTO `import` ($columns_r) values ($values_r)");
Without Using PHP you can use MySql Query Which Will Perform Insert Operation As:-
$columns_r='`name`,`class`';
mysqli_query($conn_i,"INSERT INTO `import` ({$columns_r}) select {$columns_r} from `export`");

INSERT INTO sql query is using variable string rather than field name

Getting really confused surrounding this INSERT INTO. It should insert three fields into the table, userID, activateKey and isActivated.
The activateKey is a 25 letter randomly generated key such as 63n20kw24ba1mlox34e8n2awv
The userID comes from another table and is set by auto_increment.
The isActivated is always 0 at this stage.
It seems like quite a simple INSERT statement
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated) VALUES (".$userID.",".$activateKey.",'0')"))
{
echo("Error description: " . mysqli_error($con));
}
However it doesn't work when I include the $activateKey field. What it does is try to search the string variable $activateKey as a column name. The error I get is:
Error description: Unknown column '63n20kw24ba1mlox34e8n2awv' in 'field list'
Of course there is no such column as 63n20kw24ba1mlox34e8n2awv, this is the data I'm trying to insert, hence why it's in the VALUES section. Any ideas why it's trying to search this as the column name?
Edit to clarify: the var is activateKey, the column name is activationKey
I would put the query in a different variable to avoid confusion, and PHP automatically substitutes variable names in strings in double quotes.
Try this:
<?php
$query = "INSERT INTO activations (userID,activationKey,isActivated) VALUES($userID,'$activateKey','0')
if (!mysqli_query($con,$query)
{
echo("Error description: " . mysqli_error($con));
}
You are not surrounding the values with quotes, that's why they get interpreted as variable names.
Use single quotes, like this:
"INSERT INTO activations (userID,activationKey,isActivated) VALUES
('".$userID."','".$activateKey."','0')"
However, be aware that stringing together query strings exposes you to SQL injection attacks, if that's a concern in your code you should use parameterized queries. In fact, using parameterized queries is always better.
Change your query to this:
"INSERT INTO activations
(userID,activationKey,isActivated)
VALUES ('$userID','$activateKey','0')"
You dont need to use the concatenation (.) operator as variables will be interpolated into the string.
The single quotes tell mysql to treat the variables as literals instead of column names.
As a side note you would be better to use parameterized queries. See How can I prevent SQL injection in PHP?
Solved!
It was a case of not properly wrapping the dynamic fields (the vars in the VALUES section) in ticks:
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated) VALUES ('".$userID."','".$activateKey."','0')"))
Instead of
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated) VALUES (".$userID.",".$activateKey.",'0')"))
Might be a difficult one to spot. The variables still need to be 'in ticks' or they won't register as strings.
As activationKey is a string column, you must use single quotes for $activationKey.
Try with:
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated)
VALUES (".$userID.",'".$activateKey."','0')"))

Most efficient way to use arrays in MySQL statements?

Alright, take this for example:
$array['key'] = 'value';
$SQL = "SELECT column FROM table WHERE column='{$array[key]}'";
That's how I've been doing it, but of course if I were to enable E_ALL error reporting, I'd get a notice about using the undeclared constant, and it would assume 'key' instead of a constant.
As such, I assume that's not the proper or more efficient way to do it, so what would be the most efficient way of doing that SQL query (or other relevant string)?
Actually, if you lookup the PHP string quoting rules, if you omit the quotes around the key inside {} it will be interpreted as a constant. However, if you omit the {} and the quotes, a simple array index will be properly interpreted without issuing a notice.
PHP double-quoted string parsing rules (The relevant examples are in the Variable Parsing section)
I tend to prefer surrounding with {} for readability:
// Inside {}, you must quote the array key or it will be interpreted as a constant
$SQL = "SELECT column FROM table WHERE column='{$array['key']}'";
But this is also valid and should not issue notices:
// Without {}, don't quote the array key and it will be correctly parsed.
$SQL = "SELECT column FROM table WHERE column='$array[key]'";
Note that the best way to pass variables into SQL queries is to use an API that supports prepared statements instead of concatenating in variables
You need to quote key.
$SQL = "SELECT column FROM table WHERE column='{$array['key']}'";
I always prefer to do it that way:
$SQL = "SELECT column FROM table WHERE column='".$array['key']."'";
and I have never run in trouble with that.
If you re-use the sql, binding would be an advantage:
http://nz.php.net/manual/en/pdostatement.bindparam.php
HTH

Categories