PHP脚本选择MySQL数据字段并返回JSON

时间:2014-02-26 19:06:56

标签: php mysql json

所以我试图将JSON下载到iOS应用程序中,我对PHP并不是很了解。

目前我使用通用的php脚本作为连接MySQL数据库并返回JSON结果的委托。

<?php
$host = "localhost"; //database host server
$db = "***"; //database name
$user = "root"; //database user
$pass = "root"; //password

$connection = mysql_connect($host, $user, $pass);

//Check to see if we can connect to the server
if(!$connection)
{
    die("Database server connection failed.");  
}
else
{
    //Attempt to select the database
    $dbconnect = mysql_select_db("***", $connection);

    //Check to see if we could select the database
    if(!$dbconnect)
    {
        die("Unable to connect to the specified database!");
    }
    else
    {
        $query = "SELECT * FROM table";
        $resultset = mysql_query($query, $connection);

        $records = array();

        //Loop through all our records and add them to our array
        while($r = mysql_fetch_assoc($resultset))
        {
            $records[] = $r;        
        }

        //Output the data as JSON

        echo json_encode($records);

    }


}


?>

这个问题是我不想用JSON编码整个表我只想从特定表中返回一些选择数据字段,所以我不下载不必要的数据。

我知道您在SELECT查询中执行此操作但我的语法错误。

我一直在尝试:

$query = "SELECT *[datafield],[otherdatafield],... FROM table";

但这似乎不起作用。

此外,在该表中有两个单独的数据字段用于构建图像的URL,我不知道如何在这里组合这两个,以便它们作为一个字段在JSON中返回。

例如:我有一个基本字符串

"http://wwww.mysite.com/" 

我希望将两个数据字段添加到该字符串中,这样当它返回JSON对象时,它们已经连接了这些字段,以便应用程序可以只使用该URL:

"http://wwww.mysite.com/[data field1]/[datafield2]" 

2 个答案:

答案 0 :(得分:2)

您应该尝试的查询看起来像

  

$ query =“SELECT col1,col2 FROM table”; //如果提及列名,则不需要星号

现在,如果您需要在查询中将两个列组合在一起,请尝试类似

的内容
  

$ query =“SELECT CONCAT('mysite.com /',col1,'/',col2)FROM table”;

“/”是两列之间的分隔符。

答案 1 :(得分:1)

获取单个cols的查询是

select col1,col2,col3 from table_name

无需像你一样提供*

$query = "SELECT *[datafield],[otherdatafield],... FROM table";
                 ^........here * is causing the problem.