PHP中未定义的连接变量

时间:2012-10-31 00:00:13

标签: php

我有一个PHP脚本如下:

function addPost(BlogPost $item, $tags) {
        $connection = mysql_connect('localhost', '***', '***') or die(mysql_error());
        mysql_select_db('jschaible1') or die(mysql_error());

        $queryString = "insert into BlogPost values ( null, '" . $item->Title . "', '" . $item->Body . "', " . "now());";

        $result = mysql_query($queryString) or die(mysql_error());

        $dbResult = mysql_query('select * from blogpost where Title = "' . $item->Title . '";') or die(mysql_error());
        while ($row = mysql_fetch_array($dbResult)) {
            $tableID = $row['BlogPostID'];
        }

        foreach($tags as $t) {
            $queryString = "insert ignore into Tag values('" . strtolower($t) . "');";
            mysql_query($queryString) or die(mysql_error());

            $queryString = "insert into blogposttag values (" . $tableID . ", '" . strtolower($t) . "');";
            mysql_query($queryString) or die(mysql_error());
        }

        echo $connection;
        mysql_close($connection) or die(mysql_error());
    }

正在调用该函数:

<?php
    session_start();

    $errors = '';

    if (!isset($_SESSION['dadfg6d5f6df54']))
        header('Location:admin.php');
    else {
        include('Classes.php');
        include('mySql.php');
        include('utils.php');

        if(isset($_POST['Submit'])) {
            if ($_POST['Title'] == '') {
                $errors = 'Post must have a title!';
            }
            else if ($_POST['PostBody'] == '') {
                $errors = 'Post must be something!';
            }
            else if (strlen($_POST['PostBody']) < 10) {
                $errors = "Write something substantial, c'mon!";
            }
            else if ($_POST['Tags'] == '') {
                $errors = "At least one tag must be entered";
            }
            else {
                $newPost = new BlogPost(NULL, sanitize($_POST['Title']), sanitize($_POST['PostBody']), NULL);

                $newPost->Title = addEmoticons($newPost->Title);
                $newPost->Body = addEmoticons($newPost->Body);

                $tags = str_replace(',', '', $_POST['Tags']);
                $tags = str_replace(';', '', $tags);
                $tags = explode(' ', $tags);

                error_reporting(E_ALL); ini_set('display_errors', 1);
                addPost($newPost, $tags) or die();

                $errors = 'Post added successfully';
            }
        }
    }
?>

当它到达mysql_close()时,页面停止执行,我得到一个空白页面。这真让我感到沮丧,我根本不明白为什么会发生这种情况,特别是看看PREVIOUS系列的回声如何输出“资源ID#6”。我没有收到任何错误消息,只是一个空白页面!请帮忙!

1 个答案:

答案 0 :(得分:2)

您的功能没有返回值。因此,它返回NULL evaluates as a "falsy" value。由于您通过or die()调用来关注它,因此错误评估会触发or die()并终止您的脚本。

// Don't do this:
addPost($newPost, $tags) or die();

// Do this:
addPost($newPost, $tags);

在您的功能结束时,您可以return TRUE,但除非您希望根据您的帖子添加成功或失败返回值,否则完全没有必要。你拥有它的方式,die()只会造成不必要的伤害。由于函数中的所有潜在失败点都已经错误地终止了脚本,因此返回TRUE没有什么好处。只需在函数调用后删除die()