This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 9 years ago.
I see that this question has been asked a fair amount of times, but I'm a little confused by the responses. I was hoping that somebody could please take a look at the code below and help me with how to insert text, that contains an apostrophe, into a MySQL database. The two things that are likely to contain apostrophes are full_desc and meta_desc. Thanks!
Also, I realize that this is prone to MySQL Injection, so any pointers on securing it will also be greatly appreciated. Thanks again!
<?php
$con=mysqli_connect("mysql.legfly.com","username","password","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//sql
$sql="INSERT INTO races (event_name, event_date ,start_time, entry_fee, sanctioned,location, address, city, state, zipcode, country, sport, special_info, distance, race_url, reg_url, print_url, event_phone, event_email, meta_desc, full_desc, course_info, directions, other_info, perma_url, perma_year)
VALUES
('$_POST[event_name]','$_POST[event_date]','$_POST[start_time]','$_POST[entry_fee]','$_POST[sanctioned]','$_POST[location]','$_POST[address]','$_POST[city]','$_POST[state]','$_POST[zipcode]','$_POST[country]','$_POST[sport]','$_POST[special_info]','$_POST[distance]','$_POST[race_url]','$_POST[reg_url]','$_POST[print_url]','$_POST[event_phone]','$_POST[event_email]','$_POST[meta_desc]','$_POST[full_desc]','$_POST[course_info]','$_POST[directions]','$_POST[other_info]','$_POST[perma_url]','$_POST[perma_year]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Your race is added!";
mysqli_close($con); ?>
Thanks again!
If you add a back-slash before the apostrophe, it will escape it so it's treated as text rather than as part of the query.
E.g. INSERT INTO tablename (id,text) VALUES ('0','This row\'s the first')
It's only an example for how apostrophes can still be inserted. For a more programmed approach, mysqli_real_escape_string/mysql_real_escape_string does the trick on strings before you use them in a query.
Related
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 5 years ago.
I have a registration form on a website. I'm using a pretty standard php form to send the form submission to me via email. I'm using a formhook to also insert those form entries into a mysql database. The only problem I have is when someone tries to include single or double quotes in a field. For instance one field asks for verbiage for the back of a t-shirt. Some people just seem to want to add quotes to their verbiage. This causes the information to not be inserted into the database. I'm somewhat new to sql and have been reading up on escaping quotes but still not grasping the solution. See my form below .. this is the formhook that inserts the information into the database. Is there a statement I can add to the php code that will allow both single and double quotes? Thank you!
$con=mysql_connect($hostname,$username,$password);
if(! $con)
{
die('Connection Failed'.mysql_error());
}
mysql_select_db($database,$con);
//if submit is not blanked i.e. it is clicked.
{
$sql="insert into sponsors2015(realname, sponsorname, email, phone, shirtnameverbiage, platinum_2500, gold_2000, silver_1500, bronze_1000, beverage_500, longdrive_200, closest_to_pin_200, par3_150, hole_100) values('".$_REQUEST['realname']."', '".$_REQUEST['sponsorname']."', '".$_REQUEST['email']."', '".$_REQUEST['phone']."', '".$_REQUEST['shirtnameverbiage']."', '".$_REQUEST['platinum_2500']."', '".$_REQUEST['gold_2000']."', '".$_REQUEST['silver_1500']."', '".$_REQUEST['bronze_1000']."', '".$_REQUEST['beverage_500']."', '".$_REQUEST['longdrive_200']."', '".$_REQUEST['closest_to_pin_200']."', '".$_REQUEST['par3_150']."', '".$_REQUEST['hole_100']."')";
$res=mysql_query($sql);
if($res)
{
Echo header('Location: sponsor-registration-success.php');
}
Else
{
Echo header('Location: sponsor-registration-problem.php');
}
}
First thing you should change on your codebase is the connection API. mysql_* functions are deprecated. There are another APIĀ“s like mysqli_ and PDO
http://php.net/manual/en/book.pdo.php
http://php.net/manual/de/book.mysqli.php
If your choice is going to PDO, the prepare method will escape your values, otherwise if your going with mysqli_ there is a mysqli_escape_string() function.
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 3 years ago.
I'm currently testing a html form which sends the data through php to the sql database. The problem I'm facing is special characters break the form and don't update the database. I haven't tested all the special characters but mainly ` and ' are the culprits. I've tried mysql_escape_string, preg_replace and add_slashes with no success. What am I missing?
$description = preg_replace('/[^A-Za-z0-9\ %&$=+*?()!.-]/', ' ', $_POST['description']);
$description = preg_replace("/[\n\r]/"," ",$description);
// Items Insert
foreach ($item as $index=>$value) {
$sqlItems .= "
INSERT INTO quote_items (quote_id, item, description, amount, gst)
VALUES ('$last_id', '$item[$index]', '$description[$index]', '$amount[$index]', '$gst[$index]');
";
}
Thanks in advance!
you can try this (a little dirty) but it should allow those 2 characters to be saved
$sqlItems .= '
INSERT INTO `quote_items` (quote_id, item, description, amount, gst)
VALUES ("'.$last_id.'", "'.$item[$index].'", "'.$description[$index].'", "'.$amount[$index].'", "'.$gst[$index].'");
';
EDIT: sorry had the quotes reversed
Can you post you DB call?
Those two characters in particular look like they would conflict in a DB call.
The ` is usually wrapped a table or column name
and the ' is usually wrapped around values.
Both of these would cause a problem but without code its hard to say
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 7 years ago.
Can someone please help me what is wrong with this syntax.
when i run this, it doesn't insert the values into the table.
Currently all the variables e.g $land, etc have a value.
in my database table, all except $nOwners,$id(int) are defined as varchar, .
Details:
I am using Mysqli
$sql= "INSERT into property_list (id, title_no, status, register_type, type,land_district, issue_date,guarantee_status,provisional,title_no_srs,title_no_head_srs, survey_reference, Maori_land, number_owners)
VALUES($id,'$title', '$status', '$register', '$type', '$land', '$issue_date', '$guarantee', '$provision', '$title_no_srs','$head_srs', '$survery', '$maori', $nOwners)";
if($conn->query($sql)!==false)
{
$flag=false;
echo "successfully inserted ";
}
Hmm, the column name status might be an issue, it is a reserved keyword in sql. Try another name and see if that fixes it.
https://www.drupal.org/node/141051
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
I've done some searching here and have not found what I'm looking for.
I've got a form that gets filled out, upon submitting it adds it to an SQL database (using PHP). However, if someone puts an apostrophe or single quote, it will blow up...I need to be able to either parse each text field to check for single quotes to escape them out or find some other way for this to work. Here is my SQL statement...if it helps.
$query = "INSERT INTO workshopinfo (Year, Presentername, email, bio, arrival, title, description, costyn, matcost, schedlimit, additionalinfo, typeofws, verified)" .
"VALUES ('$year', '$presentername', '$email', '$bio', '$arrival', '$title', '$description', '$costyn', '$matcost', '$schedlimit', '$additionalinfo', '$typeofws', '$verified')";
So of course a single quote will blow it up, as will a double quote...it fails every time. There is likely an easy solution to this.
I may have just found it after posting. The php functon addslashes() works in this case.
You can use PDO with prepared statements to handle quotes in SQL requests :
$req = $bdd->prepare("INSERT INTO yourTable (a, b, c) VALUES (:a, :myb, :c)");
$req->bindParam("a", $name, PDO::PARAM_STR); // string
$req->bindParam("myb", $title, PDO::PARAM_STR); // string
$req->bindParam("c", $identifier, PDO::PARAM_INT); // integer
$req->execute();
With this, you avoid all SQL injections.
Documentation : http://php.net/manual/en/book.pdo.php
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
I've been looking all over the internet for a solution to the following 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 'primary, username, password, password2) VALUES (null, 'hello', 'hello', 'hello')' at line 1"
I have no idea what is going on.. I know you will ask what my code is so here:
$con = mysql_connect("localhost","root","*****");
if (!$con)
{
die('Server overload, please try again' . mysql_error());
}
mysql_select_db("users", $con);
$sql = "INSERT INTO details (primary, username, password, password2) VALUES (null, '$_POST[username]', '$_POST[password]', '$_POST[password2]')";
if (!mysql_query($sql,$con))
{
die('Error: Server overload, try again' . mysql_error());
}
echo "You have signed up successfully!";
mysql_close($con);
I've been trying to figure it out for around 4/5 hours now and have had no success.
Thanks,
Lawrence
primary is a reserved keyword, in SQL, which means that you should either :
rename that column -- would be a good idea, to avoid that kind od situation
or use backticks arround that name
Here what the query would look like in the second case :
INSERT INTO details (`primary`, `username`, `password`, `password2`)
VALUES (null, 'hello', 'hello', 'hello')
Note : and you should escape your values, using mysql_real_escape_string, to avoid SQL Injections !
Try not to name your tables or columns with relitively common names like primary and details.
While they may not be reserved words in the flavor of SQL you are currently using, you never know when you might be supporting other types (Postgres, Oracle, etc.).
You can also use this handy-dandy reserved word checker.
Followup Question:
I would like to know who wrote the error statement you are getting, which essentially says RTM? Hilarious. I'm going to use that in my next try catch. :)
Primary is a reserved word. What is the table definition?
http://dev.mysql.com/doc/refman/5.1/en/reserved-words.html
I'd rename that first column to something else: "primary" is a reserved word in MySQL:
http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html