Sending a slash through mysql
I'm not sure why this has stumped me. I have the following code
$website = "http://www.google.com";
$name = "Person";
if(!empty($website) {
$name = "[url=$website]$name[/url]";
}
Then i try to insert that into mysql. I tried adding mysql_real_escape_string to both $websit开发者_运维问答e and $name (after the if statement), thinking the "/url" might also cause problems.
$name = mysql_real_escape_string($name);
Still no luck though. Any advice? What am I missing? It's giving me this error
"Parse error: syntax error, unexpected '/', expecting T_STRING or T_VARIABLE or T_NUM_STRING"
try
if(!empty($website)) {
$name = "[url={$website}]{$name}[/url]";
}
then use,
mysql_real_escape_string ($name);
This is a PHP syntax problem. The parser thinks $name[ is the start of a array reference you have to add curly bracelets to tell the parser where the variable name starts and end: "[url={$website}]{$name}[/url]"
There wont be any problem at all. When reading from database you should then put stripslashes()
around your value.
e.g.
$query = "SELECT field FROM table";
$row = mysql_fetch_array(mysql_query($query));
echo(stripslashes($row['field']));
And your output will be the same like YOUR input.
Make sure you're quoting values you send into a query, like so:
$sql = "INSERT INTO table (column) VALUES ('$value')";
Whatever is in $value gets passed into the query. If you leave out the quotes, bad things may happen even if you use mysql_real_escape_string()
. Inside strings, forward slashes do not have any special meaning in MySQL, and so mysql_real_escape_string()
leaves them intact. This is not a bug, but the documented, correct behaviour. Basically, you need to quote all values in your query.
However, the best solution IMHO is to use PDO and its parametrized queries instead of the mysql_XXX API. It's a bit more complicated (not much though), and it allows you to pass parameters into a query through an associative array, doing all the escaping and quoting you need for you.
Are you putting quotes around the value you want to insert? This will work
INSERT INTO table_name (column_name)
VALUES ('[url=$website]http://www.google.com[/url]')
This will fail
INSERT INTO table_name (column_name)
VALUES ([url=$website]http://www.google.com[/url])
So you might have in you php
$query = "INSERT INTO table_name (column_name) VALUES ('$name')";
// DO MYSQL_QUERY
精彩评论