2017-08-16 96 views
-1

我一直試圖讓這個語句更新我的分貝,但沒有成功。我有一個表單允許用戶更新他們的用戶名和電子郵件。我忽略了什麼?PDO準備好語句更新不起作用

這裏是我的發言:

<?php require_once('config.php'); 
    $id= $_SESSION['id'];//get user id you can use session also 
    if (isset($_POST['submit'])){ 
     $username = $_POST['username']; 
     $email = $_POST['email']; 
       $query = "UPDATE members SET username = :username ,email = :email WHERE id = :id"; 
      $stmt = $db->prepare($query); 
      $stmt->bindParam(':username',$username, PDO::PARAM_STR); 
      $stmt->bindParam(':email', $email, PDO::PARAM_STR); 
     } 

    $query = "SELECT * FROM members WHERE id = $id"; //Get user info 
    $stmt = $db->prepare($query); 
    $stmt ->execute(); 
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC); 
    if ($result) { 
     // output data of each row 
    foreach($result as $row){ 
     $username = $row['username']; 
     $email = $row['email']; 

     } 

    } 
?> 

這裏是我的形式:

<form role="form" class="cf-form floating-labels" method="post" action="<?php filter_input(INPUT_SERVER, 'PHP_SELF', FILTER_SANITIZE_FULL_SPECIAL_CHARS); ?>"> 
    <fieldset> 
     <legend>My Account<br />   
     <img class="logo_contact" src="img/jobmiser_logo2.png" alt="jobmiser logo" /> 
     </legend> 
     <div class="icon"> 
      <label class="cf-label" for="username">Username</label> 
      <input class="user" type="text" name="username" id="username" value="<?php echo $username ?>" tabindex="2" required /> 
     </div> 
     <div class="icon"> 
      <label class="cf-label" for="email">Email</label> 
      <input class="email" type="email" name="email" id="email" value="<?php echo $email ?>" tabindex="3" required /> 
     </div> 
    </fieldset> 
    <fieldset> 
     <div class="icon"> 
     <input name="submit" type="submit" value="Update" /> 
     </div> 
    </fieldset> 
</form> 
+0

考慮加入一些代碼來登錄或發出錯誤信息,這是一個有點可疑看到您的SQL語句三個佔位符,只有2'bindParam's ... – fvu

+2

看來你'UPDATE members'查詢缺少「:id」的綁定,你永遠不會執行它!? – xander

回答

0

您需要的綁定:id參數在您更新查詢:

// bind :id 
$stmt->bindParam(':id', $id, PDO::PARAM_INT); 
// You also need to execute it 
$stmt ->execute(); 

在第二個語句你也應該綁定值的id,而不是直接插入到字符串中。

// BAD 
$query = "SELECT * FROM members WHERE id = $id"; 

// GOOD 
$query = "SELECT * FROM members WHERE id = :id"; //Get user info 
$stmt = $db->prepare($query); 
$stmt->bindParam(':id', $id, PDO::PARAM_INT); 
$stmt ->execute();