保存按钮,一旦记录已保存在数据库中,也可以更新

时间:2018-04-12 03:29:55

标签: php

我想知道如何为if-else语句构造正确的语法,或者我的代码中是否缺少某些内容。

<?php
    include "../dbcon.php";
    session_start();
    ob_start();
    $sql = mysqli_query($con,"SELECT * FROM clientdocuments  WHERE docID = $_POST[docID]");
    $rows = mysqli_fetch_array($sql, MYSQLI_ASSOC);
    //IF CSS input value is filled
    if(!empty($_POST)){
        $output = '';  
        $message = '';  
        $docID = mysqli_real_escape_string($con, $_POST["docID"]);
        $docSIG_Contract = mysqli_real_escape_string($con, $_POST["docSIG_Contract"]); 
        //I don't get what this "if(isset($_POST["docID"])){" purpose (Sorry very new to php)
        if(isset($_POST["docID"])){
            if (!empty($docID)) {
                $query = "UPDATE clientdocuments(docID, docSIG_Contract) VALUES('$docID', '$docSIG_Contract');"; //UPDATE ONCE docID ALREADY EXIST ON THE DATABASE 
            } else {
                $query = "INSERT INTO clientdocuments(docID, docSIG_Contract) VALUES('$docID', '$docSIG_Contract');"; //INSERT IF THE docID doesn't exist yet
            }
            $str = mysqli_query($con,$query);
            if(!$str){
                echo 'FAILED';
            }
        }else{
            header('HTTP/1.1 500 Internal Server Booboo');
            header('Content-Type: application/json; charset=UTF-8');
        } 
    }
?>

2 个答案:

答案 0 :(得分:1)

  1. 删除此if语句:if (!empty($docID)) {

  2. 确保您随每个帖子发送更新&#34; docID&#34;值

答案 1 :(得分:0)

if(isset($ _ POST [&#34; docID&#34;]))语句检查名称为docID的输入是否具有值。

if(!empty($ _ POST))我不确定这是否有效,我的猜测是你试图检查请求方法是否是POST(如果点击了保存按钮) )。为此,我使用 if($ _SERVER [&#39; REQUEST_METHOD&#39;] ===&#39; POST&#39;){

然后我会检查docID是否有值ie (isset($ _ POST [&#34; docID&#34;]))(!empty($ _ POST [&#34; docID&#34;])) isset和!之间的区别 What's the difference between 'isset()' and '!empty()' in PHP?

如果有值,$ query将是update语句 如果没有值$ query将是insert语句在这种情况下不要输入DocID值(因为它总是0,这也会导致错误)

希望有意义!