2016-09-02 92 views
-7

我想在我的SQL插入由GET數據,但我不能插入數據插入數據通過GET

<?php 

include("config.php"); 

$f=$_GET["first_name"]; 
$l=$_GET["last_name"]; 
$e=$_GET["email"]; 
$m=$_GET["mobile"]; 
$b=$_GET["birthday"]; 
$g=$_GET["gender"]; 



$insert="INSERT INTO user (`first_name`, `last_name`, `email`, `mobile`, `birthday`, `gender`) 
VALUES ('$f', '$l', '$e', '$m', '$b', '$g')"; 
mysqli_query($insert); 



?> 

我通過這個鏈接嘗試插入數據:

http://localhost:8888/restfull/insert.php?f=hayoo

+2

你正在使用錯誤的GET數組。 '?f'?這將無法正常工作。你也需要'&'運算符。 –

+3

您也沒有將db連接傳遞給查詢。閱讀手冊http://php.net/manual/en/mysqli.query.php –

+5

您可以[** SQL注入**](https://www.owasp.org/index.php/SQL_Injection )。至於你的問題,考慮一下:你正在''_GET'中使用不存在的值。這並不奇怪,不起作用。 –

回答

1

我已經使用mysqli很長一段時間了,下面的代碼應該很可能運行。正如其他人所提到的,從不綁定未經過處理的數據(即使您認爲您信任數據,仍然可以安全地使用準備好的數據)。

<?php 
//Create you db connection 
$conn = new mysqli('server', 'user', 'password', 'databasename'); 
//Create insert statement. Never concat un-sanitized data in statements 
$insert="INSERT INTO user (`first_name`, `last_name`, `email`, `mobile`, `birthday`, `gender`) 
VALUES (?, ?, ?, ?, ?, ?)"; 


$stmt = $conn->prepare($sql); 

//Values corespond to ? except the first param which represents format of expected data. "s" stands for string 
$stmt->bind_param(
    'ssssss', 
    $_GET["first_name"], 
    $_GET["last_name"], 
    $_GET["email"], 
    $_GET["mobile"], 
    $_GET["birthday"], 
    $_GET["gender"] 
); 
$stmt->execute(); 

您的網址應該是這樣的: http://localhost:8888/restfull/insert.php?first_name=john&last_name=Doe&[email protected]test.com&mobile=0&birthday=May&gender=male

確保,如果你是把上述網址在某些類型的表格你正確的URL編碼值(我注意到很多你收集意志值像要求它斜槓等)。