Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

With PHP subtract a quantity from an mysql table

I am trying to do a php code that subtract -1 of quantity stored in a mysql table named ''caffe''. The table start with 10 and if php is executed with value caffe a quantity in table will be updated. Will be good some lines of code so i can understand how it work.

  1. read value from url: http://mypage/getdata.php?value=caffe
  2. read value from database table caffe
  3. subtract -1 from the table
  4. update the value of mysql table caffe

<?
$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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would try something like that :

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();
    }
}

And by the way, you should sanitize values from $_GET before using it : http://php.net/manual/en/function.filter-input.php


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...