How to properly add apostrophes into a mySQL INSERT command - php

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'";

Related

PHP preg_replace() is returning null when string includes a single quote but works otherwise

The code below is very simple. PHP uses POST to collect a string from a form, which I am then looking to trim and run a preg_replace function which will strip any special characters except a single quote or a hyphen. Bare in mind that the entire code works fine without the involvement of the quotes or hyphen in the regex expression.
preg_replace("/[^\w\s'-]/", '', $raw_lemurName);
Those clean variables are then inserted into a database. Apache/2.4.37. MariaDB.
When I make lemurName a string like "Diademed Sifaka<>!", it works, and returns 'Diademed Sifaka'.
When I make it a string including a single quote, however, like "Coquerel's Sifaka" the operation doesn't complete and no information is inserted.
I have tested the regex expression on its own and it works fine, it seems that when you begin to involve SQL and databases that it ceases to work.
Worth noting:
using phpMyAdmin. If I insert the string on there it works fine so my database can hold those values.
Tried using mysqli_real_escape_string() in various places, but have had no luck, perhaps doing it wrong.
Reading around, I think it has something to do with SQL not allowing strings with single quotes being inserted and that the server automatically escapes single quotes in the post method.
Any ideas?
Much appreciated.
$raw_lemurName = isset($_POST['lemurName']) ? $_POST['lemurName'] : null;
$raw_lemurLat = isset($_POST['lemurLat']) ? $_POST['lemurLat'] : null;
$raw_family = isset($_POST['family']) ? $_POST['family'] : null;
//the regex expression below seems to be messing something up
$c_lemurName = trim(preg_replace("/[^\w\s'-]/", '', $raw_lemurName));
$c_lemurLat = strtolower(trim(preg_replace('/[^\w\s]/', '', $raw_lemurLat)));
$c_family = trim(preg_replace('/[^\w\s]/', '', $raw_family));
if (isset($_POST['submit'])) {
$query1 = "INSERT INTO `lemurs` (`id`, `lemur`, `latin`, `family`) VALUES (NULL, '$c_lemurName','$c_lemurLat','$c_family')";
$run_query = mysqli_query($connection, $query1);
if($run_query){
echo "Data has been inserted";
} else {
echo "Operation Unsuccessful";
}
header("location: index.php");
return;
}
This is a standard SQL injection problem. The issue stems from the way you are getting these variables into your query:
$query1 = "INSERT INTO `lemurs` (`id`, `lemur`, `latin`, `family`) VALUES (NULL, '$c_lemurName','$c_lemurLat','$c_family')";
Think about exactly what is happening here, all you are doing is concatonating strings together, so if $c_lemurName is ' - then your SQL will become:
[...] VALUES (NULL, ''', '[...]
This actually really opens you up to what is called an "injection attack". Basically, a malicious user could set $c_family to something like... ');drop table lemurs;-- - you are now executing an insert statement, and then a drop table statement, with the rest of your SQL being a comment.
There are several ways to combat this, the most frequently advised way is to look into paramaterised queries - which for the mysqli library have to be done through prepared statements. There's an example of this on the PHP docs page.
replace the single quotation marks from 2nd params area as well. use this.
preg_replace("/[^\w\s'-]/", "", $raw_lemurName);
hope it will work

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

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)

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 Escaping Single Quotes With mysqli_real_escape_string

When I am inserting into a database with mysqli_real_escape_string, I am finding that my single quotes are been escaped with \\ rather than \ which is causing my query to fail. See below:
NOTE: $link is my db connection var.
$string = mysqli_real_escape_string($link, "BEGIN testing quotes - don't use quotes END");
$query = "INSERT INTO table (field) VALUES ('".$string."')";
When I echo out my query, I get:
INSERT INTO table (field) VALUES ('BEGIN testing quotes - don\\'t use quotes END')
which is causing a SQL syntax error. I cannot seem to find a setting anywhere that can change this. If I copy the echo'd query into MySQL workbench and remove a \, the query insert's perfectly.
I have had a look through Stack Overflow and cannot find anything relating to this, and also searched through Google with no luck.
I have many queries that need escaping across my entire website. Could a setting be set to automatically apply escaping of strings pre-insert without having to go through and update all my variables? If not, Is there anyway I can alter the mysqli_real_escape_string function without having to manually check every string I insert for single quotes etc?
I appreciate any assistance with this.
As Krishna Gupta suggested, stripslashes resolved my issue:
$string = mysqli_real_escape_string($link, stripslashes("BEGIN testing quotes - don't use quotes END"));
Thanks.

Not able to insert string which contains '

I wrote a script to insert record in my DB. The only issue I am getting is when I try to store data which contains ' character then the script does not work and it does not store anything in the DB. For example John's Birthday , Amy's Home etc . Any solution to this problem which allows special character like ' to store in the DB and retrieving them without any harm to security?
mysqli_query($con,"INSERT INTO Story (desc)
VALUES ('$mytext')");
PHP's mysqli_real_escape_string is made specifically for this purpose. You problem is that quotes are being interpreted by MySQL as part of the query instead of values. You need to escape characters like this so they won't affect your query - this is what SQL injection is.
$mytext = mysqli_real_escape_string($con, $mytext);
// continue with your query
Manual: http://php.net/manual/en/mysqli.real-escape-string.php
Filter the variable part of the query through mysqli_real_escape_string.

Categories