好的我正在制作票务系统,这里是sql查询和while循环的代码:
if (mysqli_num_rows($query) === 0) {
header('Location: /tickets');
}
$username = array();
$message = array();
$timestamp = array();
$status = array();
$subject = array();
while (var_dump($row = mysqli_fetch_assoc($query))) {
$username[] = $row['username'];
$message[] = $row['message'];
$timestamp[] = $row['timestamp'];
$status[] = $row['status'];
$subject[] = $row['subject'];
}
if (isset($_POST['submit'])) {
$new_message = $_POST['message'];
$new_message = mysqli_real_escape_string($con, $new_message);
mysqli_query($con, "INSERT INTO tickets VALUES(
NULL,
'".$id."',
'".$username."',
'".$subject."',
'1',
'".date('H M H:i')."',
'".$new_message."'
)");
}
?>
<h2>Unique Ticket ID: <?php echo $id; ?></h2>
<?php
foreach ($message as $msg) {
echo '
<div class="ticket-message clearfix">
<h4>'.$username.' ['.$timestamp.']</h4>
<p>'.$msg.'</p>
</div>';
}
如果我尝试对这些结果进行数组打印或回显,则会打印“数组”而不打印任何其他内容。我有一个var_dump,这就是结果:
array(7) { ["id"]=> string(2) "28"
["ticket_id"]=> string(10) "TICK_71323"
["username"]=> string(6) "Jordan"
["subject"]=> string(14) "ticket subject"
["status"]=> string(1) "1"
["timestamp"]=> string(13) "Thu May 12:34"
["message"]=> string(16) "ticket message "
}
显然,数据是否正确提取?为什么我不能正确得到这些值?
答案 0 :(得分:0)
$ username,$ message等是数组,所以你需要使用索引访问它们,试试这个:
if (mysqli_num_rows($query) === 0) {
header('Location: /tickets');
}
$username = array();
$message = array();
$timestamp = array();
$status = array();
$subject = array();
while ($row = mysqli_fetch_assoc($query)) {
$username[] = $row['username'];
$message[] = $row['message'];
$timestamp[] = $row['timestamp'];
$status[] = $row['status'];
$subject[] = $row['subject'];
}
if (isset($_POST['submit'])) {
$new_message = $_POST['message'];
$new_message = mysqli_real_escape_string($con, $new_message);
for($i=0;$i<count($username);$i++)
{
mysqli_query($con, "INSERT INTO tickets VALUES(
NULL,
'".$id."',
'".$username[$i]."',
'".$subject[$i]."',
'1',
'".date('H M H:i')."',
'".$new_message."'
)");
}
}
这将为每个用户名插入一张票......也就是$ id变量不知道它来自哪里......也许必须在bucle中检索。另一个方法:
if (mysqli_num_rows($query) === 0) {
header('Location: /tickets');
}
$username = "";
$message = "";
$timestamp = "";
$status = "";
$subject = "";
if($row = mysqli_fetch_assoc($query)) {
$username = $row['username'];
$message = $row['message'];
$timestamp = $row['timestamp'];
$status = $row['status'];
$subject = $row['subject'];
}
if (isset($_POST['submit'])) {
$new_message = $_POST['message'];
$new_message = mysqli_real_escape_string($con, $new_message);
mysqli_query($con, "INSERT INTO tickets VALUES(
NULL,
'".$id."',
'".$username."',
'".$subject."',
'1',
'".date('H M H:i')."',
'".$new_message."'
)");
}
如果$ query记录集中只有一行。