2014-09-29 51 views
-1

所以我用php來連接我的android應用程序到mysql數據庫。我在幾個小型數據庫上測試了應用程序和查詢。一切正常。 在較大的數據庫上使用舊的查詢使php查詢永久加載到Web瀏覽器中,因此不顯示預期的JSON。所以我做了一個新的查詢,但它沒有在應用中顯示任何結果,而且它只顯示查詢中的最後一個結果。有沒有什麼辦法可以解決這個問題?Php在mysql上的腳本查詢

舊的PHP查詢小分貝的工作,但永遠在加載網頁瀏覽器具有較大的DB:

<?php 

error_reporting(0); 

$response = array(); 

require_once __DIR__ . '/db_connect.php'; 

$db = new DB_CONNECT(); 

$result = mysql_query("SELECT eid,marca,investimento,marcatotal,dataconstituicao,datainicio FROM empresa") or die(mysql_error()); 

header('content-type: application/json; charset=utf-8'); 
mysql_query('SET character_set_connection=utf8'); 
mysql_query('SET character_set_client=utf8'); 
mysql_query('SET character_set_results=utf8'); 

if (mysql_num_rows($result) > 0) { 
    $response["empresa"] = array(); 

    while ($row = mysql_fetch_array($result)) { 
     $product = array(); 
     $product["eid"] = $row["eid"]; 
     $product["marca"] = $row["marca"]; 
     $product["investimento"] = $row["investimento"]; 
     $product["dataconstituicao"] = $row["dataconstituicao"]; 
     $product["datainicio"] = $row["datainicio"]; 

     array_push($response["empresa"], $product); 
    } 
    $response["success"] = 1; 

    echo json_encode($response); 
} else { 
    $response["success"] = 0; 
    $response["message"] = "No empresa found"; 

    echo json_encode($response); 
} 
?> 

新的PHP查詢我創建的僅顯示上次結果的網頁瀏覽器不在新的更大的數據庫應用程序顯示任何東西:

<?php 

//error_reporting(E_ALL); 
error_reporting(0); 

require_once('db_config.php'); 

$conn = mysql_connect($db_server, $db_user, $db_password) or die(mysql_error()); 

$db= mysql_select_db($db_database, $conn); 

$sql="SELECT eid,marca,investimento,marcatotal,dataconstituicao,datainicio FROM empresa" ; 

header('content-type: application/json; charset=utf-8'); 
mysql_query('SET character_set_connection=utf8'); 
mysql_query('SET character_set_client=utf8'); 
mysql_query('SET character_set_results=utf8'); 

$rs = mysql_query($sql,$conn); 

while ($row=mysql_fetch_assoc($rs)) 

{ 
    $i=0; 
    foreach($row as $key => $value) 
    { 
     if (is_string($key)) 
     { 
     $fields[mysql_field_name($rs,$i++)] = $value; 
     } 
    } 
    $json_result ["empresa"] = $fields; 
} 

$response = json_encode($json_result); 

print_r($response); 

?> 
+1

mysql_query擴展從PHP 5.5.0開始已棄用,並且將來會被刪除。相反,應該使用MySQLi或PDO_MySQL擴展。 [來源](http://php.net/manual/en/function.mysql-query.php) – consuela 2014-09-29 14:46:54

+0

這是查詢不起作用的原因? – Acejakk 2014-09-29 14:47:43

+0

你只得到最後一行的原因是你每次通過循環覆蓋'$ json_result [「empresa」]的值。你可能想要類似'$ json_result [「empresa」] [] = $ fields;' – 2014-09-29 14:49:48

回答

0

帕特里克Q中的aswer是正確的: $ json_result [ 「Empresa與」]必須是$ json_result [ 「Empresa與」] [] = $領域; 此外,他的建議幫助我進一步解決了我的問題,因爲我只是從我的應用程序中刪除了全部成功= 1邏輯,以便它能夠正常工作。謝謝大家的幫助!