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.
Related
I installed MySql on my Raspberry Pi 2 Model B+ a few days ago to see if I could use it, PHP, phpmyadmin, and Apache to make an accessible database to organize and catalog books that are around the house. I have a table in a MySQL database set up as a prototype with three columns; Booknumber (set to auto-increment), title, and authorLastName. I'm trying to use a form to insert books into table beta, in database bookProof.
Here's the code for the form:
<html>
<body>
<form action="catalog.php" method="POST">
<p>Book Title: <input type="text" name="title"></p>
<p>Author's Last Name: <input type="text name="authorlastname"></p>
</form>
</body>
</html>
Which links to "catalog.php", which is:
<?php
define('DB_NAME', 'bookProof');
define('DB_USER', 'root');
define('DB_PASSWORD', 'root');
define('DB_HOST', 'localhost');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($conn->connect_error) {
die("Could not connect: " . $conn->connect_error);
}
$value = $_POST["title"]
$value2 = $_POST["authorlastname"]
$sql = "INSERT INTO beta ('title', 'authorLastName') VALUES ('".$value."', '".$value2."')"
$query = mysqli_query($conn,$sql);
if ($conn->($sql) === TRUE) {
echo "New entry completed successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When demoform.php is opened, it functions normally, but when the "Add Books" button is clicked, it goes to catalog.php as intended, but the catalog.php page is blank, the table is unchanged, and Google Chrome's "Inspect" tool gives the error:
POST http://192.168.254.11/Library/catalog.php 500 (Internal Server Error) catalog.php:1
If anyone knows how to get the input to the database, please let me know.
Note: This is just a home system, so security is not a priority (I don't need SQL code injection protection).
Your note, "...security is not a priority (I don't need SQL code injection protection)" - you might think that, but you should do it anyways. Not only does it protect your database should your system be exposed (or made public at a later time), it will handle strings automatically for you, so that your query won't break if your strings have quotes ' in them.
One issue is that you're using singlequotes around column and table names. This should be backticks, or none at all. Then you were missing a semicolon ; after defining your $value, $value2 and $sql strings.
Then you're doing something a bit odd - which is also causing a parse-error (Had you enabled error-reporting and checked your logs, you'd see a "Parse error: syntax error, unexpected (" error in your logs), you're querying the table with mysqli_query(), but then you try to do it again - except you're trying to query on the querystring, and not the query method. Note the comments I've added in the code below.
// Don't use singlequotes ' for columns and table-names
// Use backticks ` - quotes are for strings
$sql = "INSERT INTO beta (`title`, `authorLastName`) VALUES ('".$value."', '".$value2."')"; // You were also missing a semicolon here!
// $query = mysqli_query($conn,$sql); // Remove this line, as you're attempting to query it twice
if ($conn->query($sql) === TRUE) { // You're missing the query() method here
echo "New entry completed successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Using prepared statements won't be that much of a difference, and you really should do it. There's absolutely no reason to not use prepared statements! Look how little changes that have to be made!
$sql = "INSERT INTO beta (title, authorLastName) VALUES (?, ?)";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("ss", $value, $value2);
$stmt->execute();
$stmt->close();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
You've also got some invalid HTML which would cause issues - the following line had a missing quote to close off the type attribute.
<input type="text" name="authorlastname">
I suggest you read the following documentation and articles
When to use single quotes, double quotes, and backticks in MySQL
How can I prevent SQL injection in PHP?
PHP manual on mysqli_stmt::bind_param
How to get useful error messages in PHP?
PHP Parse/Syntax Errors; and How to solve them?
As a final note, you should check that the form was submitted and that it has values before inserting into the database. Also, using variable-names like $value and $value2 are not really descriptive - you should avoid it and use proper names for your variables.
My test code is:
<?php
$connessione = mysql_connect("***", "***", "***");
mysql_select_db("***", $connessione);
$risultato = mysql_query("SELECT * FROM servem_vote", $connessione);
if(mysql_query("INSERT INTO servem_vote (uid,lastvote) VALUES ($uid,now()) ON DUPLICATE KEY UPDATE lastvote=now();
")) {
header('location:/home.php'); }
else {
echo "Error: " . mysql_error(); }
mysql_close($con);
?>
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 'now()) ON DUPLICATE KEY UPDATE lastvote=now()' at line 1
DB:
http://prntscr.com/ef7544
Where am I doing wrong?
You are missing $uid in the code you shared. You don't set that value anywhere but you attempt to use it as part of your INSERT query.
If it's coming from form data, grab it from $_REQUEST superglobal variable before attempting to use it:
$uid = $_REQUEST['uid']
If it's NOT an integer in the MySQL table, you need to wrap it in single quotes as part of your statement.
INSERT INTO servem_vote (uid,lastvote) VALUES ('$uid',now())
ON DUPLICATE KEY UPDATE lastvote=now();
I don't know what purpose this line serves:
$risultato = mysql_query("SELECT * FROM servem_vote", $connessione);
You don't seem to do anything with the result set from this query.
MOST IMPORTANTLY: As many others have commented you need to be sanitizing your data and you should be relying on PDO or mysqli* functions to safely interact with your database. See answers here
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
<?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.