PHP:未定义的变量,原因不明

时间:2014-06-04 18:38:23

标签: php mysql variables undefined

我有这个代码从MySql数据库中检索数据:

<?php
$con= mysqli_connect("localhost","root","","darrenvellaedp2");

$query = mysqli_query($con,"SELECT postTitle, pContent FROM tbl_posts WHERE userID = '2'  ");

while($rows = mysqli_fetch_array($query))
{

    $title = $rows['postTitle'];

    $content = $rows['pContent'];

}

&GT;

我收到了这些错误:

注意:未定义的变量:第48行的C:\ xampp \ htdocs \ WSSA1S1 \ index.php中的标题

注意:未定义的变量:第50行的C:\ xampp \ htdocs \ WSSA1S1 \ index.php中的内容

在您告诉我此问题已在本论坛中得到解答之前,您可以使用isset()来解决问题。我知道,我试过但是我没有正确实现它,或者它只是不能使用我的代码。

我看过这篇文章:

PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"

它没有为我工作..我在答案中告诉我,但我一直在收到错误。

我在这里使用变量:

<article class="contentbox1">
            <div class="articleHEADER">
                    <!--<h2>Welcome!</h2>-->

                    <h2><?php echo "$title"?></h2>
            </div>
                <p><?php echo "$content"?></p>
                <footer>
                    <p class="post-info">This post is written by admin</p>
                </footer>

请有人帮忙!

2 个答案:

答案 0 :(得分:3)

您能否验证$title =$content =的循环是否正在执行?

您的查询很可能失败,或者您的行返回零行

答案 1 :(得分:0)

我没有使用过MySQLi,但你的语法对我来说很奇怪,也许可以尝试一下,从PHP手册(这里:http://www.php.net/manual/en/mysqli-result.fetch-array.php):

<?php
    // Establish New Connection
    $mysqli = new mysqli("localhost","root","","darrenvellaedp2");

    // Save the Query for debugging and modification later
    $query = "SELECT postTitle, pContent FROM tbl_posts WHERE userID = '2'  ";

    // Get the result by executing the query
    $result = $mysqli->query($query);

    // Format the result and assign it to a local var
    $row = $result->fetch_array(MYSQLI_NUM);

    // Assign local values
    $title = $rows['postTitle'];
    // Assign local values
    $content = $rows['pContent'];

在这种情况下你的循环似乎是多余的,因为返回多行只会覆盖你的值并使用最后从数据库中出来的那些。