使用变量更新数据库表


Using variables to update database table

我正在尝试根据填充的下拉列表更新用户信息。我可以访问主键并将其回显(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();
}
}

您的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()是没有用的。