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

标签 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_desc

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

最佳答案

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

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

关于php - 将空白数据插入数据库的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17480414/

相关文章:

php - 如何在不为每个函数运行新的浏览器窗口的情况下运行 PHPUnit Selenium 测试?

mysql - 与同一实体的多个一对多关系

javascript - 如何根据数据库值在组中设置默认选中的单选按钮?

PHP 数组作为单独的行插入到 MySQL 表中。

php - MySQL问题: How to insert unique non-integer employee ids?

php - 下拉框内的列表项

c# - ASP MVC 4 MySQL,处理事务错误时遇到问题

c# - 在C#中高效地将数据插入多个表中的MySQL

java - 如何捕获 SQLiteConstraintException 唯一约束失败的列名

php - CodeIgniter 2.1 国际化 i18n - 如果用户数据存在则覆盖默认语言