2012-12-09 35 views
0

我有兩個問題SQL注入檢查和PHP拋出錯誤

  1. 是下面的代碼(它似乎插入方法工作OK)執業針對SQL注入

  2. 如何的好方法會在發生在完整的例子此錯誤消息:

    if (!mysqli_query($query,$link)) 
    { 
        die('Error: ' . mysqli_error()); 
    } 
    

這裏是完整的例子:

<?php 

$link = mysqli_connect("localhost","root","", "runtracker"); 
if (!$link) 
{ 
    die('Could not connect: ' . mysqli_error()); 
} 

$query="INSERT INTO userinfo (UserName) VALUES (?)"; 

if ($stmt = mysqli_prepare($link, $query)) { 

    // Lets create the variables 
    $name = $_POST['UserName']; 

    // Bind the variables and execute the query 
    mysqli_stmt_bind_param($stmt,"s", $name); 
    mysqli_stmt_execute($stmt); 

    // And now we close the statement 
    mysqli_stmt_close($stmt); 
} 

echo "1 record added"; 

mysqli_close($link); 
?> 
+0

哪裏,就是這樣,你做任何事情,以保護自己免受SQL注入? – 2012-12-09 17:46:45

+0

@JackManey,他正在使用準備好的聲明。 – Charles

回答

1

是的,對於SQL查詢中的動態值,使用綁定參數是防止SQL注入的好方法。有關SQL注入的更多信息,您可能會喜歡我的演示文稿SQL Injection Myths and Fallacies

你說得對,在調用API函數後檢查錯誤是很好的。大多數mysqli函數在錯誤時返回FALSE,但連接處理方式稍有不同。

我也喜歡將mysqli錯誤輸出到我可以讀取的日誌中,但不會輸出到用戶的瀏覽器。

這裏的我會怎樣代碼時:

<?php 

$mysqli = new mysqli("localhost","root","", "runtracker"); 
if (mysqli_connect_error()) 
{ 
    error_log("Connect error in file ".__FILE__.", line ".__LINE__.": " 
     .mysqli_connect_error()); 
    die("Could not connect to database"); 
} 

if (($stmt = $mysqli->prepare($link, $query)) === false) { 
    error_log("Error on prepare in file ".__FILE__.", line ".__LINE__.": " 
    .$mysqli->error); 
    die('Error on prepare'); 
} 

// Lets create the variables 
$name = $_POST['UserName']; 

// Bind the variables and execute the query 
if ($stmt->bind_param("s", $name) === false) { 
    error_log("Error on bind in file ".__FILE__.", line ".__LINE__.": " 
    .$stmt->error); 
    die('Error on bind'); 
} 
if ($stmt->execute() === false) { 
    error_log("Error on execute in file ".__FILE__.", line ".__LINE__.": " 
    .$stmt->error); 
    die('Error on execute'); 
} 

// And now we close the statement 
$stmt->close(); 

echo "1 record added"; 

$mysqli->close(); 
+0

謝謝,先生 –