I'm using a developer to help me build a site - and I'm getting an error relating to a webform when I use the text: I'm
Further details:
“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 'm', team_member_pic = ''' at line 7”
that he can't solve. He's suggesting it's the version of MySQL (5.5.23) on my webhost (Hostgator) - because the code seems to work okay on his server with MYSQL 5.5.xx at (GoDaddy)
The code he's applying is as follows:
$insert = "INSERT INTO ".TABLE_PREFIX."host_manager_team_members SET
user_id = '".$_REQUEST['id']."',
team_member_firstname =
'".addslashes($_REQUEST['team_member_firstname'])."',
team_member_surname =
'".addslashes($_REQUEST['team_member_surname'])."',
team_member_email =
'".addslashes($_REQUEST['team_member_email'])."',
team_member_phone =
'".addslashes($_REQUEST['team_member_phone'])."',
team_member_desc =
'".mysql_real_escape_string($_REQUEST['team_member_desc'])."',
team_member_pic = '".$filepath."'";
mysql_query($insert) or die(mysql_error());
Can anyone give some guidance on what could be causing this error? Would really appreciate any thoughts/ideas you would have.
Use sprintf like this
$insert = sprintf("INSERT INTO ".TABLE_PREFIX."host_manager_team_members SET
user_id = '%s',
team_member_firstname =
'%s',
team_member_surname =
'%s',
team_member_email =
'%s',
team_member_phone =
'%s',
team_member_desc =
'%s',
team_member_pic = '%s'",$_REQUEST['id'],addslashes($_REQUEST['team_member_firstname']),addslashes($_REQUEST['team_member_surname']),addslashes($_REQUEST['team_member_email']),addslashes($_REQUEST['team_member_phone']),mysql_real_escape_string($_REQUEST['team_member_desc']),$filepath);
mysql_query($insert) or die(mysql_error());
Your code is just about as vulnerable as it can be:
Don’t use $_REQUEST, as you don’t know where the data is coming from. It is a combination of $_GET, $_POST and $_COOKIE, and it makes it very easy for a user to inject their own additional data by simply appending ?evilstuff=hahaha to the URL.
Don’t use mysql_ functions. They are deprecated and removed in PHP7. That’s good because MySQL4, for which the original functions were created, did not have the more secure features implemented later.
Don’t use addslashes. It a poor attempt to escape strings against the possibility of SQL injection. If you must do it the old way, use one of the real_escape_string functions. Better still:
Always use prepared statements when accommodating user data. Preparing the statement results in interpreting the SQL before data has been injected, so any additional data, even if it looks like SQL, will be treated as pure data only.
Finally,
It is much easier to use PDO, which has been available since PHP 5.
Here is an alternative using PDO & prepared statements:
$table=TABLE_PREFIX.'host_manager_team_members';
$insert = "INSERT INTO $table SET user_id = ?, team_member_firstname = ?,
team_member_surname = ?, team_member_email = ?, team_member_phone = ?,
team_member_desc = ?, team_member_pic = ?";
$prepared=$pdo->prepare($insert);
$prepared->execute(array(
$_REQUEST['id'],
$_REQUEST['team_member_firstname'],
$_REQUEST['team_member_surname'],
$_REQUEST['team_member_email'],
$_REQUEST['team_member_phone']
$_REQUEST['team_member_desc'],
$filepath
));
The SQL statement is much easier to debug when you can see it by itself.
Note that you do not put quotes around the string values in a prepared statement. This is because quotes are only required for strings when they are constructed in code. By the time the prepared statement gets the data, the string has already been constructed.
I have also used a double quoted string to allow the interpolation of a variable which is not user-generated.
I see that you’re using a quirky MySQL extension to the INSERT statement, which is by no means universally supported. Perhaps you should try the more standard syntax:
$insert = "INSERT INTO $table user_id (team_member_firstname,
team_member_surname, team_member_email, team_member_phone,
team_member_desc, team_member_pic)
VALUES(?,?,?,?,?,?)";
Finally, to answer your question, it is quite possible that the error is caused by the data itself. What you need to do is print the contents of your string generated string, and then run that though MySQL directly (possibly using the SQL tab in PHPMySQL).
So, even without doing any of the above, you should try:
print $insert;
exit;
Perhaps you could try this and post the results here.
Related
I'm getting the error: Column count doesn't match value count at row 1
I think, normally this error occurs if the count of the columns and the values aren't equal, but in my code they are...(3).
This is my php code:
$tempsongtitel = $_POST['songtitle'];
$tempinterpret = $_POST['interpret'];
$templink = $_POST['link'];
$query = mysql_query("insert into tMusic (Songtitel, Interpret, Link) values ('$tempsongtitel, $tempinterpret, $templink')") or die(mysql_error());
You missed some quotes. Should be:
$query = mysql_query("insert into tMusic (Songtitel, Interpret, Link) values ('$tempsongtitel', '$tempinterpret', '$templink')") or die(mysql_error());
Otherwise, you were trying to insert all three POST values into the first field.
Moreover, the mysql_ extension has been deprecated and is on the way out and is highly discouraged, especially if you are creating new software.
AND I'll presume you are first sanitizing your data? You're not really taking user input and placing it directly into the database, are you? Even if you don't do any data validation, you should escape your data in the query... easiest and most foolproof way to do that is by using parameterized queries.
The root cause is that your values are all in one set of quotes instead of quoted individually. I think this is a pretty common error, and in my experience it is an easy mistake to make, but not immediately obvious when scanning over your code. You can fix it like this (quick fix, still using deprecated mysql, but with post values escaped):
$tempsongtitel = mysql_escape_string($_POST['songtitle']);
$tempinterpret = mysql_escape_string($_POST['interpret']);
$templink = mysql_escape_string($_POST['link']);
$query = mysql_query("insert into tMusic (Songtitel, Interpret, Link)
values ('$tempsongtitel', '$tempinterpret', '$templink')") or die(mysql_error());
If you can, it would be much better to update your code to use PDO. You could use a prepared statement like this:
$stmt = $pdo->prepare("INSERT INTO tMusic (Songtitel, Interpret, Link) VALUES (?, ?, ?)");
$stmt->bindValue(1, $tempsongtitel);
$stmt->bindValue(2, $tempinterpret);
$stmt->bindValue(3, $templink);
$stmt->execute();
Among the many benefits of using this database extension rather than the old mysql functions it should not be possible to make an error like this in your code. In the prepared statement, there are no quotes around the parameter markers, so if you have VALUES ('?, ?, ?'), or even VALUES ('?', '?', '?') You would get bind errors when trying to bind the values, and the problem would become apparent pretty quickly.
I've found that, even though it's not 100% necessary and it's more time consuming, properly quoting and backticking EVERYTHING helps prevent this from happening.
$myQuery = "INSERT INTO `tMusic` (
`Songtitel`,
`Interpret`,
`Link`
) VALUES (
'$tempsongtitel',
'$tempinterpret',
'$templink'
);";
$runQuery = mysqi_query($DBi, $myQuery) or die(mysqli_error($DBi));
The formatting you use is up to you but this helps me make sure I have a one to one relationship and that I've quoted everything.
Of course that's using mysqli_* in place of the deprecated mysql_* functions AND that's assuming you've set $tempsongtitel, $tempinterpret and $templink properly.
I need some help here!
I have a form on a site admin page, the owner fills in his projects and the get added to a mysql db, but sometimes the data contains single or double quotes so it won't add to the db.
I tried using addslashes but it still wont work.
Heres my code which Ive tried
$atitle = addslashes($_REQUEST['atitle']);
$acontent = addslashes($_REQUEST['acontent']);
$query = "INSERT INTO projects VALUES (NULL, '$atitle', '$acontent', '$remote_file', '$remote_file1', '$remote_file2')";
$result = mysql_query($query);
if(!$result){
$error = 'An error occured: '. mysql_error().'<br />';
$error.= 'Query was: '.$query;
echo $error;
die($message);
}
Can anyone help me with this?
mysql_query is part of an outdated php library that isn't supported anymore. The more reliable method of interacting with a database is mysqli. Using mysqli, you'll be able to use Prepared Statements. Prepared Statements are a way to validate input and to mitigate problems like this (your input having quotation ticks/marks). Take a look at this example:
$db = new mysqli("host","user","pw","database");
$stmt = $db->prepare("INSERT INTO projects VALUES (NULL, '?', '?', '?', '?','?')");
$stmt->bind_param('s', $atitle); // s means string in the first param
$stmt->bind_param('s', $acontent); // s means string in the first param
... // same for all other parameters in your query
$stmt->execute();
More on this: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
I heavily recommend using mysqli. It is current and supported. Prepared Statements are the best way to defend against SQL injections and also catching trip-ups like this. It will sanitize the input for you and account for quotation symbols.
you can try stripslashes() to un-quotes a quoted string. More details are available on the PHP documentation website here.
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 :)
The following code is generating this
Warning: oci_execute() [function.oci-execute]:
ORA-00911: invalid character in F:\wamp\www\SEarch Engine\done.php on line 17
the code is...
<?php
include_once('config.php');
$db = oci_new_connect(ORAUSER,ORAPASS,"localhost/XE");
$url_name=$_POST['textfield'];
$keyword_name=$_POST['textarea'];
$cat_news=$_POST['checkbox'];
$cat_sports=$_POST['checkbox2'];
$anchor_text=$_POST['textfield2'];
$description=$_POST['textarea2'];
$sql1="insert into URL(Url_ID,Url_Name,Anchor_Text,Description)
VALUES( 9,".'{$url_name}'.",".'{$anchor_text}'.",".'{$description}'.")";
$result=oci_parse($db,$sql1);
oci_execute($result);
?>
Never insert user input directly into SQL. Use oci_bind_by_name() to prepare a secure statement. As a side effect, that will also fix the error you're getting (which is a quoting typo). The code would look like
$url_name = $_POST['textfield'];
$anchor_text = $_POST['textfield2'];
$description = $_POST['textfield3'];
$sql = 'INSERT INTO URL(Url_ID,Url_Name,Anchor_Text,Description) '.
'VALUES(9, :url, :anchor, :description)';
$compiled = oci_parse($db, $sql);
oci_bind_by_name($compiled, ':url', $url_name);
oci_bind_by_name($compiled, ':anchor', $anchor_text);
oci_bind_by_name($compiled, ':description', $description);
oci_execute($compiled);
You've got a few problems here. First, variables aren't interpolated into strings enclosed in single quotes. Try this simple script to see what I mean:
$a = 'hi';
print 'Value: $a'; // prints 'Value: $a'
vs.
$a = 'hi';
print "Value: $a"; // prints 'Value: hi'
Secondly, you'll need to escape the variables before using them to construct an SQL query. A single "'" character in any of the POST variables will break your query, giving you an invalid syntax error from Oracle.
Lastly, and perhaps most importantly, I hope this is just example code? You're using unfiltered user input to construct an SQL query which leaves you open to SQL injection attacks. Escaping the variables will at least prevent the worst kind of attacks, but you should still do some validation. Never use 'tainted' data to construct queries.
It's rather hard to say without seeing what the generated SQL looks like, what charset you are posting in and what charset the database is using.
Splicing unfiltered user content into an SQL statement and sending it to the DB is a recipe for disaster. While other DB APIs in PHP have an escape function, IIRC this is not available for Oracle - you should use data binding.
C.
It's because you have un-quoted quote characters in the query string. Try this instead:
$sql1="insert into URL(Url_ID,Url_Name,Anchor_Text,Description)
VALUES( 9,\".'{$url_name}'.\",\".'{$anchor_text}'.\",\".'{$description}'.\")";
You need single quotes around the varchar fields that you are inserting (which I presume are url_name, anchor_text, and description). The single quote that you currently have just make those values a String but in Oracle, varchar fields need to have single quotes around them. Try this:
$sql1="insert into URL(Url_ID,Url_Name,Anchor_Text,Description) VALUES( 9,'".'{$url_name}'."','".'{$anchor_text}'."','".'{$description}'."')";
I don't have PHP anywhere to test it, but that should create the single quotes around your values.
Because really the sql you will eventually be executing on the database would look like this:
insert into URL
(
Url_ID,
Url_Name,
Anchor_Text,
Description
)
VALUES
(
9,
'My Name',
'My Text',
'My Description'
)
The main article Binding Variables in Oracle and PHP appears to be down but here is the Google Cache Version that goes into detail about how to bind variables in PHP. You definitely want to be doing this for 1) performance and 2) security from SQL injection.
Also, my PHP is a bit rusty but looks like you could also do your original query statement like this:
$sql1="insert into URL(Url_ID,Url_Name,Anchor_Text,Description) values ( 9, '$url_name', '$anchor_text', '$description')";
Edit
Also, you need to escape any single quotes that may be present in the data you receive from your form variables. In an Oracle sql string you need to convert single quotes to 2 single quotes to escape them. See the section here titled "How can I insert strings containing quotes?"
If you are still in starting developing, I want to suggest to use AdoDB instead of oci_ functions directly.
Your code above can be rewritten using AdoDB like this:
<?php
include_once('config.php');
$url_name=$_POST['textfield'];
$keyword_name=$_POST['textarea'];
$cat_news=$_POST['checkbox'];
$cat_sports=$_POST['checkbox2'];
$anchor_text=$_POST['textfield2'];
$description=$_POST['textarea2'];
//do db connection
$adodb =& ADONewConnection("oci8://ORAUSER:ORAPASS#127.0.0.1/XE");
if ( ! $adodb )
{
die("Cannot connect to database!");
}
//set mode
$adodb->SetFetchMode(ADODB_FETCH_BOTH);
//data for insert
$tablename = 'URL';
$data['Url_ID'] = 9;
$data['Url_Name'] = $url_name;
$data['Anchor_Text'] = $anchor_text;
$data['Description'] = $description;
$result = $adodb->AutoExecute($tablename, $data, 'INSERT');
if ( ! $result )
{
die($adodb->ErrorMsg());
return FALSE;
}
//reaching this line meaning that insert successful
In my code above, you just need to make an associative array, with the column name as key, and then assign the value for the correct column. Data sanitation is handled by AdoDB automatically, so you not have to do it manually for each column.
AdoDB is multi-database library, so you can change the databas enginge with a minimal code change in your application.
Im writing a php script that is used to update a database but it is giving errors when i tries to run the query it returns an error along the lines of
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 'id=15"' at line 1
Where it says "To use near" seems to display part of the query after there is a space in the data. Im assuming i need to put single quotes around where the data to the query from the php variables but when i try to put them in (even escaping the quotes) i get parse errors from the script
The SQL Query is
mysql_query("UPDATE Videos SET Title=".$_POST['Title'].", Preacher=".$_POST['Preacher'].", Date=".$_POST['Date'].", Service=".$_POST['Service'].", File=".$_POST['File'].", Description=".$_POST['Description']."WHERE id=".$_GET['vid_id']."\"") or die(mysql_error());
Thank in advance for any help
mysql_real_escape_string() and sql injections have already been mentioned.
But right now your script (painstakingly) has to mix the sql statement with the data/parameters and in the next step the MySQL server has to separate the data from the statement.
Using (server-side) prepared statements both "parts" of your query are sent separately and the sql parser (of your MySQL server) can never get "confused" about where the statement ends and the data begins.
The php-mysql module doesn't know prepared statements but php-mysqli and PDO do.
$pdo = new PDO('mysql:host=localhost;dbname=test', '...', '...');
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $pdo->prepare('
UPDATE
Videos
SET
Title=:title ,
Preacher=:preacher ,
Date=:date ,
Service=:service ,
File=:file ,
Description=:description
WHERE
id=:id
');
$stmt->bindParam(':title', $_POST['title']);
$stmt->bindParam(':preacher', $_POST['preacher']);
$stmt->bindParam(':date', $_POST['date']);
$stmt->bindParam(':service', $_POST['service']);
$stmt->bindParam(':file', $_POST['file']);
$stmt->bindParam(':description', $_POST['description']);
$stmt->bindParam(':id', $_GET['id']); // really _GET?
$stmt->execute();
May seem a lot of bloat if you use $stmt for only one operation. But consider that otherwise you have to call mysql_real_escape_string() for each parameter.
You need to escape the variables properly and surround them by single quotes:
mysql_query("UPDATE
Videos
SET
Title = '".mysql_real_escape_string($_POST['Title'])."',
Preacher = '".mysql_real_escape_string($_POST['Preacher'])."',
Date = '".mysql_real_escape_string($_POST['Date'])."',
Service = '".mysql_real_escape_string($_POST['Service'])."',
File = '".mysql_real_escape_string($_POST['File'])."',
Description = '".mysql_real_escape_string($_POST['Description'])."'
WHERE
id = '".mysql_real_escape_string($_GET['vid_id'])."'")
or die(mysql_error());
Without escaping your variables properly, you are making yourself vulnerable to SQL injection attacks.
EDIT
To simplify the above, you can do a few tricks:
// Apply mysql_escape_string to every item in $_POST
array_map('mysql_real_escape_string', $_POST);
// Get rid of $_POST, $_POST['Title'] becomes $p_Title
extract($_POST, EXTR_PREFIX_ALL, 'p_');
// Use sprintf to build your query
$query = sprintf("UPDATE
Videos
SET
Title = '%s',
Preacher = '%s',
Date = '%s',
Service = '%s',
File = '%s',
Description = '%s'
WHERE
id = '%s'",
$p_Title,
$p_Preacher,
$p_Service,
$p_File,
$p_Description,
mysql_real_escape_string($_GET['vid_id']));
mysql_query($query) or die(mysql_error());
Note that mixing $_POST and $_GET variables is not encouraged. You should supply the update ID through an hidden input field in the form.
As you are using DB API directly (no DB abstraction level) the best solution is to use DB escape function.
Just use mysql_real_escape_string().
<?php
// Your query
$query = sprintf("UPDATE Videos SET Title='%s', preacher='%s', Date='%s', "
."Service='%s', File='%s', Description='%s' WHERE id='%s'",
mysql_real_escape_string($_POST['Title']),
mysql_real_escape_string($_POST['Preacher']),
mysql_real_escape_string($_POST['Date']),
mysql_real_escape_string($_POST['Service']),
mysql_real_escape_string($_POST['File']),
mysql_real_escape_string($_POST['Description']),
mysql_real_escape_string(($_GET['vid_id']));
?>
As a bonus you'll get a really improved security against SQL INJECTION attacs your previous code was prone.
In the case you would simply escape slashes you have, again, to use php/mysql functions addslashes() will do the job in this case.
Why are you putting a \" right at the end, this puts a " on to the end of your SQL but you don't have one at the start?
Try this:
mysql_query("UPDATE Videos SET Title=".$_POST['Title'].", Preacher=".$_POST['Preacher'].", Date=".$_POST['Date'].", Service=".$_POST['Service'].", File=".$_POST['File'].", Description=".$_POST['Description']."WHERE id=".$_GET['vid_id']) or die(mysql_error());
REMOVE \", from:
id=".$_GET['vid_id']."\""