How do I escape a single quote&double quote in SQL Server? - php

I'm using SQL2000.
How can i escape single quote&double quote into query without get SQLi?
PHP:
$Username = "s'ql'fp".'"ffo"t';
SQL:
$Query = "INSERT INTO Users (Username, Password) VALUES (".$Username.", '432432')";
mssql_query($Query);
Sorry for my bad english :S

You must enclose string constants in single quotes and double all single quotes within them in SQL:
PHP:
$Username = "s'ql'fp".'"ffo"t'";
SQL:
$Query = "INSERT INTO Users (Username, Password) VALUES ('"
. str_replace("'", "''", $Username),
. "', '432432')";
mssql_query($Query);
str_replace("'", "''", $Username) will be "s''ql''fp".''"ffo"t''", i. e. all single quotes doubled. This does not change your $Username variable, but just the string used as SQL statement.
Probably, you would do that for the password as well (if it is not a string you know does not contain quotes, as is the case for the literal password you use here).

mysqli_real_escape_string() on the inserted data should do the trick.
You should also put your varchar()s in brackets, escaping won't help if you insert VALUES (SOME STRING) this works mainly with integers.

Related

I cant seem to insert a special character like “\” in a MySQL database in PHP?

I cant seem to insert a special character like “\” in a MySQL database
here's my code
<?php
$insert_data = mysqli_query($con, "INSERT INTO table_name (id, img) VALUES('', '<img title="\sum" src="http://latex.codecogs.com/gif.latex?\sum" data-mce-src="http://latex.codecogs.com/gif.latex?\sum" data-mce-selected="1">')");
?>
You need to escape the " in your query.
Since you are using PHP, you need to escape backslash (\) with another backslash like this \\ inside a string
<?php
$insert_data = mysqli_query($con, "INSERT INTO table_name (id, img) VALUES('', '<img title="\\sum" src="http://latex.codecogs.com/gif.latex?\\sum" data-mce-src="http://latex.codecogs.com/gif.latex?\\sum" data-mce-selected="1">')");
?>

MySQL query is not working when I use single apostrophe symbol ( ' ) in query

I am creating simple form using PHP and MySQl. But When I enter the apostrophe symbol (') as input in one of the textbox in the form, the query is not working. It does not insert any record to the database due to apostrophe symbol.
Following is the simple example of MySQL query using PHP.
mysql_query("insert into users (username,passwd,name,mobile) values ('$username','$passwd','$name','$mobile')")
You need to escape input data, when you're using mysql, you need mysql_real_escape_string function.
mysql_query("insert into users (username,passwd,name,mobile) values (
'" . mysql_real_escape_string($username) . "',
'" . mysql_real_escape_string($passwd) . "',
'" . mysql_real_escape_string($name) . "',
'" . mysql_real_escape_string($mobile) . "')"
);
As a bonus you get protection against SQL injection.
Because there are a lot of outdated answers I will give you a clean(er) solution by using PDO. You should switch immideatly to PDO or mysqli because your code will most likely crash in a few months/in less than a year (as soon as PHP7 is out):
$pdo = new PDO('mysql:...');
$stmnt = $pdo->prepare("insert into users (username,passwd,name,mobile) values (?, ?, ?, ?)");
$stmnt->execute(array($username, $passwd, $name, $mobile));
As fields username, password, phone does not contain single quotes, you need not to use any function to remove quotes from form data, you can simply use query like :
mysql_query("insert into users (username,passwd,name,mobile) values ('".$username."','".$passwd."','".$name."','".$mobile."')")
or you can remove quotes from form data if required.
Use htmlspecialchars() function to encode single quotes and insert into Database and while fetching that data use htmlspecialchars_decode() function which decodes back to single quotes.

Insertion query in sql php function

i'am beginner in php and i have problem in insertion query
if(isset($id)){
$qry = "insert into user_to_birds(user_id,tax_id)values( 1 ,'.$id .') ";
$result = mysql_query($qry);
}
I'am connected to the database but the query didn't work.
Why it is not working? how can i correct it?
Don't create queries this way. It is very vulnerable to SQL injection.
Use a prepared statement instead. A prepared statement is precompiled, hence will not be subject to SQL injection.
$id = 99;
$tax = 8;
$stmt = $mysqli->prepare("insert into user_to_birds(user_id,tax_id)values(?,?)"));
$stmt->bind_param("ii", $user, $tax);
$stmt->execute();
.. work on it ..
$stmt->close();
ii stands for two integers. After that first part of the binding, telling which type of variables you use in which order, can you add the values of those variables to the statement. The values will be escaped automatically using this method.
if(isset($id)){
$qry = "insert into user_to_birds(user_id, tax_id)values('1','$id') ";
$result = mysql_query($qry);
}
Work like a charm.
I think your single quotes should be double quotes:
$qry = "insert into user_to_birds(user_id,tax_id )values( 1 ,".$id .") ";
You are confusing strings in PHP with strings in SQL (which is, admittedly, easy to do).
For how to insert into there's a nice article here
http://www.w3schools.com/php/php_mysql_insert.asp
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
//not sure if this will make a difference buy i would try a space between tax_id) and values(
also, im not sure if the way youve done it is wrong but i would have written like this
if(isset($id))
{
$qry = "insert into user_to_birds (user_id, tax_id)
values( '1' ,'".$id ."') ";
$result = mysql_query($qry);
}
look at string concatination aswell either have
" ' ' ".$variable." ' ' ";
in that fashion
As others have said, it looks like you're not using string concatenation correctly in your query. Try changing your query to something like:
$qry = "INSERT INTO user_to_birds (user_id,tax_id) VALUES ( 1 ,'$id') ";
Another possibility is that your $id variable isn't set. Try printing out the variale before doing the isset() check and that will tell you if you need to look at an earlier point in your code.
Finally, I'd recommend you look at mysqli functions rather than mysql.
http://php.net/manual/en/book.mysqli.php
You have some confusion in quotes: your string in " ", your sql value in ' ', but when you concatenate you need to close your string and write dot and variable, after this you need write dot, open string quotes again and write text if it needed. Your mistake - you didn't close string (") before concatenation and this leads to misinterpretation of the code. In this case your code will look like:
$qry = "insert into user_to_birds(user_id,tax_id)values( 1 ,'" .$id ."') ";
But you can not use concatenation,you can do it simply: PHP allows write your variable $id in string, without use concatenation:
$qry = "insert into user_to_birds(user_id,tax_id)values( 1 ,'$id') ";

My insert statement (php to mysql) fails to use my variables

It must be the simplest error, but I dont see nor find it.
I fill a variable $aa_minerid with value 7.
I use this variable in a insert.
The insert always inserts a 0 (zero) in the database never a 7
The field i put it in is a smallint(6)
I tried
VALUES ('$aa_productid')
VALUES ($aa_productid)
VALUES ("$aa_productid")
VALUES ('{$aa_productid}')
VALUES ("{$aa_productid}")
and all with use of ` aswell
into script placed hereafter.
If I put there : VALUES ( 7 )
It does work perfect.
So what do I do wrong in this script?
BTW the echo at the end DOES show the right value of the variable $aa_productid
<?php
/* This php script should transfer data from the aa to the sql database */
// Info coming from aa
$aa_productid = 7 ;
include ("dogs.inc");
$cxn=mysqli_connect($host,$user,$passwd,$dbname);
$query = 'SELECT * FROM `Price` WHERE '
. ' `Time_Stamp`=(select max(`Time_Stamp`) from `Price` where `Product_ID` = \'1\')';
$result=mysqli_query($cxn,$query) or
die("Couldn't execute select query");
$row = mysqli_fetch_row($result);
$aa_price=$row[3] ;
$aa_value = $aa_price * $aa_amount;
// Info ready to go to database
$sqlinsert = 'INSERT INTO Mining (Product_ID)'
. ' VALUES ( $aa_productid )' ;
echo $aa_productid;
Single quotes don't do variable expansion in PHP. But I would recommend you use prepared statements, such as:
$stmt = $cxn->prepare('INSERT INTO Mining (Product_ID) VALUES ( ? )');
$stmt->bind_param('i', $aa_productid);
$stmt->execute();
See the documentation at prepare and bind_param.
This will protect you from SQL injection.
Try
'.$aa_productid.'
or
".$aa_productid."
Depending on the type of apostrophe used to beging the string, use the same one.
Also, if You are using ", then You should be able to Just do
$insert="INSERT INTO $tablename;";
It's been a while since I have done any PHP but..
I think you need to have smartquotes turned on
Try this instead:
$sqlinsert = 'INSERT INTO Mining (Product_ID)'
. ' VALUES ('. $aa_productid .' )' ;
concatenate the variable into the query.
When you are using variables within quotes, you must use the double-quote if you want PHP to parse variables within it. So, this would work:
$sqlinsert = 'INSERT INTO Mining (Product_ID) VALUES ('.$aa_productid.')';
Or this would:
$sqlinsert = "INSERT INTO Mining (Product_ID) VALUES ($aa_productid)";
Try:
$query = "SELECT * FROM Price WHERE Time_Stamp=(select max(Time_Stamp) from Price where Product_ID = "1")";
$sqlinsert = "INSERT INTO Mining (Product_ID) VALUES ( '$aa_productid' )" ;
Also, its always a good idea to escape the strings before entering them in the db.
Try this syntax instead:
$sqlinsert = "INSERT INTO Mining (Product_ID) VALUES ("' . $aa_productid . '")";
no need to concatenate the two parts of the insert. Also double quoting the variable seems to avoid problems.

Insert query problem with php mysql

This is simple one i am using the following insert query
mysql_query(insert into table1 set saltval = 'Y'Z' where uid ='1');
but i does not work becaues the value for the field saltval is Y'Z . my question is how to considered this value is as a string .
You need to escape any single quotes with a backslash.
mysql_query("insert into table1 set saltval = 'Y\'Z' where uid ='1'");
However your SQL is invalid as well... Did you mean to do an update? Insert statements don't have a where.
As mentioned in other answers, if the input is from a user then you should use mysql_real_escape_string()
http://www.php.net/manual/en/function.mysql-real-escape-string.php
$string = mysql_real_escape_string("Y'Z");
mysql_query("insert into table1 set saltval = '{$string}' where uid ='1'");
Always use mysql_real_escape_string() function for this if values come from user input
$query="insert into table1 set saltval = '".mysql_real_escape_string($InputVal)."' where uid ='1'";
See http://php.net/manual/en/function.mysql-real-escape-string.php
You have to add a backslash to certain characters to make your string fit into SQL syntax rules.
Assuming you're creating your query dynamically, PHP has special escaping function for this and you should use it for the every quoted string in the query, no exceptions.
So, write your code like this:
$salt = "Y'Z";
$id = 1;
$salt = mysql_real_escape_string($salt);
$id = mysql_real_escape_string($id);
$sql = "update table1 set saltval = '$salt' where uid ='$id'";
mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
to make it safe and fault-tolerant

Categories