2015-12-02 143 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