2017-01-31 28 views
-1

我有兩種用戶類型的註冊表單,分別是Surveyee和Client。在涉及同一領域時他們有相似之處,但Surveyee有更多。因此,我希望我的Surveyee插入代碼避免使用一列,因爲它僅適用於客戶端usertype。如何在插入PHP時跳過某些表列?

<?php 
if(isset($_POST['submit'])){ 

    include("connection.php"); 
    $username = $_POST['username']; 
    $fullname = $_POST['fullname']; 
    $email = $_POST['email']; 
    $age = $_POST['age']; 
    $password = $_POST['password']; 
    $confirmpassword = $_POST['confirmpassword']; 
    $gender = $_POST['gender']; 
    $occupation = $_POST['occupation']; 

    $user = mysqli_query($con, "SELECT username from user WHERE username = '".$username."'"); 
    $count = mysqli_num_rows($user); 

    if($password != $confirmpassword){ 
     echo "Password does not match!"; 
    } 
    else{ 
     if($count != 0){ 
      echo "Username already exists!"; 
     } 

     else{ 

      $insert = mysqli_query($con, "INSERT INTO `user` (`username`,`fullname`,`email`,`companyname`,`age`,`password`,`gender`,`occupation`,`usertype`) VALUES (`$username`,`$fullname`,`$email`,``,`$age`,`$password`,$gender`,`$occupation`,`Surveyee`)"); 
      if(!$insert){ 
       echo mysqli_errno(); 
      } 
      else{ 
       echo "Records have been saved!"; 
      } 
     } 
    } 
} 
?> 

這裏是我的表設計 enter image description here

我試圖避免列公司名稱,但我得到一個錯誤。警告:mysqli_errno()期望恰好有1個參數,第29行給出的0,即if(!$ insert){echo mysqli_errno(); }部分

$insert = mysqli_query($con, "INSERT INTO `user` (`username`,`fullname`,`email`,`companyname`,`age`,`password`,`gender`,`occupation`,`usertype`) VALUES (`$username`,`$fullname`,`$email`,``,`$age`,`$password`,$gender`,`$occupation`,`Surveyee`)"); 
     if(!$insert){ 
+0

**切勿將明文密碼!**請使用PHP的[內置函數(http://jayblanchard.net/proper_password_hashing_with_PHP.html)來處理密碼的安全性。如果您使用的PHP版本低於5.5,則可以使用'password_hash()'[兼容包](https://github.com/ircmaxell/password_compat)。確保你*** [不要越獄密碼](http://stackoverflow.com/q/36628418/1011527)***或在哈希之前使用其他任何清理機制。這樣做*更改密碼並導致不必要的附加編碼。 –

+0

[Little Bobby](http://bobby-tables.com/)說*** [你的腳本存在SQL注入攻擊風險。](http://stackoverflow.com/questions/60174/how-can- ***)瞭解[MySQLi](http://php.net/manual)[準備](http://en.wikipedia.org/wiki/Prepared_statement)聲明/en/mysqli.quickstart.prepared-statements.php)。即使[轉義字符串](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string)是不安全的! [不相信它?](http://stackoverflow.com/q/38297105/1011527) –

+0

插入NULL或爲每個用戶類型分別查詢。 –

回答

1

刪除撇號('),並使用反引號(`)括列名和表名。

$insert = mysqli_query($con, "INSERT INTO `user` (`username`,`fullname`,`email`,`companyname`,`age`,`password`,`gender`,`occupation`,`usertype`) VALUES ('$username','$fullname',$email','',$age','$password','$gender','$occupation','Surveyee')"); 

而且,

INSERT INTO (Column_Name, Column_Name) Table_Name VALUES ('','');語法也是不對根據你定的查詢。

將其更改爲,

INSERT INTO `Table_Name` (`Column_Name`, `Column_Name`) VALUES ('',''); 
+0

爵士編輯我的問題。我仍然得到了同樣的錯誤,雖然:(@nana partykar – ranger

+0

@ranger:你編輯它錯了,我已經在我的答案寫了,只有列名稱需要包括在反引號中,而不是值,你也爲值。查詢。 –

+1

這個答案不值得讚賞 –