什么应该添加到UPDATE查询

时间:2017-04-11 10:49:45

标签: php html sql

我想授予用户更改用户类型以成为管理员或基本用户的权限,这是我使用的代码:

第一页:

echo "<p>please type the employee ID</p><input type='number' name='id'>";
echo "<p> Change to: </p><select name='usertype'>
      <option>Admin</option>
      <option>Basic User</option>
      </select>";

点击提交后进入此页面:

$usertype= $_POST['usertype'];
$empID= $_POST['id'];
$sql="UPDATE `sap` SET `UserType`='$usertype' WHERE `ID`='$empID'";

但是当我检查数据库时没有更新任何内容,任何人都可以告诉我我错过了什么

3 个答案:

答案 0 :(得分:2)

您永远不会执行使用query()mysqli_query();

执行查询所需的查询

那么你的代码应该是

<?php

$usertype= $_POST['usertype'];
$empID= $_POST['id'];

$sql="UPDATE `sap` SET `UserType`='$usertype' WHERE `ID`='$empID'";

$run = $conn->query($sql);

if($run){

    echo "data updated";
}else{

    echo "error". $conn->error;
}

?>

<?php

$usertype= $_POST['usertype'];
$empID= $_POST['id'];

$sql="UPDATE `sap` SET `UserType`='$usertype' WHERE `ID`='$empID'";

$run = mysqli_query($conn, $sql);

if($run){

    echo "data updated";
}else{

    echo "error ".mysqli_error($conn);
}

?>

其中$conn是您的连接字符串

或更好地使用准备好的陈述:

<?php
$usertype= $_POST['usertype'];
$empID= $_POST['id'];

$sql="UPDATE `sap` SET `UserType`= ?  WHERE `ID`= ? ";
$run = $conn->prepare($sql);
$run->bindParam("si",$usertype,$empID)

if($run->execute()){

    echo "data updated";
}else{

    echo "error". $conn->error;
}
?>

或使用PDO

<?php


    $host = '';
    $db   = '';
    $user = '';
    $pass = '';
    $charset = 'utf8';

    $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
    $opt = [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
            ];


$dbh = new PDO($dsn, $user, $pass, $opt);


$usertype= $_POST['usertype'];
$empID= $_POST['id'];


$sql="UPDATE `sap` SET `UserType`= ?  WHERE `ID`= ? ";

    $stmt = $dbh->prepare($sql);

    if($stmt->execute(array($usertype,$empID))){

        echo "data updated";
    }

?>

请参阅mysqli_query

答案 1 :(得分:0)

在你的问题中,你有很多想念。因此,我决定编写完整的示例代码,您可以看到所有遗漏。 这是工作解决方案:

->

我的每一个问题都在这里。

答案 2 :(得分:0)

$host='localhost'; 
$username = 'root'; 
$pass = '';// your db password
$database = 'your db name'; // set here your db name.
$connection = new mysqli($host,$username,$pass,$database);// for db connection.

// but db connection is missed here.

 if(isset($_POST['usertype'])){ 
   $usertype= $_POST['usertype'];
   $empID= $_POST['id'];

   $sql ="UPDATE `sap` SET `UserType`='$usertype' WHERE ID ='$empID'"; 
   $result = $connection->query($sql);// it is missed in your code. 

  if($result){
  echo  'record updated successfully';  
  }else{
    echo  ' error------------- ';
  }


}