使用PHP更新MySQL数据库

时间:2017-01-23 17:26:18

标签: php mysql

您好我正在尝试使用php更新我的mysql数据库。我可以用以下内容完美地更新它:

<?php

$conn = mysqli_connect("localhost", "root", "", "logintest");

if(!$conn){
    die("Connection failed: ".mysqli_connect_error());
}
?>

<?php

    $sql = "UPDATE user SET bot = '1' WHERE id = 9";

    if($conn -> query ($sql) === TRUE){
        echo "record updated successfully";
    }else{
        echo "Error updating record" . $conn -> error;
    }

    $conn -> close ();

?>

但是在我将上面的bot列更新为1之前,我想检查它是否为0,因为它只能是0或1。 要做到这一点,我做了以下(见下文),但它没有工作,是否可能和或有没有不同的方式这样做?感谢所有帮助!!

$sql = "SELECT bot FROM user"; // bot is the column in the table which should be 0 or 1

        if( $sql == '0') { //if its 0 i can update it

            echo 'here'; //if i get here i will update using code above
     }

2 个答案:

答案 0 :(得分:1)

有两种方法

  1. SELECTUPDATE

    $query = "SELECT bot FROM user where id=9"
    $res = $conn->query($query);
    
    if ($res->num_rows == 1) {
    // it should return only one row as id is unique
      $row = $result->fetch_assoc()
      if($row["bot"] == 0){
            // UPDATE 
      }
    }
    
  2. CASE构建

    UPDATE  user SET bot = CASE 
        WHEN bot = 0 
           THEN 1 
           ELSE bot 
        END 
    WHERE id='9'
    
  3. 工作原理:

    根据匹配案例的返回值更新机器人值。如果当前bot值为0,则返回1,否则返回current value的{​​{1}}行。

    优势:只有1个查询

答案 1 :(得分:0)

请尝试

<?php

$conn = mysqli_connect("localhost", "root", "", "logintest");

if(!$conn){
    die("Connection failed: ".mysqli_connect_error());
}

$sql= "SELECT bot FROM user where columnid=value"; // change is according to your real value
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        if($row["bot"] == 0){
            $sql = "UPDATE user SET bot = '1' WHERE id = 9";

            if($conn -> query ($sql) === TRUE){
                echo "record updated successfully";
            }else{
                echo "Error updating record" . $conn -> error;
            }
        }
    }
}

$conn -> close ();
?>