2015-12-02 144 views
1

我試圖根據填充的下拉列表更新用戶信息。我能夠訪問主鍵並將其回顯(ID),但我似乎無法得到信息更新。使用變量更新數據庫表

這是我的功能;

function updateTable() { 

if (isset($_POST['submit'])) { 
    global $db; 
    $first_name = $_POST['first_name']; 
    $last_name = $_POST['last_name']; 
    $address = $_POST['address']; 
    $city = $_POST['city']; 
    $state = $_POST['state']; 
    $phone = $_POST['phone']; 
    $email = $_POST['email']; 
    $category = $_POST['category']; 

    $id = $_POST['users']; 

    $query = "UPDATE customers SET "; 
    $query.= "first_name = '$first_name', "; 
    $query.= "last_name = '$last_name' "; 
    $query.= "address = '$address', "; 
    $query.= "city = '$city' "; 
    $query.= "state = '$state', "; 
    $query.= "phone = '$phone' "; 
    $query.= "email = '$email', "; 
    $query.= "category = '$category' "; 
    $query.= "WHERE id = $id "; 
    echo $id; 


    $statement = $db->prepare($query); 
Try 
{ 
$statement->execute(); 
$users = $statement->fetchAll(); 
} 
Catch (PDOException $e) 
{ 
    $error_message = $e->getMessage(); 
    include('database_error.php'); 
    exit(); 
} 
$statement->closeCursor(); 

} 
} 
+0

檢查您的查詢是否成功 - 如果沒有,它將返回布爾值false。在這種情況下,您可以使用錯誤處理來查看出錯的地方 - 記錄或打印錯誤。在這種情況下,您的查詢中存在拼寫錯誤,在''last_name'後面缺少逗號。 – andrewsi

+0

在更一般的說明 - 這是*而不是*你應該如何生成你的SQL。這會在您的代碼中引入巨大的注入漏洞。您正在使用的數據庫庫將允許您使用準備好的語句並綁定參數。 _使用它們_。 – andrewsi

+0

也在電話='$電話'「和'」城市='$城市'「'和類別也缺少逗號 – Standej

回答

3

在SQL中有許多語法錯誤,但是您應該使用預準備語句將變量綁定到SQL查詢。

不確定您是否在這裏使用MySQLi或PDO。對於MySQLi嘗試這樣的事情;

$query = "UPDATE customers SET 
    first_name = ?, 
    last_name = ?, 
    address = ?, 
    city = ?, 
    state = ?, 
    phone = ?, 
    email = ?, 
    category = ? 
    WHERE id = ?"; 

$statement = $db->prepare($query); 
$statement->bind_param('ssssssssi',$first_name,$last_name,$address,$city,$state,$phone,$email,$category,$id); 
$statement->execute(); 

或爲PDO試試這個;

$query = "UPDATE customers SET 
    first_name = :firstname, 
    last_name = :lastname, 
    address = :address, 
    city = :city, 
    state = :state, 
    phone = :phone, 
    email = :email, 
    category = :category 
    WHERE id = :id"; 

$statement = $db->prepare($query); 
$statement->bindParam(':firstname',$first_name); 
$statement->bindParam(':lastname',$last_name); 
$statement->bindParam(':address',$address); 
$statement->bindParam(':city',$city); 
$statement->bindParam(':state',$state); 
$statement->bindParam(':phone',$phone); 
$statement->bindParam(':email',$email); 
$statement->bindParam(':category',$category); 
$statement->bindParam(':id',$id,PDO::PARAM_INT); 
$statement->execute(); 

由於這是一個更新查詢,所以沒有結果可以提取。所以fetchAll()沒有用。

+0

可能會使用pdo接口:) – Ghost