使用变量更新数据库表

时间:2015-12-02 23:56:07

标签: php mysql prepared-statement

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

}
}

1 个答案:

答案 0 :(得分: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()没用。