2016-05-13 125 views
0

我想知道如果我添加mysql_real_escape_string我的变量足以解决SQL注入MySQL的真正转义字符串解决SQL注入明确

$get_id = "select * from `book` where id='".$mysqli->real_escape_string($id)."' limit 1"; 
+3

您的代码很容易受到[SQL-注射(http://stackoverflow.com/questions/60174/how-can-i-prevent- SQL注入功能于PHP)。请开始使用Prepared,Parameterized Queries。 –

+0

[Escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string)不安全! –

回答

1

不,事实并非如此。使用预准备的语句

你将不得不做这样的事情:

// Your connection settings 
$connData = ["localhost", "user", "pass", "database"]; 

$conn = new mysqli($connData[0], $connData[1], $connData[2], $connData[3]); 
$conn->set_charset("utf8"); 

if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 

// Here we explain MySQL which will be the query 
$stmt = $conn->prepare("select * from book where id=? limit 1"); 

// Here we tell PHP which variable hash de "?" value. Also you tell PHP that $id has an integer ("i") 
$stmt->bind_param("i", $id); 

// Here we bind the columns of the query to PHP variables 
$stmt->bind_result($column1, $column2, ...); // <--- Whichever columns you have 

// Here we execute the query and store the result 
$stmt->execute(); 
$stmt->store_result(); 

// Here we store the results of each row in our PHP variables ($column1, column2, ...) 
while($stmt->fetch()){ 
    // Now we can do whatever we want (store in array, echo, etc) 
    echo "<p>$column1 - $column2 - ...</p>"; 
} 

$stmt->close(); 
$conn->close();