0

我正在创建一个 CMS,当您在其中添加新页面时,display_order 将根据已经存在的行数自动获取下一个最高数字。这是我目前拥有的:

<?php

if(isset($_POST['updateContent'])){

    require ("connection.php");
    $sql = "SELECT * FROM pages";
    $result = $conn->query($sql) or die(mysqli_error());

    $content = $_POST['content'];
    $title = $_POST['title'];
    $id = $_POST['id'];

    $order = mysqli_num_rows($result);

    if (empty($id)){
        /** ADD NEW SLIDE*/
        $sql = "INSERT INTO pages (title, content, display_order, visible) VALUES ('".$title."', '".$content.", '".$order.", 0)";
    }else{
        /** UPDATE SLIDE*/
        $sql = "UPDATE pages SET content = '".$content."', title = '".$title."' WHERE id = '".$id."'";
    }

    if ($result){
        header("Location: admin.php");
    }
}

?>

这段代码所做的是采用我在名为 edit.php 的页面中使用的 HTML 表单,并确定它是新页面还是只是正在更新的页面。我得到的错误是没有任何东西发布到数据库中。如果我删除$sql,$result$order行.. 脚本工作正常,但 display_order 变量不会设置为下一个最高数字。

4

2 回答 2

1

您的查询中有错误:

INSERT INTO pages (title, content, display_order, visible)
VALUES ('".$title."', '".$content.", '".$order.", 0)";
                                     ^-- here

应该:

INSERT INTO pages (title, content, display_order, visible)
VALUES ('".$title."', '".$content."', ".$order.", 0)";
                                   ^-- quote goes here

此外, usingmysqli并不能神奇地保护您免受 SQL 插入。逃避数据输入!

于 2013-04-08T16:16:13.110 回答
0

解决这种情况的常用方法是在 pages 表中使用 AUTO_INCREMENT 字段。依次插入,然后询问 LAST_INSERT_ID

php方式: http: //php.net/manual/en/function.mysql-insert-id.php

原生mysql方式:http ://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id

于 2013-04-08T16:26:42.740 回答