I need to secure this PHP code from SQL injection attacks [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to stop SQL Injection in PHP
I need to secure this code from SQL injection attacks, possibly using mysql_real_escape_string. Where and how do I apply it?
<?php
mysql_select_db("database");
$sql="INSERT INTO email (address) VALUES ('$_POST[address]')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "<center>THANK YOU!</center>";
?>

You should be able to just wrap your post value in mysql_real_escape_string():
$address = mysql_real_escape_string($_POST[address]);
$sql="INSERT INTO email (address) VALUES ('$address')";

Stack Overflow is less for teaching and more for authoritative answers to less-common questions.
What you've got is a common question, "how do I use this function," and it's much better to use the PHP docs to answer that sort of thing. So for example, you look up mysql_real_escape_string in the documentation and you find this page: http://php.net/manual/en/function.mysql-real-escape-string.php
Which has example code like:
<?php
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
OR die(mysql_error());
// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));
?>
Adapting this into your case would give:
$sql = sprintf("INSERT INTO email (address) VALUES ('%s')",
mysql_real_escape_string($_POST['address']));
Or you could do it in two phases,
$email = mysql_real_escape_string($_POST['address'])
$sql = sprintf("INSERT INTO email (address) VALUES ('$email')"

Related

PHP|MySql - cannot insert text contains apostrophe [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 6 years ago.
[I am using phpmyadmin]
I want to insert the long texts which are a large description of a city or region.
It contains apostrophe and comma, but when inserted, comma is not a problem but the apostrophe are.
For eg.
' Taunggyi's the administrative capital for the whole of Shan State. Perched on top of a mountain, it's also a busy trading post,
and the...',
It will an input from the user (type-in) to the text area on my website.
So it cannot define statically like other examples I found.
Current one
//php $name=$_REQUEST["name"]; //
//in insert query => '.$name.',
Have tried like below too, but not working.
'".$name."',
Any good ideas, please! Your help is most appreciated. Thank you!
Escape the quote with a backslash. Like 'sumit\'s'.
Here is an example function, using mysqli_real_escape_string:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$age = mysqli_real_escape_string($con, $_POST['age']);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Reference: http://www.w3schools.com/php/func_mysqli_real_escape_string.asp
In your case, it should be mysql_real_escape_string($name)
Have you tried escaping special characters? Below should be helpful:
$name=mysqli_real_escape_string($connection, $name);
I created a function called post() and each time I need something from $_POST I simple call post('item_name'); the function than perform escaping and returns safe string ... There are numerous questions and answers to your question including this one: Properly Escaping with MySQLI | query over prepared statements

Invalid query: You have an error in your SQL syntax

<?php
mysql_connect("mysql6.000webhost.com","a6124751_murali1","***");
$db= mysql_select_db("a6124751_signup");
$topic=$_GET["Topic"];
$question=$_GET["Question"];
$company =$_GET["Company"];
$query = "INSERT INTO questions (topic, question, company) VALUES ($topic, $question, $company)";
$sql1=mysql_query($query);
if (!$sql1) {
die('Invalid query: ' . mysql_error());
}
?>
this is my php code in server where there is a table named 'questions' and i am trying to insert the data into it from the input got from the GET method using form at front end, i can figure out that data is coming properly from the client which i have checked using echo. I am getting an error as
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 'name, type your question here, company)' at line 1
Don't know what is the error in the query. anyone find it out asap. thank you
You need to quote your values
('$topic', '$question', '$company')
since those are strings.
Plus, you should escape your data for a few reasons. Not let MySQL complain about certain characters such as hyphens etc., and to protect against SQL injection.
Use prepared statements:
https://en.wikipedia.org/wiki/Prepared_statement
Reference(s):
https://en.wikipedia.org/wiki/SQL_injection
How can I prevent SQL injection in PHP?
http://php.net/manual/en/function.mysql-real-escape-string.php
Edit:
As an example using your present MySQL API:
$topic = mysql_real_escape_string($_GET['topic']);
$question = mysql_real_escape_string($_GET['question']);
$company = mysql_real_escape_string($_GET['company']);
I don't know what your inputs are called, so that's just an example.
You mentioned about using $_GET for debugging but using a POST method.
Change all $_GET to $_POST above.
Try this
<?php
$db = mysqli_connect('mysql6.000webhost.com', 'a6124751_murali1', 'default#123', 'a6124751_signup');
if (!$db) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
$topic = $_GET["Topic"];
$question = $_GET["Question"];
$company = $_GET["Company"];
$query = "INSERT INTO questions (topic, question, company) VALUES ('$topic', '$question', '$company')";
$sql1=mysqli_query($db, $query);
if(!$sql1)
{
die('Invalid query: ' . mysqli_error($db));
}
?>
Fixes in your code
The mysql extension is deprecated and will be removed in the future:
use mysqli or PDO instead
You need to quote your values ('$topic', '$question', '$company')
You have to put the values in single qoutes, if that are char types:
$query = "INSERT INTO questions (topic, question, company) VALUES ('$topic', '$question', '$company')";
But you should not longer use the deprecated mysql_*API. Use mysqli_* or PDO with prepared statements.

mysql error :error in sql syntax [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
i want to insert some lines of text(paragraph) in database that is coming from wikipedia page..but mysql is showing this error when i try to insert the data in db:
"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 's capital." can anyone help me to fix this problem..
here is what i have done so far...
<?php
$loc=$_POST["new"];
$url1 ="https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=".$loc;
$opf = file_get_contents($url1);
$data = json_decode($opf, true);
$titles = array();
foreach ($data['query']['pages'] as $page) {
$des = $page['extract'];
}
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("location", $con);
$url = "http://upload.wikimedia.org/wikipedia";
echo $sql="INSERT INTO `search`(`id`, `name`, `text`) VALUES ('$loc', '$des');";
mysql_query($sql) or die(mysql_error());
echo "1 record added";
mysql_close($con);
?>
Ideally you should escape data before entering it into a database. The problem you have is the apostrophe is ending the SQL query on '$loc' so the query actually reads:
... VALUES ('Giant's Capital',
Syntax highlight should indicate why that's a problem :)
Use something like: mysql_real_escape_string() to escape your $_POST data before inputting.
$loc = mysql_real_escape_string($_POST['new']);
Doesn't explain why it should work
You have 3 fields and 2 values.
doesn't fix their error
Yes, it does.
uses obsolete code, and is wide open to SQL injections
It isn’t my code. I am adapting OPs code, I am not trying to write it from scratch. Also, I guess, you forgot to mention that mysql function is deprecated since 5.5
Further, although the fact that the code is SQL injectable is good to mention it does not in my opinion constitute an actual answer. It's a comment at best. ie. "hey btw did you know you misspelled a word?" or some such. An editorial nitpick. If questions are going to be closed as duplicates of SQL injection questions then 80% of the questions here would have to be closed as dupes.
If the OPs wants to know about SQL injection please refer to this site
Oh, btw,this is the code:
<?php
$loc=$_POST["new"];
$url1 ="https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=".$loc;
$opf = file_get_contents($url1);
$data = json_decode($opf, true);
$titles = array();
foreach ($data['query']['pages'] as $page) {
$des = $page['extract'];
}
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("location", $con);
$url = "http://upload.wikimedia.org/wikipedia";
echo $sql="INSERT INTO `search`(`name`, `text`) VALUES ('$loc', '$des');";
mysql_query($sql) or die(mysql_error());
echo "1 record added";
mysql_close($con);
?>

i have an error while inserting the values what i did [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
help me with this code i am new to php
<?php
$conn=mysql_connect("localhost","root","","test");
if(isset($_POST['submit']))
{
$sql="INSERT INTO registration(fname,designation,emailid,
address,phonenumber)VALUES('".$_POST['fname']."','".$_POST['designation']."','".$_POST['ema
lid']."', '".$_POST['address']."','".$_POST['phonenumber']."')";
echo $sql;
$result=mysql_query($conn,$sql);
echo $result;
}
else{
echo "Error";
}
?>
its a registration page getting values and inserting it in the table...
You have the parameters around the wrong way here:
$result=mysql_query($conn,$sql);
Try
$result=mysql_query($sql, $conn) or die(mysql_error($conn));
Side notes:
Don't use mysql_*() functions: they're deprecated. Use mysqli_*() versions instead.
You should escape your user inputs with mysql_real_escape_string() to protect against SQL Injection attacks. Consider using prepared statements with mysqli_() instead.
Take a look at this link which is a good tutorial for inserting data (from a form etc.) to a mysql database.
Also: be aware of sql-injection and prevent it. here is a tutorial on how to do this: link
If you want to have readable code, set the $_POST[] values to a variable, and then pass them to the query, it's not different in fact but this is more easy and clean.:
<?php
$conn=mysql_connect("localhost","root","","test");
if(isset($_POST['submit']))
{
$fname = $_POST['fname'];
$designation = $_POST['designation'];
$emailid = $_POST['emailid'];
$address = $_POST['address'];
$phonenumber = $_POST['phonenumber'];
$sql="INSERT INTO registration(fname,designation,emailid,address,phonenumber)";
$sql .="VALUES('$fname', '$designation', '$emailid', '$address', '$phonenumber')";
echo $sql;
$result=mysql_query($conn,$sql);
echo $result;
}
else{
echo "Error";
}
?>
you hade a typing mistake in $_POST['emailid']...
and you can select your database with this:
mysql_select_db('your db name');
put this line after your connection variable means $conn
and this is wrong:
$result = mysql_query ($conn, $sql)
you have to set the query first:
$result = mysql_query($sql, $conn)

PHP and MySql trouble

I am having trouble making this seemingly simple MySql query work. Can anyone spot the problem?
<?php
include "config.php";
$offerid = $_POST["offerid"];
$ip = $_SERVER["REMOTE_ADDR"];
mysql_query("INSERT INTO voted (offerid,ip) VALUES (".$offerid.",".$ip.")");
?>
You probably want some single quotes:
"INSERT INTO voted (offerid,ip) VALUES ('" . $offerid . "','" . $ip . "')"
You should also use intval and mysql_real_escape_string to avoid SQL injection vulnerabilities:
$sql = "INSERT INTO voted (offerid,ip) VALUES (" .
intval($offerid). ", '" .
mysql_real_escape_string($ip) . "')";
Another alternative which may be easier to read is to use sprintf:
$sql = sprintf("INSERT INTO voted (offerid, ip) VALUES (%d, '%s')",
$offerid, mysql_real_escape_string($ip));
To place a string value into query, you must perform 2 actions on it:
enclose it in quotes
and escape special characters.
So, query must be like this:
INSERT INTO voted (text) VALUES ('I\'m a programmer')
Armed with this knowledge, you can easily write a code to make valid query:
$offerid = mysql_real_escape_string($_POST["offerid"]);
$ip = mysql_real_escape_string($_SERVER["REMOTE_ADDR"]);
$sql = "INSERT INTO voted (offerid,ip) VALUES ('$offerid','$ip')"
mysql_query($sql) or trigger_error(mysql_error().$sql);
Note the trigger_error part.
It will provide you with comprehensive information on any error
my guess would be with quotes
mysql_query("INSERT INTO voted (offerid,ip) VALUES (\"".$offerid."\",\"".$ip."\")");
<?php
include "config.php";
$offerid = $_POST["offerid"];
$ip = $_SERVER["REMOTE_ADDR"];
mysql_query("INSERT INTO voted (offerid,ip) VALUES ('".mysql_real_escape_string ($offerid)."','".mysql_real_escape_string ($ip)."')");
?>
This adds the single quote marks around the strings you are inserting - as well as mysql_real_escape_string php function that will escape (add a backslash infront of) any security risk characters.
In addition to using intval(...) and mysql_real_escape_string(...) you could use parameterized statements (or placeholders) using PEAR::DB or PEAR::MDB2:
$dsn = "mysqli://testuser:testpass#localhost/test";
$conn =& DB::connect ($dsn); // using PEAR::DB, though it's been superseded
if (DB::isError ($conn)) {
die ("Cannot connect: " . $conn->getMessage () . "\n");
}
$result =& $conn->query ("INSERT INTO voted (offerid,ip) VALUES (?,?)", array($_POST["offerid"], $_SERVER["REMOTE_ADDR"]));
if (DB::isError ($result)) {
die ("INSERT failed: " . $result->getMessage () . "\n");
}
Using placeholders and parameters is pretty common on platforms other than PHP, so it's not a bad idea to understand the basic premise behind them.
If you're interested in using DB modules like these, I'd recommend checking out Writing Scripts with PHP's PEAR DB Module by Paul DuBois. Again, the module it describes is superseded, but I find it's nonetheless interesting and informative.

Categories