PHP,如果基于初始行计数,if / else的插入和更新不起作用

时间:2018-09-16 23:18:02

标签: php mysql sql

我这里有一个问题。

我正在提交一个表格,当他第一次提交表格时,我只需要插入两次(我必须插入内容,然后插入与内容关联的面板记录),但是如果面板类型该页面ID已经存在,我需要获取存在的内容记录并对其进行更新。

问题在于,我在if($existingPanel->count == 0){行遇到mysqli_result :: $ count的未定义属性的错误,因此不再插入,请进行更新。

在根据计数添加新的if / else之前,它起作用。

如何更好地构造它以便使其正常工作?

$content = $_POST['page_content'];
$panelID = $_POST['panel_type'];
$pageID = $_POST['page_id'];


//Check is a panel record exists for the page
$checkIfExists = "SELECT COUNT(*) AS count FROM panels WHERE panel_type_id = $panelID AND page_id = $pageID";

$existingPanel = $mysqlConn->query($checkIfExists);

//if no record exists for the panel type in this page
if($existingPanel->count == 0){

    //add content record
    $addContent = "
        INSERT INTO content(content)
        VALUES('$content');
    ";

    if ($mysqlConn->query($addContent) === TRUE) {
        $cont_id = $mysqlConn->insert_id;
        $data['last_insert_id'] = $cont_id;
        echo json_encode($data);
    } else {
        echo "Error: " . $addContent . "<br>" . $mysqlConn->error;
    }

    //add panel record with association to content
    $addPanel = "
        INSERT INTO panels(panel_type_id, page_id, cont_id)
        VALUES ('$panelID', '$pageID', '$cont_id');
    ";

    if ($mysqlConn->query($addPanel) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $addPanel . "<br>" . $mysqlConn->error;
    }

//if the count is 1 from $checkExisting
}else {


    //get content ID for the existing content
    $checkContentExists = "SELECT cont_id as existingContent FROM panels WHERE panel_type_id = $panelID AND page_id = $pageID";

    $existingContent = $mysqlConn->query($checkContentExists);

    //execute and update content for the content ID
    if($mysqlConn->query($checkContentExists)){

        $updateContent = "
            UPDATE content
                SET content = '$content'
                WHERE id = $existingContent->existingContent;";
    }
}

0 个答案:

没有答案