The right syntax for insertion into Mysql using php - php

I'm trying to insert some values into the database using information posted on a form through php
following is the code that i'm using for insertion
$query=mysql_query("select * from poll_question where question = '$question'") or die(mysql_error());
$numrows=mysql_num_rows($query);
if($numrows)
{
while($row=mysql_fetch_assoc($query))
{
$dbid=$row['id'];
}
}
$sql1 = "INSERT INTO poll_option(option , poll_id ,click)
VALUES('$_POST[optionone]',
'$dbid' , 0)";
$result1 = mysql_query($sql1);
echo "1 record added";
echo mysql_error();
$sql2 = "INSERT INTO poll_option(option , poll_id , click)
VALUES('$_POST[optiontwo])',
'$dbid', 0)";
$result2 = mysql_query($sql2);
echo mysql_error();
$sql3 = "INSERT INTO poll_option(option , poll_id, click)
VALUES('$_POST[optionthree])',
'$dbid ', 0)";
$result3 = mysql_query($sql3);
echo mysql_error();
now i'm getting the following output
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 'option , poll_id ,click) VALUES('sj', '24' , 0)' at line 1
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 'option , poll_id , click) VALUES('dsdg', '24', 0)' at line 1
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 'option , poll_id, click) VALUES('xzf', '24 ', 0)' at line 1
The part under the "values" syntax is the one that i'm trying to insert. that information is correct.that is VALUES('xzf', '24 ', 0) is Correct and i want to insert this only , but their is some problem with the syntax.Any suggestions?

What echo_me said.
Additionally, in $sql2 and $sql3 you are closing the VALUES (...) parenthesis too soon:
VALUES('$_POST[optiontwo])',
^ remove this
Your $sql1 is correct.

OPTION is reserved keyword for mysql
try use backticks around it in all your queries
like that:
`option`
look reserved keywords here

In addition to what echo_me stated in removing the parentheses incorrectly added to $sql2 and $sql3, you really should migrate over to mysqli (since mysql is deprecated) and at least use the real escape string option on your post variable before automatically inserting whatever is posted to the script into your database. A good example for your code is:
$post_option1 = mysql_real_escape_string($_POST['optionone']);
$post_option2 = mysql_real_escape_string($_POST['optiontwo']);
$sql1 = "INSERT INTO poll_option (`option`, `poll_id`, `click`) VALUES('$post_option1', '$dbid', 0)";
$sql2 = "INSERT INTO poll_option (`option`, `poll_id`, `click`) VALUES('$post_option2', '$dbid', 0)";
My opinion is it would make things simpler for you as well. The info on the real escape string can be found here:
http://php.net/manual/en/function.mysql-real-escape-string.php
It's against best practice to insert a POST or GET directly into your database without any form of mitigation against SQL injection.

Try to avoid using mysql functions, but rather learn to use PDO functions. They have a number of advantages over mysql functions, although im really sorry, i dont remember them right now, and i dont want to say anything that's not true.
Also, i dont think that the mysql functions can prevent SQL injection, which can let any user alter your Database however they want.
Most importantly though, is that they're deprecated in PHP 5.5
Sorry if i didn't solve your question, just thought to let you know. Good luck, maybe you can get it to work with the new functions.
Update: Sorry, didn't see the comments and posts about switching to mysqli and such.

Related

Why isn't mysql_real_escape_string working?

I am trying to insert a ' symbol into my database and have the below code.
$actionurl =$_POST['actionurl'];
$newtitle = $_POST['newtitle'];
$newtitle = mysql_real_escape_string($newtitle);
$result2 = mysql_query("UPDATE links SET title='$newtitle' WHERE url='$actionurl'")
or die(mysql_error());
And I get this 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 's to start up a sample library (forum thread)'' at line 1
Why am I getting an error if I'm using mysql_real_escape_string on the $newtitle variable?
I suspect that it's actionurl that is causing the error, not $newtitle.
To debug this, echo or print the SQL statement to be executed.
You can do something like this:
$sql = "UPDATE links SET title='$newtitle' WHERE url='$actionurl'";
// for debugging, output contents of the $sql string
echo "SQL=" . $sql ;
mysql_query($sql) or die(mysql_error();
As others have already suggested, the mysql_ interface is deprecated. New development should use either mysqli or PDO. And use prepared statements with bind placeholders. It just seems nonsensical to be struggling with mysql_real_escape_string in 2016.
Are magic quotes on in your php.ini? If yes, disabling it should solve your issue. (It could be enabled by default)

Basic sql injection

I'm trying to learn SQL injections so I can protect myself in the future.
Here is the PHP code:
$req = mysql_query("INSERT INTO ip_change VALUES('', '".$_SESSION['id']."', '".$_POST['raison']."')") or die(mysql_error());
And the user has full control over $_POST['raison'] content.
When i use 'hello as $_POST['raison'] value I get
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 'hello')' at line 1
When i use '); DELETE * FROM tabledetest;") or die(mysql_error());-- as $_POST['raison'] value I get
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 'DELETE * FROM tabledetest;") or die(mysql_error());--')' at line
1
So I don't understand why my request isn't injected and I can't delete my tabledetest table.
Any help would be appreciated.
It is because you didn't do proper injection!
Here is the one you have done. The auto-format will hint you:
<?php
$_SESSION['id'] = "123"; //Just assume
$req = mysql_query("INSERT INTO ip_change VALUES('', '123', ''hello')") or die(mysql_error());
It didn't properly end the statement.
For the next one:
$req = mysql_query("INSERT INTO ip_change VALUES('', '123', ''); DELETE * FROM tabledetest;") or die(mysql_error());--')") or die(mysql_error());
From the manual:
mysql_query() sends a unique query (multiple queries are not
supported) to the currently active database on the server that's
associated with the specified link_identifier.
mysqli has support for multiple statements.
-- can't comment PHP code! PHP comment is // or #
Some of the links that might help you: [Similar to your question]
https://en.wikibooks.org/wiki/PHP_Programming/SQL_Injection_Attacks
http://roshanbh.com.np/2007/12/sql-injection-attack-examples-and-preventions-in-php.html
SQL injection test - mysql_query
To protect from SQL injection you should not inject the variables directly to query use Prepared Statements instead.

mySQL error, that I can't find

I'm writing because I simply can't find my error, I copied this code from another document and edited some few things, but then I have an error. I'm unable to see what it is.
The following error is:
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 'by,telefon,email) VALUES (987, , , , by, , )' at line 1
And my code is following:
$taelf = mysql_result(mysql_query("SELECT COUNT(*) FROM `Firma` WHERE `navn` = '$navn'"),0);
if($taelf < 1){
mysql_query("INSERT INTO `Firma` (navn,cvr,Adresse,postnr,by,telefon,email)
VALUES ($_POST[navn], $_POST[cvr],
$_POST[adresse], $_POST[postnr],
by, $_POST[nummer], $_POST[email]
)"
) or die(mysql_error());
echo "<div id='success'>Vupti, firmaet er nu oprettet. '$_POST[navn]','$_POST[cvr]','$_POST[adresse]','$_POST[by]','$_POST[postnr]','$_POST[nummer]','$_POST[email]'</div>";
BY is a reserved word. If you are going to name a column with that name you must wrap it in ticks:
INSERT INTO `Firma` (navn,cvr,Adresse,postnr,`by`,telefon,email)
Also see Fabien Warniez's answer which explains that you also need to wrap your string values in quotes.
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
You are also wide open to SQL injections
You need to add quotes around your string values:
mysql_query("INSERT INTO `Firma` (navn,cvr,Adresse,postnr,by,telefon,email)
VALUES ('$_POST[navn]', '$_POST[cvr]', '$_POST[adresse]', '$_POST[postnr]',
'by', '$_POST[nummer]', '$_POST[email])'") or die(mysql_error());
Please note that this should fix your syntax problem, but you really should escape the POST variables.

PHP MySQL INSERT statement syntax error

I'm having problems with an INSERT statement, and the error only says:
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 '' at line 1
It's not helpful at all.
The version I have tried so far and failed is:
mysql_query("INSET INTO `cos` VALUES ('".$_GET['prod']."','".$_GET['page']."')");
[needless to say that the two variables when printed show the right values]
I've also tried versions with nothing around the table name, with ` or ', a million combinations really and nothing works. Not even with constants or into different tables. It just won't insert anything ever. I've checked the privileges (I'm logging into it with root), and it's all on.
I've tried similar stuff on two different machines with the same server (XAMPP 1.7.7) and it works. I'm completely baffled! What can it be?
Thank you for your time!
First and foremost, just type INSERT correctly.
Using _GET like that really opens you up to SQL INJECTIONS...
Do take a look into MySQL prepared statements.
It is also considered good practice to name the columns that you're inserting data into. That allows you to, latter on, insert extra-columns and keep application logic.
INSERT INTO cos(rowName1, rowName2) VALUES(?, ?)
Where ? would be prepared statements.
Correct:
mysql_query("INSERT INTO `cos` VALUES ('".$_GET['prod']."','".$_GET['page']."')");
Have you tried passing the $link to mysql_query ?
Like:
mysql_query("INSERT INTO `cos` VALUES ('".$_GET['prod']."','".$_GET['page']."')", $link);
EDIT:
And of course you must take some security measures before inserting anything into the database, maybe mysql_real_escape_string() or even prepared statements.
You are doing it wrong. Why aren't you escaping the values?
Php.net documentation is providing some good and safe working examples:
$query = sprintf("SELECT firstname, lastname, address, age FROM friends
WHERE firstname='%s' AND lastname='%s'",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname));
// Perform Query
$result = mysql_query($query);
So adapted to your code:
$query = sprintf("INSERT INTO `cos` VALUES (%s, %s);",
mysql_real_escape_string($_GET['prod']),
mysql_real_escape_string($_GET['page']));
$result = mysql_query($query);
Please, always escape your values. And use INSERT, not INSET :)
first this is you are using INSET make it correct with INSERT like
$pro = mysql_real_escape_string($_GET['prod']);
$page = mysql_real_escape_string($_GET['page']);
mysql_query("INSERT INTO `cos` (column1, column2)
VALUES ('$pro', '$page')" );
you forget to set the column names...
Try this:
$prod = $_GET['prod'];
$page = $_GET['page'];
mysql_insert("INSERT INTO 'cos' VALUES('$prod','$page)");
This should very well do it :)

Strange MySQL Error. (PHP)

I have a following code:
<?php
include("config.php");
$key = 'blahblah';
$sql = "INSERT INTO softversions SET key='$key'";
$result = mysql_query($sql) or die ($mysql_error());
echo "dude";
?>
This gives me an 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 'key='svksskjfvns'' at line 1
The thing is that I've used this script about a hundred times on other pages and it worked.
Table and field names are 100% correct.
I don't understand what is going on.
Do you see the syntax error there?
KEY is a reserved word in MySQL and you need to escape it using backticks to use it as a column name and also you should not use SET when inserting.
$sql = "INSERT INTO softversions (`key`) VALUES ('$key')";
key is a reserved word in MySQL. To use it as a column, you need to escape it every time you call it.
$sql = "INSERT INTO softversions SET `key`='$key'";
$sql = "INSERT INTO softversions(keyName) values('{$key}')";

Categories