简体   繁体   English

如何从PHP Web服务中的MySQL表获取所有记录

[英]how to get all the records from MySQL table in php web services

$sql=mysql_query("SELECT friendName,createdDate FROM friends where userId='$userId'");
$result=mysql_fetch_assoc($sql);
if(!empty($result))
{
$json=$result;
}
else
{
$json = array( "msg" => "No infomations Found");
}
header('Content-type: application/json');

I am trying the about code for getting all the values from database but only one record will come.please help me 我正在尝试关于代码来从数据库中获取所有值,但是只有一条记录会来。请帮助我

try this one: 试试这个:

$sql=mysql_query("SELECT friendName,createdDate FROM friends where userId='$userId'");
$json= array();
while($json = mysql_fetch_assoc($sql)){}
if(empty($json))
{
    $json = array( "msg" => "No infomations Found");
}
header('Content-type: application/json');

See sample below : 请参阅以下示例:

while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
      echo "EMP ID :{$row['emp_id']}  <br> ".
         "EMP NAME : {$row['emp_name']} <br> ".
         "EMP SALARY : {$row['emp_salary']} <br> ".
         "--------------------------------<br>";
   }

First stop using mysql_* ,because its deprecated library now. 首先停止使用mysql_* ,因为现在已弃用它的库。 Use mysqli_* or PDO 使用mysqli_*PDO

Second you need to do iteration on your query returned result-set object in below manner:- 其次,您需要按照以下方式对查询返回的result-set object进行迭代:-

$sql=mysql_query("SELECT friendName,createdDate FROM friends where userId='$userId'");
$json = array(); // create empty array
$i = 0; // start a counter
while($result=mysql_fetch_assoc($sql)){ // start iteration on result-set object
    // fetch values one-by-one and assing to them in the array
    $json[$i]['friendName'] = $result['friendName'];
    $json[$i]['createdDate'] = $result['createdDate'];
    $i++; // increase the counter so that values will assign to the new indexes every-time (prevent from over-writing)
}
if(count($json)>0){ // check array have some values or not
 // now you have all records in $json array and here you can do your next code whatever you want based on this resultant array
}else{
$json = array( "msg" => "No infomations Found");
}
header('Content-type: application/json'); //i don't know what purpose this line will serve, so check your self.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM