Can't use mysql_real_escape_string

為{幸葍}努か 提交于 2019-12-04 20:03:50

First point: If you're getting an error from mysql_real_escape_string(), it's because you are calling the function before you're connected to the database.

It looks like you connect to the database right before you run a query. So anything you do before you call your mm_mysqlquery() function won't have a connection.

The mysql_real_escape_string() function needs a live connection to the database, so it can do the right kind of escaping with respect to the connection's character set. So you need to connect before you do escaping.

It's better to do that anyway, because if you make several queries during the course of a single PHP request, it's less overhead to connect once and use the same connection for all your queries.

Second, please don't take suggestions to use addslashes() -- it does not do the same thing as mysql_real_escape_string(). The two are not interchangeable. You should get into the habit of using mysql_real_escape_string().

Third, your sani() function shows a common misconception.

function sani($string){     
  $string = strip_tags($string); 
  $string = htmlspecialchars($string); 
  $string = trim(rtrim(ltrim($string))); 
  $string = mysql_real_escape_string($string);
  return $string;
}

The common misconception is that you need all these functions to make a string safe in an SQL statement. You don't. Only mysql_real_escape_string() is necessary. All the other functions in this example do nothing to protect against SQL injection.

Those functions are useful if you output a string in an HTML presentation and you want to reduce the risk of XSS attacks, but then mysql_real_escape_string() is irrelevant.

Use each type of sanitizing method in its appropriate context.

string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier ] )

Where $unescaped_string is your string and $link_identifier is your db resource.

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

PHP.NET mysql_real_escape_string resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!