将信息从新创建的记录发送到不同的MySQL表

时间:2015-04-25 14:03:28

标签: php mysql

我正在制作一个表单,将故事提交到名为“work”的MySQL表中。我想稍后获取新创建的记录的id并将信息放入另一个表中。

但是当我提交故事时,它说:

  

$ workid未定义。

我看不出问题,因为我相信我已定义了它?

<?php
    if (!empty($_POST) && !empty($_POST['title']) && !empty($_POST['story']) && !empty($_POST['genre']) && !empty($_POST['rating'])) { 
        $title = strip_tags($_POST['title']);
        $story = strip_tags($_POST['story']);
        $title = mysqli_real_escape_string($db, $title);
        $story = mysqli_real_escape_string($db, $story);
        $genre = $_POST['genre'];
        $rating = $_POST['rating'];

        $query = "SELECT COUNT(*) AS count FROM works WHERE Title = '".$title."'";
        $result = $db->query($query);
        $data = $result->fetch_assoc();

        if ($data['count'] > 0) {
            echo "<p>Story already exists!</p>";
        } else {
            $query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";

            $query = "SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
            if ($result = $db->query($query)) {
                while ($row = $result->fetch_assoc()) 
                    $workid = $row["id"]; //workid is written here but still considered undefined
            }

            $query = "INSERT INTO `author_work` (`author_id`) VALUES ('".$authorid."')";
            $result = $db->query($query);

            $query = "INSERT INTO `author_work` (`work_id`) VALUES ('".$workid."')";
            $result = $db->query($query);

            $query = "INSERT INTO `login_work` (`work_id`) VALUES ('".$workid."')";
            $result = $db->query($query);

            $query = "INSERT INTO `login_work` (`login_id`) VALUES ('".$userid."')";
            $result = $db->query($query);                           

            if ($result) {
                echo "<p>Story submitted!</p>";
            } else {
                echo "SQL Error: " . $db->error;
            }
        }
    }
?>

2 个答案:

答案 0 :(得分:0)

您的$ workid可能未初始化,具体取决于您的条件和SQL查询的结果:因此,请尝试使用continueelse

答案 1 :(得分:0)

您的$db->query()查询字符串上从未执行过INSERT INTO...,因此它从未插入,并被SELECT id ...查询覆盖。

$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";

$db->query($query); // Missing this $db->query()

$query="SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row= $result->fetch_assoc()) 
$workid = $row["id"];}