2016-04-23 69 views
-1

我想使用mysqli,php插入表單數據。我堅持的問題是它插入'?'作爲表格中的值而不是我在表單中輸入的值?我知道我在某個地方出了問題,但我無法弄清楚。如何使用MySqli/PHP插入表單數據?

我的另一個問題是:使用mysqli語句這樣插入或從數據庫中選擇數據是否安全,因爲我猜想$ _POST成爲注入攻擊的威脅。現在是否足夠我在這裏寫作來防止攻擊,還是需要添加更多內容?

任何建議都會有很大的幫助。

這裏是我的代碼

的index.php

<?php 

     session_start(); 
     include('db.php'); 

?> 

<!DOCTYPE html> 

<head> 

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <meta name="viewport" content="width=device-width,initial-scale=1" /> 
    <link rel="stylesheet" type="text/css" href="style.css"/> 

</head> 

<body> 


<?php 

    if(isset($_POST['login']) && $_POST['login'] == 'Login') { 
     $loginEmail = $_POST['loginEmail']; 
     $loginPassword = $_POST['loginPassword']; 

     $query = $db->prepare("INSERT INTO dbname(password,email) VALUES ('?','?');"); 
     $query->bind_param("ss",$loginEmail,$loginPassword); 
     $query->execute(); 

    }   
    ?> 

     <div id="login">    
      <strong>Login</strong> 

      <br/><br/> 

      <form action = "<?php echo $_SERVER['PHP_SELF'];?>" method="POST"> 
       <table style="width:500px">       
        <tr> 
         <td><input type="text" name="loginEmail" placeholder = "Email" required/><br/></td> 
        </tr>      
        <tr> 
         <td><input type="password" name="loginPassword" placeholder = "Password" required/><br/></td> 

        </tr> 
       </table> 

       <input style="font-weight: bold; width: 70px; height: 25px; border-radius: 5px;" type="submit" name="login" value="Login"/> 
      </form> 
     </div>  
</body>  
</html> 

db.php中

<?php 

     $host = 'host'; 
     $user = 'user'; 
     $password = 'password'; 
     $database = 'dbname'; 

     $db = new mysqli($host, $user, $password, $database); 

     if($db->connect_errno > 0){ 
      die('Unable to connect to database ['.$db->connect_errno.']'); 
     } 
?> 
+0

你有語法錯誤在你準備好的聲明中,並沒有檢查錯誤。然後你使用純文本輸入密碼。如果你活着或打算接受這個,不要。使用'password_hash()'。 –

+0

您不應該在數據庫中存儲純文本密碼。請參閱[password_hash()](http://php.net/manual/en/function.password-hash.php)和[password_verify()](http://php.net/manual/en/function.password- verify.php) – RiggsFolly

+0

@fred:你的意思是password_hash($ loginPassword)? –

回答

2

使用

$db->prepare("INSERT INTO users(password,email) VALUES (?, ?);"); 

而不是

$db->prepare("INSERT INTO users(password,email) VALUES ('?','?');"); 

ps。訂單很重要:在您的bind_param()中,您的電子郵件和密碼的順序與查詢中的順序相反。

0

刪除INSERT查詢中的引號。

$query = $db->prepare("INSERT INTO dbname(password,email) VALUES (?,?);"); 

另外,我建議你使用的功能,如stripslahes()trim()

用途:

$loginEmail = trim (stripslashes($_POST['loginEmail'])); 
$loginPassword = stripslashes($_POST['loginPassword']); 
+1

'trim()'在密碼上?另外,爲什麼在使用準備好的語句時甚至需要額外的無用功能? –

+0

好點!但修剪當然可以使用。 –

+1

看到這個問題在堆棧http://stackoverflow.com/questions/36628418/cleansing-user-passwords你會明白我的意思。另外,如果用戶在其密碼或用戶中有\,那麼您發佈的內容可能會失敗。密碼數組不應該被操縱。 –