Hi when ever I want to insert a comment into my database, I sanitize the data by using Mysql Escape String function this however inserts the following verbatim in field. I print the comment and it works fine and show me the text however when ever I sanitize it, it literally inserts the following into my db
mysql_real_escape_string(Comment)
This is my insert statement, The Id inserts correctly however the comment doesn't it just inserts the "mysql_real_escape_string(Comment)" into the field. what can be wrong?
foreach($html->find("div[class=comment]") as $content){
$comment = $content->plaintext;
$username = mysql_real_escape_string($comment);
$querytwo = "insert into Tchild(Tid,Tcomment)values('$id','$username')";
$resulttwo = $db -> Execute($querytwo);
}
If I'm reading the documentation correctly, you should make the call like this:
$db->Execute("insert into Tchild(Tid,Tcomment)values(?, ?)", array($id, $username));
That will account for proper escaping. Having unescaped values in your query string is dangerous and should be avoided whenever possible. As your database layer has support for SQL placeholders like ? you should make full use of those any time you're placing data in your query.
A call to mysql_real_escape_string will not work unless you're using mysql_query. It needs a connection to a MySQL database to function properly.
Since you're using ADODB, what you want is probably $db->qstr(). For example:
$username = $db->qstr($comment, get_magic_quotes_gpc());
See this page for more information: http://phplens.com/lens/adodb/docs-adodb.htm
Related
After a lot of searching the web, the times I see this error, it looks really scenario specific. So far, I haven't found one that matched my scenario. I think my issue is coming from a prepared statement with spatial data type params.
The way I'm executing my code is:
$sql = $conn->prepare("INSERT INTO states(`name`, `poly`) VALUES(':name',GeomFromText('GEOMETRYCOLLECTION(:coords)'));");
$res = $sql->execute(['name'=>$name, 'coords'=>$coords]);
if($res){
echo "... Successfully Inserted<br><br>";
}
else{
echo "... Failed<br><br>";
print_r($sql->errorInfo());
echo "<br><br>";
}
The above is failing. The connection to the database has been tested. Since these are rather large geometry sets, instead of pasting my code, I'll show how I verified my SQL:
Dumping a raw SQL file and copy/pasting the SQL into a phpMyAdmin window, everything inserted just fine.
$sqlStr = "INSERT INTO states(`name`, `poly`) VALUES('$name',GeomFromText('GEOMETRYCOLLECTION($coords)'));";
$check = file_put_contents('./states/'.$name.'2.sql', $sqlStr);
So it's because of this, that I believe my sql is correct, but it my problem is likely due to the prepare/execute portion somehow. I'm not sure if spatial data types can't be assigned like this?
Edit
I also want to note that I am on PHP version 5.5.9 and I've executed queries in the original method, with the params in the execute just fine.
There's no way the code at the end could be working. Parameters in the query must not be put inside quotes.
Since GEOMETRYCOLLECTION(:coords) has to be in a string, you need to use CONCAT() to create this string.
$sql = $conn->prepare("
INSERT INTO states(`name`, `poly`)
VALUES(:name,GeomFromText(CONCAT('GEOMETRYCOLLECTION(', :coords, ')')));");
It sounds strange to me. I have a simple PHP script that inserts data into MYSQL table.
Upon receiving the content from the client via AJAX the data is stored in a variable:
$content=$_POST['content'];
$sql="insert into contents values('$content')";
mysql_query($sql);
The problem is that if the content contains a '&' symbol,the sub-string before & is stored in MYSQL and the rest of the string is discarded. If I try directly in MYSQL then it stores complete string containg & symbol.why?
The problem is that mysql regocnizes '&' as AND. Check this out:
$content = mysql_real_escape_string($_POST['content']);
$sql = "insert into contents (column) values('$content')";
mysql_query($sql);
First off if this site is live take it down lol. This is classic sql injection vulnerability.
You need to be using mysqli now instead of mysql.
The way you use this is the same but it has this REALLY cool feature called 'real escape string'
What it does is parameterize the data before you pass it into the database
$content = $_POST['content'];
$connection = new mysqli('ipaddress','username','password','database');
$content = $connection->real_escape_string($content);
$sql="insert into contents values('$content')";
$connection->query($sql);
This is a much safer way of passing in data
Before I put data into my database I pass it through mysql_real_escape_string.
If I want to copy that same data into another table, do I need to pass it through mysql_real_escape_string again before I copy it?
I wrote a small script to test the issue and it looks like the answer is yes:
$db = new AQLDatabase();
$db->connect();
$title = "imran's color";
$title = mysql_real_escape_string($title);
$sql = "insert into tags (title, color) values ('".$title."','#32324')";
$db->executeSQL($sql);
$sql = "select * from tags where color = '#32324' ";
$result = $db->executeSQL($sql);
while($row= mysql_fetch_array($result))
{
$new_title = $row['title'];
}
$new_title = mysql_real_escape_string($new_title);
$sql = "insert into tags (title, color) values ('".$new_title."','DDDDD')";
$db->executeSQL($sql);
NOTE: If I remove the second mysql_real_escape_string call, then the second insert won't take place
Are doing something like this?
save mysql_real_escape_string($bla) to database
fetch $bla from database
save $bla again (in another table..)
Fetching $bla from the database will "unescape" it so it could be a harmful string again. Always escape it again when saving it.
Before I put data into my database I always make it go the Mysql_real_Escape_String thing.
You are doing right. Just keep it as is. Not database though but query it is.
The only note: only strings should be escaped using this function. It shouldn't be used with any other query parts.
do I need to make it go through the Mysql_real_Escape_String again before I copy it?
Didn't you answer your question already? Before I put [string-type] data into my [query] I always make it go the Mysql_real_Escape_String thing. Is your data going to SQL query? So, here is an answer you have already.
Well, if you are sure this data is already properly escaped, there is no need to.
mysql_real_escape_string is for 1) escaping 2) security purposes. Since it's your own data base and as long as you pass data to another database outside a potential hacker reach - you are already safe
Its already scaped, just copy it as is, if you want to undo the mysql_real_escape_string you can use stripslashes($sting) to remove it
PD: This is false and now i understand why.
Just wondering, to sanitize user input, I use mysql_real_escape_string() on data before it is inserted into a table. Therefore when a user enters something like this:
Hi I'm just testing this
It gets placed into the table just fine, exactly as above. Question is, if I were to pull that data and place it into a variable via PHP, say $string, what would happen if I then used that variable to insert data into a new row in the table? Such as:
<?php
$result = mysql_query( "SELECT data FROM table WHERE id='1'" ); //data = Hi I'm just testing this
$result_array = mysql_fetch_array( $result );
$string = $result_array['data']; //string = Hi I'm just testing this
$insert = mysql_query( "INSERT INTO table (data) VALUES ('$string')" ) or die(mysql_error());
?>
Would the single quote (') cause problems in this scenario? Should I be using $string = mysql_real_escape_string( $result_array['data'] ) in this case as well?
Thanks!
Once the data's pulled out of MySQL, it's just like any other piece of data that you want to use in a query: You have to do proper escaping/quoting, or use a prepared statement. There's no magical flag within PHP that says "this came from the database and shall return whence it came".
The alternative is to use the INSERT INTO ... SELECT FROM syntax to do the operation completely within the database, if you can meet the conditions.
mysql_real_escape_string() simply prepares it for insertion into the database, once you request that data again it will be in its original form, i.e. you will have to sanitize it again before trying to insert it like your example above.
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.