I have a query that looks at a list of files inside a folder and enters the names of everything into a database so I can control the sort when showing the images.
Now I had an image today which had a name of image123('2).jpg. The single quote caused my query from crashing so how can I get around this? To make things simpler I have made example scenario
I have list of 4 variables which have the following strings
$myVAR1 -- "MyName IS Leo";
$myVAR2 -- "MyName IS 'Tiger";
I am running a SQL query to enter them into a database
$sql = "INSERT INTO `names` (`StringID`, `StringValue`) VALUES (NULL, ' $myVAR1');";
$sql2 = "INSERT INTO `names` (`StringID`, `StringValue`) VALUES (NULL, ' $myVAR2');";
So how can I detect that the single quote is inside the string $myVar2 and how can I ignore it when entrying into the database?
You need to escape your data. Use prepared queries with PDO so you don't have to worry about this.
You are currently wide open to SQL injection.
At a minimum, use mysql_real_escape_string(), assuming you are using the standard MySQL library in PHP. It takes care of quotes, among many other things, escaping them properly so they will be inserted into your database.
Related
So Im reading in a RFID tag and wish to store the tag data into an sql database.
I cannot get it to store in the RFID field of my sql database without manually placing single quote marks around the tag data.
The RFID field is set to text in php myadmin.
How can I read the tag and have it automatically place single quote marks around the data??
<?php
mysql_connect("localhost" , "xxxxxxxxx", "xxxxxxx");
mysql_select_db("xxxxxxxxx");
$SQL = "INSERT INTO Track(RFID) VALUES (".$_GET["RFID"].")";
$result = mysql_query($SQL);
echo "uploaded".$_GET["RFID"];
?>
$SQL = "INSERT INTO Track(RFID) VALUES ('".$_GET["RFID"]."')";
This should work.
Modify the $SQL variable to include single quotes as follows:
$SQL="INSERT INTO Track(RFID) VALUES('".$_GET["RFID"]."')";
You need to place the quote marks "in your SQL syntax" because you have specified the RFID field of Track table as text which falls into the string category(along with varchar() and the other text variants).
Also consider using mysqli_* functions as mysql_* functions are depreciated and only good to be used in PHP 4.x versions; use a newer version if you are using the 4.x ones.
Thank You #hecate Yes that worked perfectly.
But I have taken into consideration what people have said about parameterized statements and will be changing my code to safegaurd against SQL injections. Still got a lot more learning to do!
I have an input field named "eventName". everytime I will put single quote (e.g uncle's birthday) it won't be inserted to the database. I mean no data at all will be posted to database. the system will just say that the event was saved but no data is being stored in the database.
You need to escape the single quote. The escape character used in this case of a '\', you can use inbuilt functions like mysqli_escape_string or add-slashes.
When you add a single quote in a variable and add it to a query, this will change your query by considering the single quote as a comment. e.g
Insert into Table ('name') values ('uncle's birthday');
Your query got ended at uncle and the part after that won't be considered, essentially this would result in failure. You should check what the error code as well depending on which database you are using.
Update:
$eventName = add_slashes($_POST['eventName']);
Rather than simply adding slashes, consider prepared statements, thus preventing SQL injection attacks. More details about this here: How can I prevent SQL injection in PHP?
It's good practice to escape values before writing them to your database.
$escapedName = mysqli_real_escape_string($_POST['eventName']);
My question of to day is. Do i need to escape PDO in my script?
$columns = implode(", ",$column);
$query = ''.$query.' '.$columns.' FROM '.$table.'';
$dbh_query = $dbh->prepare($query);
$dbh_query->execute();
$dbh_querys = $dbh_query->fetchAll();
return $dbh_querys;
The whole script can be found at.
https://github.com/joshuahiwat/crud/blob/master/control/query_connector.class.php
Can someone explain why do i need a escape at this time or why not.
I like to hear from you, thanks a lot!
The parts of your query that are dynamic are the table name and column names. You can't use bind functions for these parts of the query. Bind functions can be used only for the parts of the query that would otherwise be a simple value in an SQL query. Like a numeric constant, or a quoted string or quoted date literal.
To avoid SQL injection from dynamic table names or column names, you have the following choices:
Use values that are predefined in your class, or otherwise certain to be safe. Don't use external content from users or any other source.
Use escaping. Note that the function PDO::quote() doesn't do the kind of escaping you need for table names or column names.
Create a "allowlist" of known table names and the column names for the respective table, and compare the dynamic input to the allowlist. If it doesn't match the allowlist, raise an error.
First of all you need to understand that the word you are using - "escape" - is meaningless.
What you probably mean is "to make your query safe from SQL injection". But, unfortunately, there is no such magic "escaping" that will make some abstract query safe.
The traditional query building assumes that all the query parts beside data values are hard-coded, while data values are bound via placeholders, like this:
$query = 'SELECT col1, col2 FROM some_table WHERE id = ?';
$stmt = $dbh->prepare($query);
$stmt->execute([$id]);
$row = $stmt->fetch();
This kind of a query considered safe.
In your case of a dynamically constructed query, every part is potentially vulnerable.
And here it is very important to understand that a burden of sanitizing all the query parts is entirely on this function. You cannot dismiss the danger simply claiming that your data is coming from the trusted source. That's a slippery ground because people often have no idea whether their source is trusted or not.
So, if take your question as "Do I have to protect this code from SQL injection", than the answer is - YES, YOU HAVE.
In the meantime you are protecting only a small part of your query - the data values. So you still have to protect (this term is much better than "escape") all other parts.
On a side note, your code is connecting to database every time it runs a query, which is highly inefficient and makes it impossible to use some database features.
$tablename = "channel";
mysql_query("INSERT INTO '".$tablename."' (episode_name,episode_title,episode_date)
values ('$videoname','$videotitle','$date')");
In PHP a double quoted string literal will expand scalar variables. So that can be done like this
$sql = "INSERT INTO $tablename (episode_name,episode_title,episode_date)
values ('$videoname','$videotitle','$date')";
I assume you thought that the single quotes were requred around the table name, they are not in fact they are syntactically incorrect.
You may wrap the table name and the columns names in backtick like this
$sql = "INSERT INTO `$tablename` (`episode_name`,`episode_title`,`episode_date`)
values ('$videoname','$videotitle','$date')";
The reason that the Values(....) are wrapped in single quotes is to tell MYSQL that these are text values, so that is not only legal syntax but required syntax if the columns are defined as TEXT/CHAR/VARCHAR datatypes
However I must warn you that
the mysql_ database extension, it
is deprecated (gone for ever in PHP7) Specially if you are just learning PHP, spend your energies learning the PDO database extensions.
Start here its really pretty easy
And
Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared statement and parameterized statements
Dont use quotes arround table name or use backtick
mysql_query("INSERT INTO $tablename (episode_name,episode_title,episode_date)
values ('$videoname','$videotitle','$date')");
"INSERT INTO `$tablename` (episode_name,episode_title,episode_date) values ('$videoname','$videotitle','$date')";
OR
"INSERT INTO `".$tablename."` (episode_name,episode_title,episode_date) values ('$videoname','$videotitle','$date')";
I am trying to insert a data from a form which has about 1990 characters into mysql. How ever the insert is not working. when i var_damp the content of the variable is shows the correct content. When i set it to an empty string the insert works. I have done my research and still can't get ti to work. I am not trying to upload a file. This characters are from a textarea in my form.
Below is the insert code:
if (isset($_POST['val'])) {
$score = $_POST['val'];
$course = $_POST['course'];
$mysqli->query("INSERT INTO `evaluate` (`id`, `course`, `score`) VALUES (Null, '$course', '$score')");
Note: is score column has type TEXT in the database.
This is a common problem because most introductions to mysqli don't cover it right away even when it should be the first thing you learn. Inserting into any database, especially SQL, requires carefully escaping the values you're supplying. The way these are escaped varies depending on the platform, but the good news is that mysqli can handle it for you.
The key is using prepared statements:
$stmt = $mysqli->prepare("INSERT INTO evaluate (course, score) VALUES (?,?)");
$stmt->bind_param('ss', $_POST['course'], $_POST['val']);
$stmt->execute();
Now it's best to enable exceptions so that any errors are not ignored. Once in a while we all make little mistakes that can be a giant pain to track down if there isn't any warning about them. Exceptions make a lot of noise.
If you're just getting started with PHP and databases, you might want to evaluate using PDO which is significantly better than mysqli for a number of reasons, or a higher level database layer like Doctrine or
Propel which make using the database a lot more pleasant.
I have a single quote (') in the text and not escaping it meant that the SQL statement was been interpreted wrongly
The correct way to go, and you must always do this, is:
$score = $mysqli->real_escape_string($_POST['val']);
$course = $mysqli->real_escape_string($_POST['course']);
$mysqli->query("INSERT INTOevaluate(id,course,score)VALUES (Null, '$course', '$score')");