未定义的变量:第101行的/dashboard/index.php中的con

时间:2017-07-24 21:20:33

标签: php mysql

我试图在while循环中显示用户列表的状态(Active或Suspended)。

0 =有效 1 =暂停

<?php
/**
 * Template Name: Sign up Page
 *
 * @package WordPress
 * @subpackage Twenty_Fourteen
 * @since Twenty Fourteen 1.0
 */

echo 'this is the signup page';


$post   = get_post(2);
$output =  apply_filters( 'the_content', $post->post_content );

echo $output;

上面给了我:

注意:未定义的变量:第101行/dashboard/index.php中的con

警告:mysqli_query()要求参数1为mysqli,在第101行的/dashboard/index.php中给出null

警告:mysqli_fetch_assoc()期望参数1为mysqli_result,在第102行的/dashboard/index.php中给出null

3 个答案:

答案 0 :(得分:2)

请务必回答评论中的问题。很多聪明的人试图帮助你。

我不使用mysqli。如果我这样做,我可能会尝试这样的事情......

<?php
if ($stmt = mysqli_prepare($con, "SELECT status FROM e_customer WHERE account = ?")) {

    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "s", $username);

    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $status);

    mysqli_stmt_fetch($stmt);

    //is 0 really active and 1 suspended because than seems pretty backwards?
    if (!$status) { //per your comment then `!$status`. cringing...
        echo 'Active';
    } else {
        echo 'Suspended';
    }

    mysqli_stmt_close($stmt);
}

当期望一行时,不需要循环。不确定用户名来自何处 - 尝试并使用参数化(参见PDO)语句。

答案 1 :(得分:1)

首先,我会直接在数据库中尝试您的查询以确保它有效,然后尝试以下操作:

<?php 
    $result = mysqli_query($con,"SELECT status FROM `e_customer` WHERE account='$username'");
    $row = mysqli_fetch_assoc($result);
    echo ($row['status'] == "1") ? "Suspended" : "Active";
?>

如果还没有,那么尝试执行$ con变量的var_dump以及$ row变量。看看你是否连接和/或得到了结果。

...还有$ username变量。

答案 2 :(得分:0)

现在我们有了真正的PHP错误,我们可以处理它。

确保在查询之前初始化$ con。您可能忘记了包含或其他内容。出于调试目的,将其添加到查询上方。如果这可以解决您的问题,请告诉我。

  

注意:mysqli_connect()需要4个参数

     

主机:127.0.0.1或localhost或远程服务器的IP / DNS

     

用户:连接到数据库的用户名

     

密码:连接数据库的密码

     

数据库名称:数据库的名称

$con = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");

所以完整的代码看起来像这样:

<?php 
error_reporting( E_ALL );
ini_set('display_errors', 1);
$con = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");

$result = mysqli_query($con,"SELECT status FROM `e_customer`") or die(mysqli_error($con));
    while($row = mysqli_fetch_array($result)) {
    if ($row['status'] == "1") {
     echo $row['account']." is Suspended</br>";
    } else {
      echo $row['account']." is Active</br>";
    }
} 
?>