2016-10-04 99 views
0

我有一個POST PHP腳本,我想檢查POST數據是否已經存在於數據庫中,如果它確實存在,則拋出錯誤消息,如果它不將它添加到數據庫並且成功信息。Mysqli_num_rows無法正常工作

它成功地增加了,但如果我嘗試添加已經存在的名稱,它提供了錯誤:

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, string given in 

和反正添加新的數據。

代碼:

<?php // _POST Add Major Category 
    if(isset($_POST['AddMajorCat'])) 
    { 
     // Declare _POST Variables 
     $POSTNewMajorCatName = $_POST['MajorCatName']; 

     // Check if name exists in database 
      include_once('connection.php'); // db connection 

      $query = "SELECT * 
           FROM DowntimeCategoriesMain 
           WHERE DowntimeCategoriesMain.maincategory = '$POSTNewMajorCatName'"; 

      $response = mysqli_query($db, $query); // Send Statement 
      $NumRows = mysqli_num_rows($query); // Count number of rows 

       if ($NumRows != 0) { 
        $messageSendTitle = "Uh-oh!"; 
        $messageSend = "Major Downtime Category " . $POSTNewMajorCatName ." already exists. Unable to add Category."; 
        $messageSendType = "error"; 
       } 
       else { // If name doesn't exist in database, add 
            include_once('connection.php'); // db connection 

            $query = "INSERT INTO DowntimeCategoriesMain (maincategory) 
                 VALUES ('$POSTNewMajorCatName')"; 

                 $response = mysqli_query($db, $query); // Send Statement 

                   if ($response) { // Successful 
                    $messageSendTitle = "Success!"; 
                    $messageSend = "Major Category " . $POSTMajorCatName . " was added. "; 
                    $messageSendType = "success"; 
                   } 
                   else { // Unsuccessful 
                    $messageSendTitle = "Uh-oh!"; 
                    $messageSend = "There seems to be a problem. MySQL Error: " . mysqli_error($db); 
                    $messageSendType = "error"; 
                   } 
        } // else statement 

     } // If _POST is set statement 
?> 

我試圖交換mysqli_num_rows($query);$query->num_rows;,它不再顯示錯誤,但還是增加了數據。

+1

請使用準備好的語句。 –

+0

'$ NumRows = mysqli_num_rows($ response);' – Jeff

回答

2

您是否真的看過錯誤信息?它告訴你到底什麼是錯的。 $query是一個字符串,它想要一個mysqli_result,這是$response你的情況:

$response = mysqli_query($db, $query); 
$NumRows = mysqli_num_rows($response); 
0

你通過了$query作爲mysqli_num_rows()的說法,這又是基於你的代碼的字符串。你必須通過$response

$NumRows = mysqli_num_rows($response); 
2

錯誤信息給你一個提示,是什麼問題。 mysqli_num_rows需要一個資源作爲參數。你正在給你的$query變量這是一個字符串。您想要提供給mysqli_num_rows的資源位於$response變量中。所以,你需要的是這樣的:$NumRows = mysqli_num_rows($response);

此外,通過直接串接$POSTNewMajorCatName變量到你的查詢字符串,你打開自己高達SQL注入攻擊。您可以通過使用準備好的語句來防止此情況。 mysqli_prepare函數就是你用來做這個的。您可以在這裏查看文檔mysqli_prepare