Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么我的php从mysql返回一个值(一行)?_Php_Mysql - Fatal编程技术网

为什么我的php从mysql返回一个值(一行)?

为什么我的php从mysql返回一个值(一行)?,php,mysql,Php,Mysql,我有一个从mysql返回值的php文件,她是我的php文件: <?php $host = "localhost"; // Host name $username = "UserName"; // Mysql username $password = "PassWord"; // Mysql password $db_name = "DbName"; // Database name $tbl_name = "Notes"; // Table name // Connect t

我有一个从mysql返回值的php文件,她是我的php文件:

<?php

$host = "localhost"; // Host name 
$username = "UserName"; // Mysql username 
$password = "PassWord"; // Mysql password 
$db_name = "DbName"; // Database name 
$tbl_name = "Notes"; // Table name 

// Connect to server and select databse.
mysql_connect($host, $username, $password)or die("cannot connect"); 
mysql_select_db($db_name)or die("cannot select DB");




// To protect MySQL injection (more detail about MySQL injection)
$mytitle = $_REQUEST['title'];
$mytitle = stripslashes($mytitle);
$mytitle = mysql_real_escape_string($mytitle);

$sql="SELECT * FROM $tbl_name WHERE title = '$mytitle'";


$result = mysql_query($sql);

// Mysql_num_row is counting table row
$count = mysql_num_rows($result);

$count = 0;
$items;

while($row = mysql_fetch_array($result)) {
    $item['userName'] = $row['userName'];
    $item['title'] = $row['title'];
    $item['comments'] = $row['comments'];
    $item['commentsTime'] = $row['commentsTime'];
    $item['commentsDate'] = $row['commentsDate'];
    $items[$count] = $item;
}

echo json_encode($items);

?>

当我从浏览器运行代码时,该文件只返回一个值,我通过URL()访问该文件

有人能告诉我我的代码出了什么问题吗?
谢谢

您错过了
$count++内部while循环

您永远不会增加
$count
;它的值始终为0。因此,第二项将覆盖第一项,第三项将覆盖第二项,依此类推。最终,您将只返回从数据库获取的最后一行

在循环结束时增加
$count
,以解决问题:

    $items[$count] = $item;
    $count++;
}
或者,您可以在不记录计数的情况下执行此操作。完全删除
$count
变量,并将数组分配更改为:

$items[] = $item;

虽然我看到这个问题已经得到了回答,但我想我应该注意到,您正在使代码变得更加复杂。您的整个while循环可以总结如下,并将给出您想要的结果

while($row = mysql_fetch_array($result)) {
    $items[] = $row;
}