PHP MySQLi Query使用有效语法返回null

时间:2014-05-28 22:24:29

标签: php syntax mysqli null

好的,

我一直在尝试为我的wxPanel制作票证系统,以便为应用程序提供基本支持。虽然我可以使用提供的代码轻松地创建数据库记录:

PHP:

if (isset($_POST['submit'])) {
    $subject = $_POST['subject'];
    $message = $_POST['message'];

    $date = date('D M H:i');

    $subject = mysqli_real_escape_string($subject);
    $message = mysqli_real_escape_string($message);
    $ticket_id = 'TICK_'.rand(00000,99999);

    if (strlen($subject) === 0) {
        echo "Subject Invalid.";
    } elseif (strlen($message) === 0) {
        echo "Message Invalid.";
    } else {
        mysqli_query("INSERT INTO tickets VALUES(
        NULL,
        '".$ticket_id."',
        '".$_SESSION['user']."',
        '".$subject."',
        '1',
        '".$date."',
        '".$message."'
        )");
    }
    header('Location: /view-ticket?identifier='.$ticket_id);
}

工作正常...... 然后有这个,这是获取票据记录并逐个显示标题:

PHP:

$query = mysqli_query("SELECT `subject`,`ticket_id` FROM tickets WHERE `username` = '".$_SESSION['user']."'");

while ($row = mysqli_fetch_assoc($query)) {
    $tickets = $row['subject'];
    $id = $row['ticket_id'];
}

foreach ($tickets as $ticket) {
    echo '
    <a href="view-ticket?identifier='.$id.'"><h2>'.$ticket.'</h2></a>
    ';
}

这总是返回NULL。而且这一切都不起作用:

if (isset($_GET['identifier']) === false || empty($_GET['identifier']) === true) {
    header('Location: /tickets');
    exit();
}

$id = mysqli_real_escape_string($_GET['identifier']);

$query = mysqli_query("SELECT `ticket_id`,`message`,`timestamp`,`status` FROM tickets WHERE `ticket_id` = '".$id."'");

while($row = mysqli_fetch_assoc($query)) {
    $ticket_id = $row['ticket_id'];
    $message = $row['message'];
    $timestamp = $row['timestamp'];
    $status = $row['status'];
}

foreach($message as $msg) {
    echo '
    <div class="ticket-message">
        <h2>'.$message.'</h2>
    </div>';
}

提前谢谢!

P.S。我的一些代码可能很乱。建议总是受到赞赏:)

1 个答案:

答案 0 :(得分:3)

使SELECT查询工作后,您还必须查看处理结果的代码。

如果ticket_id标识了唯一的行

$query = mysqli_query($con, "SELECT ticket_id,message,timestamp,status 
                             FROM tickets WHERE ticket_id = '$id'");


$row = mysqli_fetch_assoc($query);
$ticket_id = $row['ticket_id'];
$message   = $row['message'];
$timestamp = $row['timestamp'];
$status    = $row['status'];

echo '<div class="ticket-message"><h2>'.$message.'</h2></div>';

如果ticket_id无法识别唯一的行

$query = mysqli_query($con, "SELECT ticket_id,message,timestamp,status 
                             FROM tickets WHERE ticket_id = '$id'");

// initialise the arrays that hold multiple row results
$ticket_id[] = array();
$message[]   = array();
$timestamp[] = array();
$status[]    = array();

while($row = mysqli_fetch_assoc($query)) {
   $ticket_id[] = $row['ticket_id'];
   $message[]   = $row['message'];
   $timestamp[] = $row['timestamp'];
   $status[]    = $row['status'];
}

foreach($message as $msg) {
   echo '<div class="ticket-message"><h2>'.$msg.'</h2></div>';
}