将空白数据插入数据库的字段

时间:2013-07-05 02:51:39

标签: php mysql insert

我检查了我的代码与我网站上其他地方的代码相比,我看不出任何不一致的地方,但由于某种原因,记录正在使用空白数据进入我的数据库,这是我的代码。

<?php

include '../includes/connect.php';
include '../header.php';

echo '<h2>Create a Sub category</h2>';
if($_SESSION['signed_in'] == false | $_SESSION['user_level'] != 1 )
{
//the user is not an admin
echo 'Sorry, you do not have sufficient rights to access this page.';
}
else
{
//the user has admin rights
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
    //the form hasn't been posted yet, display it
    echo '<form method="post" action="">
        Category name: ';
        $sql = "SELECT cat_id, cat_name, cat_description FROM categories";
        $result = mysql_query($sql);
    echo '<select name="topic_cat">';
                while($row = mysql_fetch_assoc($result))
                {
                    echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
                }
            echo '</select><br />';


    echo 'Sub category name: <input type="text" name="sub_cat_name" /><br />
        Sub category description:<br /> <textarea name="sub_desc" /></textarea><br /><br />
        <input type="submit" value="Add Sub Category" />
     </form>';
}
else
{

    //the form has been posted, so save it
    $sql = "INSERT INTO subcategories(c_id, sub_cat_name, sub_desc)
       VALUES('" . $_POST['categories.cat_id'] . "', '" . $_POST['sub_cat_name'] . "', '" . $_POST['sub_desc'] . "')";
    $result = mysql_query($sql) or die (mysql_error());
            echo 'The sub category <b>' . $row['sub_cat_name'] . '</b> has been added under the main category <b>' . $row['cat_name'] . '</b>';
    if(!$result)
    {
        //something went wrong, display the error
        echo 'Error' . mysql_error();

    }
}
}
; ?>

我的类别表的结构如此......

  • cat_id
  • cat_desc

我的子类别表的结构如此......

  • id(AI)
  • c_id
  • sub_cat_name
  • sub_desc

如果我没有提供足够的信息,请告诉我。

3 个答案:

答案 0 :(得分:1)

您似乎没有将$ POST变量读入您在查询中使用的变量中。你可能想要这样的东西:

$sub_cat_name = mysql_real_escape_string($_POST['sub_cat_name']);
// repeat for other variables.

答案 1 :(得分:0)

在我看来,$cat_id $sub_cat_name$sub_desc未在任何地方定义。

另外,你在这里错过了一个管道:

if($_SESSION['signed_in'] == false || $_SESSION['user_level'] != 1 )
// --------------------------------^

最后,我应该注意mysql_*函数已被弃用。你应该真的使用mysqli或PDO

答案 2 :(得分:0)

if($_SESSION['signed_in'] == false || $_SESSION['user_level'] != 1 )
------------------------------------^ (OR)

我也看不到您设置变量的位置。 ('" . $cat_id . "' and etc...)

您应该将它们存储到variable中,如此:

$cat_id = mysql_real_escape_string($_POST['name_of_the_input']); //and etc..

或者在insert query执行此操作 :(取决于您是否需要像上面那样逃避它的值)

'".$_POST['name_of_input']."',