Inserting Row in MySQL From Existing Row That Contains Quotes - php

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.

Related

& can't be inserted in MYSQL through PHP

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

Insert mysql error when parsing a webpage

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

mysql_real_escape_string again if copying 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.

How to add data off HTML page into MySQL DB

How can I add data from a HTML page, into a MySQL Database based on the attributes?
It's already scraped data, but I would like to import links into a particular field in a table and remove some things from them (ill work that out) and another from into another field in a table.
I have PHP/MySQL and Linux. Should I use curl, and if so how do I actually add data into a MySQL DB?
Some PHP example to Insert and update data:
//***************************************
// Connect to database
//
mysql_connect('127.0.0.1','MyUserName','MyPassword',false,MYSQL_CLIENT_SSL|MYSQL_CLIENT_COMPRESS);
mysql_select_db('MyDatabase');
// If you work with UTF-8 it would be a good idea to set the character set as well to be sure.
//mysql_set_charset('utf8_general_ci');
//***************************************
// Insert new data
//
$MyURL = mysql_real_escape_string("http://www.exampledomain.com/product/");
$Result = mysql_query("INSERT INTO ProductTable (URLField) VALUES ('".$MyURL."')");
if($Result)
print mysql_affected_rows();
//***************************************
// Update existing data
//
$MyURL = mysql_real_escape_string("http://www.exampledomain.com/newproduct/");
$RecordID = 123;
$Result = mysql_query("UPDATE ProductTable SET URLField='".$MyURL."' WHERE ID=".$RecordID);
if($Result)
print mysql_affected_rows();
Connect to the MySQL Server with mysql_connect() and use mysql_select_db() to select the database.
I'm not native English and use UTF-8 to get all the special character correct. If you have no need of this you can ignore this line.
All data that goes into a SQL server should be be sanitized, meaning escaping control characters such as quotes. The Variable $MyURL is sanitized with mysql_real_escape_string() before it is used in the SQL statement.
The SQL statement is executed with mysql_query() and returns true or false (for INSERT and UPDATE statements). With mysql_affected_rows() you can see how many rows that was affected by the SQL statement, a way to see if it worked as expected.
Next comes an UPDATE example to change data in a single column and/or row. The $RecordID variable is the record ID you want to update (you need to know what record you want to update). This example is pinpointing a single record. By changing the WHERE clausule you can update a whole bunch of rows at the same time. For example
UPDATE ProductTable SET URLField='".$MyURL."' WHERE URLField='http://www.exampledomain.com/oldproduct/'
...will update all rows that have 'http://www.exampledomain.com/oldproduct/' in the field URLField.
I think this will get you going for a while...
http://us3.php.net/manual/en/function.mysql-query.php
You will then use a MySQL query like "INSERT INTO table_name (column1,column2) VALUES ('Testing','Testing 2')

Inserting data in oracle database using php

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.

Categories