mysql_real_escape_string not letting string through - php

I'm trying to sanitize a string going into my database. But with the code below, I don't get the update to my db.
First page posts this in an input form:
$note="Here is some example text";
Receiving page:
$note = $_POST['note'];
$note = mysql_real_escape_string($note);
$sql="UPDATE some_table SET notes='$note' WHERE id='$some_id'";
$result=mysql_query($sql);
When I take out the mysql_real_escape_string line it works, but not with it in there.
What am I missing?
Thanks!

I strongly recommend using Prepared Statement, mysql_real_escape_string() won't full protect you from SQL Injection.
Example for your update:
<?php
// connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$sql = "UPDATE some_table
SET notes=?
WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($$_POST['note'], $some_id));
?>
More details: http://www.php.net/manual/en/intro.pdo.php

Related

Update query not working in PHP and Mysql

I have made an update page which fetches record from a table, shows all the details on html form where user can change/Edit the values and submit. Next page fetches those values using $_POST and Update the table.
$new_id = $_POST['c_id'];
$new_name = $_POST['c_name'];
$table_name = "tcompany";
$sqlStatement = "UPDATE $table_name SET 'name'=$new_name WHERE 'id'= $new_id";
if($result_1 = mysql_query($sqlStatement))
{
header('Location: edit_company.php');
}
else {
echo "". mysql_error();
}
I am getting 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 ''name'=HARDWARE Exporters WHERE 'id'= 69' at line 1
I am not considering security issues related to injection. Using this code for personal use.
Don't use apostrophe (') for column names and use it instead to your variables.
$sqlStatement = "UPDATE ".$table_name." SET name='$new_name' WHERE id='$new_id'";
You should also sanitize the values you are binding to your query. Use *_real_escape_string.
$new_id = mysql_real_escape_string($_POST["c_id"]);
And mysql_* API is already deprecated and you should consider using mysqli prepared statement instead.
If you want an example of prepared statement, using the code you have given, you can refer below. No need to sanitize each values before using them to your query.
/* ESTABLISH FIRST YOUR CONNECTION */
$con = new mysqli("YourHost","Username","Password","Database"); /* REPLACE NECESSARY DATA */
if($stmt = $con->prepare("UPDATE ? SET name = ? WHERE id = ?")){ /* CHECK IF STATEMENT IS TRUE */
$stmt->bind_param("ssi",$table_name,$_POST["c_name"],$_POST["c_id"]); /* BIND VALUES TO YOUR QUERY */
$stmt->execute(); /* EXECUTE THE QUERY */
$stmt->close();
} /* END OF PREPARED STATEMENT */
The problem is that variable $new_name contains spaces. So you should quote the use of variables in the statement, like this:
$sqlStatement = "UPDATE $table_name SET 'name'='$new_name' WHERE 'id'= '$new_id'";

mysql query does not get updated due to apostrophe sign

$url = "example.com";
$data = json_decode($raw);
$pname=$data->name;
$sql="UPDATE `client` SET pname='$pname' WHERE url='$url'";
$query=mysql_query($sql,$link)or die(mysql_error());
When the json data is decoded, the value in variable $pname goes in client table. If there is an apostrophe sign (') in name then it throws an error. What changes can I make in the variable to send the name to database table?
example:
Jerry get updated with no issues
D'Cunha does not get updated as it has the apostrophe sign. The query becomes
"UPDATE `client` SET pname='D'Cunha' WHERE url='example.com'"
I found some articles but that does not say about how to find the apostrophe sign and change the variable value
use mysql_escape_string()
$sql="UPDATE `client` SET pname='".mysql_escape_string($pname)."' WHERE url='$url'";
and learn mysqli or PDO as mysql is deprciated and soon going to be drop
Use prepared statements. Mysqli or PDO. Here's an example with mysqli:
$url = "example.com";
$data = json_decode($raw);
$pname=$data->name;
$mysqli = new mysqli($host, $user, $password, $db);
$stmt = $mysqli->prepare("UPDATE client SET pname = ? WHERE url = ?");
$stmt->bind_param("ss", $pname, $url);
$stmt->execute();
Why shouldn't I use mysql_* functions in PHP?
Try this:
UPDATE client SET pname = 'D\'Cunha' WHERE url = 'example.com'

not updating the sql database

i wrote the following code,but its not updating the database,,its a part of a script and it cease to work..cant find a way around it .. need suggestions
<?php
$link = mysql_connect('xxxxxxxx');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xxx", $link);
$usernames='aneeshxx';
echo $usernames;
$update = "INSERT sanjana SET $name ='$usernames'";
mysql_query($update, $link);
$update1 = "INSERT INTO sanjana (name)VALUES ($usernames)";
mysql_query($update1, $link);
?>
$update = "INSERT sanjana SET $name ='$usernames'";
this probably is meant as an UPDATE statement, so for an update it should be
$update = "UPDATE sanjana set name = '$usernames'";
I put name and not $name due to your second query and not seeing $name being defined anywhere. Be aware that this will change the value in the column name of every row in the sanjana table to the value of $usernames, normally a statement such as this gets limited by conditions, e.g. WHERE userid = 33
$update1 = "INSERT INTO sanjana (name) VALUES ($usernames)";
for an INSERT statement it needs to have the values quoted so
$update1 = "INSERT INTO sanjana (name) VALUES ('$usernames')";
Be wary that this way of putting variables directly into your query string makes you vulnerable to SQL injection, to combat this please use the PDO or mysqli extensions, they both protect you from injection by providing you with prepared statements ; plain old mysql_* is not recommended for use anymore.
using pdo you'd use prepared statements like this
<?php
// we got $usernames from wherever you define it
$pdo = new PDO('mysql:dbname=mydb;host=localhost','username','password');
// to insert
$statement = $pdo->prepare('INSERT INTO `sanjana` (name) VALUES (:name)');
// the following replaces :name with $usernames in a safe manner, defeating sql injection
$statement->bindParam(':name',$usernames);
$statement->execute(); // it is done
// to update
$statement = $pdo->prepare('UPDATE `sanjan` SET `name` = :name');
$statement->bindParam(':name',$usernames);
$statement->execute(); // it is done
so as you can see protecting your code from malicious input is not hard and it even makes your SQL statements a lot easier to read. Did you notice that you didn't even need to quote your values in the SQL statement anymore? Prepared statements take care of that for you! One less way to have an error in your code.
Please do read up on it, it will save you headaches. PDO even has the advantage that it's database independent, making it easier to use another database with existing code.
The right update sql clause is like so:
UPDATE table
SET column = expression;
OR
UPDATE table
SET column = expression
WHERE predicates;
SQL: UPDATE Statement
Your query should be like this:
$update = "UPDATE sanjana SET $name ='$usernames'";
mysql_query($update, $link);
Of course you need to specify a row to update (id), other wise, the whole table will set column $name to $usernames.
UPDATE:
Because you are inserting a data in empty table, you should first execute $update1 query then execute $update query. UPDATE clause will make no change/insert on empty table.
Problem 1: use the correct "insert into" (create new record) vs. "update" (modify existing record)
Problem 2: It's good practice to create your SQL string before you call mysql_query(), so you can print it out for debugging
Problem 3: It's also good practice to detect errors
EXAMPLE:
<?php
$link = mysql_connect('xxxxxxxx')
or die('Could not connect: ' . mysql_error());
mysql_select_db("xxx", $link);
$usernames='aneeshxx';
$sql = "INSERT INTO sanjana (name) VALUES ('" . $usernames + ")";
echo "sql: " . $sql . "...<br/>\n";
mysql_query($sql, $link)
or die(mysql_error());
You have INSERT keyword for your update SQL, this should be changed to UPDATE:
$update = "UPDATE sanjana SET $name ='$usernames'";

Is php site only using mysql SELECT safe from sql injection attack

I have a website that uses a db to store information for site users. All the mysql db calls are SELECT. I use $_GET to pass variables from page to page that are then used in the mysql SELECT calls. I don't use UPDATE or INSERT in any of my code.
Do I have to worry about sql injection attacks?
Do I have to protect the db from some other type of attack?
I'm willing to read and learn. I just don't know if it's necessary in this case.
My db queries all take the form of:
$leadstory = "-1";
if (isset($_GET['leadstory'])) {
$leadstory = $_GET['leadstory'];
}
$query_News = "SELECT * FROM news WHERE lead_story = $leadstory";
$News = mysql_query($query_News, $HDAdave) or die(mysql_error());
$row_News = mysql_fetch_assoc($News);
$totalRows_News = mysql_num_rows($News);
Are the first three lines replaced with:
$statement = $db_connection->prepare("SELECT * FROM news WHERE lead_story = ?;';");
$statement->bind_param("s", $leadstory);
$statement->execute();
$row_News = $statement->fetchAll();
What is the replacement for $totalRows_News?
Do I also have to clean the $leadstory?
Thanks for your help.
That would a be "yes", I think.
SELECT * FROM users WHERE name='hacker' or name='Admin' and '1'='1'
With the supplied name being hacker' or name='Admin' and '1'='1
Yes, you do have to worry about SQL injection attacks.
Use PDO and prepared statements to protect your queries.
$stmt = $pdo->prepare('SELECT * FROM table WHERE id = ?');
$stmt->bindParam(1, $_GET['id']);
$stmt->execute();
$rows = $stmt->fetchAll();
Simple answer, yes. If any part of your sql statement comes from a request or form submission by the client, you need to sanitize/escape it.
Use PDO and prepared statements, or mysql_real_escape_string()

Is mysql_real_escape_string() unsafe against hexadecimal encoded data?

We know that all user input must be escape by mysql_real_escape_string() function before executing on mysql in php script. And know that this function insert a \ before any ' or " character in user input. suppose following code:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='".mysql_real_escape_string($_POST['username']."' AND password='".mysql_real_escape_string($_POST['password']."'";
mysql_query($query);
// This means the query sent to MySQL would be:
echo $query;
this code is safe.
But I find out if user enters her inputs with hexadecimal format then mysql_real_escape_string() can not do any thing and user can execute her sql injection easily. in bellow 27204f522027273d27 is same ' OR ''=' but in hex formated and sql execute without problem :
$_POST['username'] = 'aidan';
$_POST['password'] = "27204f522027273d27";
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='".mysql_real_escape_string($_POST['username']."' AND password='".mysql_real_escape_string($_POST['password']."'";
mysql_query($query);
// This means the query sent to MySQL would be:
echo $query;
But whether this is true and if answer is yes how we can prevent sql injection in this way?
If you are using mysql_real_escape_string(), odds are you would be better served using a prepared statement.
For your specific case, try this code:
/*
Somewhere earlier in your application, you will have to set $dbh
by connecting to your database using code like:
$dbh = new PDO('mysql:host=localhost;dbname=test', $DBuser, $DBpass);
*/
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";
$user = $_POST['username'];
$password = $_POST['password'];
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user=? AND password=?";
$stmt = $dbh->prepare($query);
$stmt->bindParam(1, $user);
$stmt->bindParam(2, $password);
$stmt->execute();
This does require you to use PDO for your database interaction, but that's a good thing overall. Here's a question discussing the differences between PDO and mysqli statements.
Also see this StackOverflow question which is remarkably similar to yours and the accepted answer, from which I poached some of this answer.

Categories