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.
Related
Here is my code below:
$studentTalking = mysql_real_escape_string($_POST['studentTalking']);
//Finally, we can actually the field with the student's information
$sql = <<<SQL
UPDATE `database` SET
`studentName`='$studentName',
`studentEmail`='{$data['studentEmail']}',
`studentPhone`='{$data['studentPhone']}',
`studentID`='{$data['studentID']}',
`studentTalking`= '{$studentTalking}',
`resume` = '{$data['resume']}'
WHERE `id`={$data['date_time']} AND (`studentName` IS NULL OR `studentName`='')
SQL;
I am trying to use the mysql_real_escape_string to allow apostrophes entered into our form by the user to go to the database without breaking the database, however the data will either go through as null or the apostrophe will break the database. I have changed everything I could think of, and can't figure out why this isn't working. Yes I understand the that injections could break our database, and we will work on updating the code soon to mysqli but we need this working now. I suspect my syntax isn't correct and the first line may need to be moved somewhere, but I am not the strongest in PHP and I am working with code that was written by previous interns. Thank you in advance.
Switch to mysqli_* functions is the right answer.
The answer if intend to stayg with the deprecated and dangerous mysql_* functions:
Here you set a new variable equal to your escaped $_POST[]:
$studentTalking = mysql_real_escape_string($_POST['studentTalking']);
But in your SQL you still refer to the $_POST array... Switch your SQL over to use your new variable you created
$sql = <<<SQL
UPDATE `tgtw_rsvp` SET
`studentName`='$studentName',
`studentEmail`='{$data['studentEmail']}',
`studentPhone`='{$data['studentPhone']}',
`studentID`='{$data['studentID']}',
`studentTalking`= '$studentTalking',
`resume` = '{$data['resume']}'
WHERE `id`={$data['date_time']} AND (`studentName` IS NULL OR `studentName`='')
SQL;
Because you are not using the stripped variable but still the raw POST data.
I have made a database where email id and corresponding name and password is stored. I have successfully obtained a form's data.. where the user enters updated name and password. But the problem is occuring with the query which is as follows
$db = mysqli_connect(all details)...
$name = $_POST['name'];
$password = $_POST['password']:
$email = $_POST['email'];
$query = "UPDATE mytable SET name='$name',password='$password' WHERE emailid='$email'";
$result = mysqli_query($db,$query);
Though I am getting all form values succesffuly and until and unless I put the 'where' clause.It works.But obviously updates all values. i want it to work with where..but so far unsuccessful :(
you need to put {} around the variables if its surrounded by quote ''
so your query should look like this
$query = "UPDATE mytable SET name='{$name}',password='{$password}' WHERE emailid='{$email}'";
$result = mysqli_query($db,$query);
EDIT : also before saving data to database make sure to filter and validate data
You need to make sure that emailid exists in mytable, you truly intended to filter by it and in your database scheme it has a type which supports the posted data. It seems that you are sending strings, like 'foo#bar.lorem' and your emailid is an int or something in the database scheme. Check it by running
desc mytable;
You need to put curly brackets around variables if you use apostrophe around them, but as a matter of style I like to close the string and attach the $variable with a . as this coding style is closer to me personally.
If everything fails, see what is generated, by echoing out the query string, try to run that directly, see what the error is and fix until...
... until it is fixed.
Also, you do not encrypt the password and your code is vulnerable to SQL injection too. Please, read about password encryption and SQL injection and then protect your project against these dangers.
You can write your statement as:
$query = "UPDATE mytable SET name='".$name."',password='".$password."' WHERE emailid='".$email."'";
using . as string concatenating operator
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
When I execute this query it returns false, which means the query is wrong. Can you figure out why?
$string1 = 'wee';
$string2 = 'wee';
$string3 = 'wee';
$string4 = 'wee';
if (isset($_POST['submit'])) {
$query = "INSERT INTO data (book, title, content, author)
VALUES ($string1, $string2, $string3, $string4)";
mysql_query($query, $con);
}
However, when I put something that is like the following, it returns true and inserts correctly:
$query = "INSERT into data (book, title, content, author)
VALUES ('wee', 'wee', 'wee', 'wee')";
And another question: when I submit, it seems that the query is returning twice when executed which means two records with one query. Does anyone understand that?
If you need more information, just ask.
Thanks in advance.
Although this question seems answered, you should not be using user input directly in queries as this opens holes for vulnerabilities like SQL Injection (and that's bad mmmay)
If you look at the mysql page on php.net (mysql_query) the page says it is recommended you use an abstraction layer like PDO (pdo-mysql)
Using PDO will allow you to bind parameters to your sql queries to bypass the security implications of using user input in your queries.
If you don't bind parameters to your queries, you're gonna have a bad time.
Your field data type is string or varchar so you need to put '' or "" around them.
Change your query as below
$query = "INSERT into data (book, title, content, author)VALUES ('".$string1."', '".$string2."',
'".$string3."', '".$string4."')";
To resolve submit issue, please post your html code
When a user searches on my site, I grab the get request and do a mysql query against it. My original code looked something like this: $q = $_GET['q'];.
Right now urldecode is adding slashes for me, but I decided to aslo try filter_var with the santize string filter.
Here is my sql when I use $q = urldecode($_GET['q']);:
SELECT * FROM item WHERE title LIKE '%you\'re%' OR description LIKE '%you\'re%' ORDER BY date DESC
and here is my sql when I use: q = filter_var(urldecode($_GET['q']), FILTER_SANITIZE_STRING);
SELECT * FROM item WHERE title LIKE '%you\'re%' OR description LIKE '%you\'re%' ORDER BY date DESC
The sql is exactly the same, but I get different results and I'm not sure why? Just using urldecode returns the correct results from the database, but filter_var returns nothing (even though the sql is the same).
I guess my question is, is what's the best way to sanitize and search query string?
Urldecode is the wrong function to use - PHP will automatically decode any variables in $_GET so you don't need to, and the PHP Manual says doing so is dangerous.
Often people talk about sanitizing input, but I prefer to think about sanitizing output.
For example, sanitizing input would be:
$q = urldecode($_GET['q']);
$sql = "SELECT * FROM item WHERE title LIKE '%{$q}%'"
// later
echo "These items match '$q'";
And sanitizing output:
$sql = "SELECT * FROM item WHERE title LIKE '%".mysql_real_escape_string($_GET['q'])."%'"
// later
echo "These items match '".htmlspecialchars($_GET['q']).'";
Notice how in the latter example I've used different functions - one for converting the data into a mysql safe format, the other for converting the data into an HTML safe format. You can't know which function you want to run until you know what you're doing with the data.
Others have mentioned parameterised queries. Yes, these are about as secure as you can get and avoid accidental errors, but are not easy to switch to overnight.
Don't try to sanitize your data.
Use parametrized queries.
See http://bobby-tables.com/php.html for examples.
I would do:
$q = mysql_real_escape_string( stripslashes( $_GET['q'] ) );
The best variant is to use php Sanitize filters http://php.net/manual/en/filter.filters.sanitize.php,