2016-08-14 28 views
0

我想做一個批量上傳功能,將用戶添加到數據庫。我有一個函數,將單個用戶的詳細信息的數據庫,我把它從一個while循環,從一個Excel工作表中讀取裏面:沒有mysqli結果內循環批量上傳

$excel = new Spreadsheet_Excel_Reader(); 
$excel->read($target_file); 

     $company = mysql_prep($_POST["company"]); 

while($x<=$excel->sheets[0]['numRows']) { 
      $username = isset($excel->sheets[0]['cells'][$x][1]) ? $excel->sheets[0]['cells'][$x][1] : ''; 
      $email = isset($excel->sheets[0]['cells'][$x][2]) ? $excel->sheets[0]['cells'][$x][2] : ''; 

      //generate random password 
      $password = generate_random_password(); 

      //hash the password 
      $hashed_password = password_encrypt($password); 
      $status = "Employee"; 

      //save details in db 
      $result = add_single_user($username, $hashed_password, $email, $status, $company); } 

功能add_single_user返回一個結果從這個循環外部調用的時候,但不會插入如上所示的用戶。我已經檢查過這些值是由excel讀者讀取並分配的。下面是函數:

function add_single_user($username, $hashed_password, $email, $status, $company){ 
global $connection; 
$safe_username = mysqli_real_escape_string($connection, $username); 
$safe_email = mysqli_real_escape_string($connection, $email); 
$safe_status = mysqli_real_escape_string($connection, $status); 
$safe_company = mysqli_real_escape_string($connection, $company); 

$query = "INSERT INTO users ("; 
$query .= " username, hashed_password, email, status, company"; 
$query .= ") VALUES ("; 
$query .= " '{$safe_username}', '{$hashed_password}', '{$safe_email}', '{$safe_status}', '{$safe_company}'"; 
$query .= ")"; 
$result = mysqli_query($connection, $query); 
return $result; 

}

+0

第一個簡單的調試/故障排除:在執行mysqli_query之前,將$ query字符串回顯到您的屏幕/瀏覽器。如果它顯示你期望的SQL - 然後複製/粘貼到你的php管理SQL窗口並測試它 – dbmitch

+0

@dbmitch謝謝。我曾嘗試複製/粘貼它,但這是一種更好的故障排除方法。有一個數據庫字段有一個限制,我沒有意識到。非常感激。 – SeemsLegit57

回答

0

對於INSERT查詢,mysqli_query返回值應該是truefalse

假設$connection實際上包含DB連接的對象,查詢應該可以工作(除了VALUES部分中可能會插入數據庫的大括號)。

嘗試查看mysqli_connect_error()mysqli_error()在連接或查詢中是否存在錯誤(無論如何,要控制是否在建立到數據庫的連接時出現錯誤並執行查詢時是一個很好的做法)。

此外,我建議您使用prepared statements而不是使用mysql_prep,real_escape_string和mysqli_query,因爲它們對注入無效。