簡體   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');

我正在嘗試關於代碼來從數據庫中獲取所有值,但是只有一條記錄會來。請幫助我

試試這個:

$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');

請參閱以下示例:

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>";
   }

首先停止使用mysql_* ,因為現在已棄用它的庫。 使用mysqli_*PDO

其次,您需要按照以下方式對查詢返回的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