2017-05-05 66 views
1

我真的很難打破這個堅果。準備好的語句返回undefined索引錯誤

MySQL數據庫由以下列名組成:​​。

我在窗體中有一個按鈕。當我點擊「選擇」按鈕時,列名records應該更新爲+1。每次我按一下按鈕我得到的錯誤:

Notice: Undefined index: id in /Applications/MAMP/htdocs/practiceProject/updaterecords.php on line 8 Updated Succesfull

我在計算器上閱讀,這是因爲我沒有得到id的值。所以我加了$id = $_POST['id'];,但仍然得到相同的錯誤。

有沒有人知道這裏有什麼問題?

的index.php

<form action="updaterecords.php" method="post"> 
    <button type="submit" name="selectstore" >Select</button> 
    <?php include 'updaterecords.php' ?> 
    <button type="button" data-dismiss="modal">Close</button> 
</form> 

updaterecords.php

<?php error_reporting(E_ALL); ini_set('display_errors', 1); 

if (mysqli_connect_errno()) { echo "Error: no connexion allowed : " . mysqli_connect_error($mysqli); } 
?> 
<?php 
include 'dbconnection.php'; 

if(isset($_POST['selectstore'])) { 
$id = $_POST['id']; // Line 8 

    $stmt = $mysqli->prepare("UPDATE stores SET records = records + 1 WHERE id= ?"); 

    $stmt->bind_param('i', $id); 

    if ($stmt->execute()) { 
     $success = true; 
    } 

    $stmt->close(); 

    $mysqli->close(); 
    if($success) { 
     echo "Updated Succesfull"; 
    } else { 
     echo "Failed: " . $stmt->error; 
     } 
    } 

?> 
+0

你的表單是否帶有'name =「id」'的字段?如果它不'$ _POST ['id']'永遠不會被填充。 –

+0

感謝您的評論。我在這個問題上的表單,或者當我插入數據,或? – NMkdk4

+1

上面顯示的表單沒有名爲'id'的輸入,所以'$ _POST ['id']'沒有設置。爲什麼你在表單中間包含一個文件? –

回答

0

你綁定PARAM應該:id 開始也確保$id = $_POST['id'];被張貼

<form action="updaterecords.php" method="post"> 
<!-- test the id --> 
<input type="hidden" value="333" name="id" /> 
    <button type="submit" name="selectstore" >Select</button> 
    <!-- removed php include don't need it here --> 
    <button type="button" data-dismiss="modal">Close</button> 
</form> 

updaterecords.php

 <?php error_reporting(E_ALL); ini_set('display_errors', 1); 

     if (mysqli_connect_errno()) { echo "Error: no connexion allowed : " . mysqli_connect_error($mysqli); } 
     ?> 
     <?php 
     include 'dbconnection.php'; 

     if(isset($_POST['selectstore'])) { 
     $id = $_POST['id']; // Line 8 

      $stmt = $mysqli->prepare("UPDATE stores SET records = records + 1 WHERE id = :id"); 

       $stmt->bindParam(':id', $id); 

      if ($stmt->execute()) { 
       $success = true; 
      } 

      $stmt->close(); 

      $mysqli->close(); 
      if($success) { 
       echo "Updated Succesfull"; 
      } else { 
       echo "Failed: " . $stmt->error; 
       } 
      } 

     ?> 
+0

使用冒號*開始佔位符不是必需的。 http://stackoverflow.com/questions/17386469/pdo-prepared-statement-what-are-colons-in-parameter-names-used-for你也不必使用命名的佔位符,因爲'?'是*完全可以接受的佔位符。 –

+0

你好。非常感謝你的回答。我只是測試你的代碼,但我的數據庫仍然沒有用+1更新。但是當我點擊選擇按鈕時,我不會收到任何錯誤,只是'updaterecords.php'上的空白頁面。如果我使用ID號碼,我的查詢在myPhpAdmin中正常工作。 Fx:'UPDATE stores SET records = records + 1 WHERE id = 333'; – NMkdk4

+0

但它比?因爲它更容易識別參數 –

0

你沒有張貼您id的值。 你的PHP腳本應該如何知道哪一行更新? 您的html中沒有輸入字段(或類似內容),所以$_POST['id']未定義。

+0

謝謝你的答案。我在這個項目的大約25個不同文檔中使用$ _POST ['id']。除了這個之外,一切都在起作用。 – NMkdk4