用PHP从mysql表中减去一个数量

时间:2017-11-28 09:51:08

标签: php mysql

我正在尝试执行一个PHP代码,该代码减去存储在名为''''''的mysql表中的数量的-1。 该表以10开头,如果使用值caffe执行php,则表中的数量将更新。 将是一些良好的代码行,以便我能理解它是如何工作的。

  1. 从网址读取值:http://mypage/getdata.php?value=caffe
  2. 从数据库表caffe
  3. 读取值
  4. 从表中减去-1
  5. 更新mysql表caffe
  6. 的值
    <?
    $servername = "localhost";
    $username = "xxx";
    $password = "";
    $database = "my_ufficina";
    
    
    //creating a new connection object using mysqli 
    $conn = new mysqli($servername, $username, $password, $database);
    
    //if there is some error connecting to the database
    //with die we will stop the further execution by displaying a message causing the error 
    if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    }
    
    //if everything is fine
    
    $txt = $_GET['value'];
    
    if ($txt == caffe)
    $count = 1;
    
    echo $count;
    

1 个答案:

答案 0 :(得分:0)

我会尝试这样的事情:

if ($txt === 'caffe') {

    // get Caffe value :

    try {
        $currentCaffeValue = $conn->query("SELECT yourCaffeValue FROM yourTable");
    } catch (Exception $e) {
        echo 'db read failed : ', $e->getMessage();
    }

    // do your stuff then update Caffe value :

    try {
        $conn->query("UPDATE yourTable SET yourCaffeValue = yourCaffeValue - 1");
    } catch (Exception $e) {
        echo 'db update failed : ', $e->getMessage();
    }
}

顺便说一句,你应该在使用它之前清理$ _GET中的值:http://php.net/manual/en/function.filter-input.php