无法同时插入和更新

时间:2015-06-19 11:34:59

标签: php mysql mysqli content-management-system sql-insert

我有下面的代码,但我无法理解为什么它不起作用。问题是我可以用它插入帖子,但是当我尝试更新帖子时,它会创建一个新页面而不是更新。

我尝试从isset删除if(isset($_POST['id']) != 'null')并更新工作,但插入功能已不再适用。

知道我的代码有什么问题吗?感谢。

    <?php 

        if(isset($_POST['submitted']) == 1) 
        {

            $title = mysqli_real_escape_string($dbc, $_POST['title']);
            $header = mysqli_real_escape_string($dbc, $_POST['header']);
            $body = mysqli_real_escape_string($dbc, $_POST['body']);

            if(isset($_POST['id']) != 'null')
            {
                $q = "UPDATE pages SET user = $_POST[user], title = '$title', header = '$header', body = '$body' WHERE id = $_GET[id]";
            }
            else
            {
                $q = "INSERT INTO pages (user, title, header, body) VALUES ($_POST[user], '$title', '$header', '$body')";
            }


            $r = mysqli_query($dbc, $q);

            if($r)
            {
                $message = '<p>Page was added!</p>';
            } 
            else 
            {

                $message = '<p>Page could not be added because:</p>'.mysqli_error($dbc);
                $message .= '<p>'.$q.'</p>';
            }

        }
    ?>

3 个答案:

答案 0 :(得分:1)

您正在使用帖子并同时获取。首先检查它是发布还是获取。然后只需执行isset()检查

<?php 

    if(isset($_POST['submitted']) == 1) 
    {

        $title = mysqli_real_escape_string($dbc, $_POST['title']);
        $header = mysqli_real_escape_string($dbc, $_POST['header']);
        $body = mysqli_real_escape_string($dbc, $_POST['body']);

        if(isset($_GET['id']) && $_GET['id']!="")

        {
            $q = "UPDATE pages SET user = $_POST[user], title = '$title', header = '$header', body = '$body' WHERE id = $_GET[id]";
        }

        else

        {
            $q = "INSERT INTO pages (user, title, header, body) VALUES ($_POST[user], '$title', '$header', '$body')";
        }


        $r = mysqli_query($dbc, $q);

        if($r)
        {
            $message = '<p>Page was added!</p>';
        } 

        else 
        {

            $message = '<p>Page could not be added because:</p>'.mysqli_error($dbc);
            $message .= '<p>'.$q.'</p>';
        }

    }
?>

答案 1 :(得分:0)

试试这个:

    <string name="order_terms_and_condtions">text... <a href="link">Terms and conditions</a> ...text</string>

答案 2 :(得分:0)

use this code:  if(isset($_POST['id'] && $_POST['id']!= '')