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
Related
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
This one has had me stumped for a couple of days. I have a basic PHP script to submit a user registration form. I just cant see what I am doing wrong in this instance the web server is running PHP 7.0 and there are no errors in the logs.
<?php
require_once('connect.php');
if(isset($_POST) && !empty($_POST)){
$username = mysqli_real_escape_string($connection, $_POST['username']);
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password =md5($_POST['password']);
$sql = "INSERT INTO 'login' (username, email, password) VALUES ('$username', '$email', '$password')";
$result = mysqli_query($connection, $sql);
if($result){
echo "User Rego Secusseflllgk";
}else{
echo "User rego faile";
}
}
?>
I saw a couple of these already but they seemed to be to do with using both myslq and mysqli and others appeared to not be first connection to the DB. Any help would be much appreciated. I am recieving the User Rego Failed echo
You probably want use the backtick ` instead of a single quote ' to wrap your table name.
INSERT INTO `login`
When a query fail, it's useful to print the error message. You can do it with mysqli_error:
echo mysqli_error($connection);
Use table name without single quote and try to check mysqli error with mysqli_error($connection) just after $result.
<?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.
I'm making a small project and I'm having some trouble with a php script. Basically, when they enter the text then click 'Enter' It loads to the 'insert.php'. The thing is, if they just visit the insert.php page without going to the main page It enters a plan table which could cause big problems.
Code:
$con=mysqli_connect("localhost","info","info","info");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
Can you help me fix this problem as It could cause a lot of troubles.
First you need to validate your $_POST variables by using isset().
If they are not submitted from a form, $_POST will be empty. Meaning that when a user try to type in the url, there won't be any post data and your SQL queries won't run.
2nd, you are subject to SQL injection since you are not escaping the content.
I'd suggest escaping each variable by using a prepared statement or mysqli_real_escape_string (less secure but better than nothing).`
if ( isset($_POST) && !empty($_POST['firstname']) && !empty($_POST['lastname']) && !empty($_POST['age'])) {
$con=mysqli_connect("localhost","info","info","info");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//simple example of escaping variables - BUT NOT AS SECURE AS PREPARED STATEMENT!!
$firstname = $con->real_escape_string($_POST['firstname']);
$lastname = $con->real_escape_string($_POST['lastname']);
$age = $con->real_escape_string($_POST['age']);
//With MySQLi it is best practice to use `prepere`, `bind_param` and `execute:
//or use PDO.
$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);
}
Lastly, you were missing the single quotes inside your $_POST variables.
Hope this helps!
This is pretty simple.
if(isset($_POST)):
//all of your code here
endif;
You have to check if $_POST exists to trigger your sql request
if (isset($_POST)){
//script
}
One of the first things that I see right off the top of my head is the fact that you are not checking to ensure that something has infact been typed Into your input box that passes the data to your other file. You can try to use isset() or array_key_exist(). Not to mention these are things that you should be doing anyway.
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')"
I post the data of dynamically generated textbox in PHP. When I post the data using real_escape_string(), i.e:
$ingredient = mysql_real_escape_string($_POST['ingredient']);
...it doesn't post data from textbox and I use simple $_POST['']; method i.e:
$ingredient = $_POST['ingredient'];
...it gives me error when I use a single quote (') in my text.
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', 'fgad', '55')' at line 2
this was my old post i solved the problem locally by enabling magic_quotes_gpc = On but when upload this on my server it does't work again so how can i turn on magic quotes on server.
Do you have an open database connection? mysql_real_escape_string needs a MySQL server to talk to in order to function.
You might want to try
$ingredient = $_POST['ingredient'];
$ingredient = mysql_real_escape_string($ingredient);
<?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);
?>
you must used connection db see
http://php.net/manual/en/mysqli.real-escape-string.php
you can use also
string mysqli::real_escape_string ( string $escapestr )
I think this might be related to the "magic" quotes feature -- see this page for details: Magic Strings & SQL
Basically, because of problems with SQL injection attacks, they pre-escaped strings with quotes after a certain version of PHP (I think it was 5.0, but I could be wrong). So the end result is that now your software has to check for the software version and behave differently depending on whether the string is already escaped or not.