MySQL查询从PHP代码返回null,但在终端中工作正常

时间:2013-09-25 03:26:52

标签: php mysql sql json joomla

当我在PHP中运行此代码时,结果为null,但是当我在mysql终端或phpmyadmin中运行它时,我得到了我想要的内容。

PHP

if ($_GET["action"] == "list") {
    //Get records from database
    $mainQuery = mysql_query("
    SET SQL_BIG_SELECTS=1;
    SELECT
      ci.id AS item_id,
      ar.title, ar.introtext, 
      flo.value AS logo, fph.value AS phone, fad.value AS address, fur.value AS url, fse.value AS services, fma.value AS map,
      ar.id AS joomla_id, ci.hidden_id, ci.type
    FROM kd9fb_content ar
      RIGHT JOIN calc_settings cs ON ar.catid = cs.joomla_cat  
      LEFT JOIN kd9fb_fieldsattach_values flo ON flo.articleid = ar.id AND flo.fieldsid = 1
      LEFT JOIN kd9fb_fieldsattach_values fph ON fph.articleid = ar.id AND fph.fieldsid = 2
      LEFT JOIN kd9fb_fieldsattach_values fad ON fad.articleid = ar.id AND fad.fieldsid = 3
      LEFT JOIN kd9fb_fieldsattach_values fur ON fur.articleid = ar.id AND fur.fieldsid = 4
      LEFT JOIN kd9fb_fieldsattach_values fse ON fse.articleid = ar.id AND fse.fieldsid = 5
      LEFT JOIN kd9fb_fieldsattach_values fma ON fma.articleid = ar.id AND fma.fieldsid = 6
      LEFT JOIN calc_item ci ON ci.joomla_id = ar.id
      ORDER BY ci.id DESC;
    ", $con);

    while ($row = mysql_fetch_array($mainQuery)) {      
        $rows[] = $row;
    }
    //Return result to jTable
    $jTableResult = array();
    $jTableResult['Result'] = "OK";
    $jTableResult['Records'] = $rows;
    print json_encode($jTableResult);
}

返回NULL:

$row = mysql_fetch_array($mainQuery)

MySQL基础没问题,代码连接到base:

$con = mysql_connect($host, $user, $password) or die("DB login failed!");
mysql_select_db($db, $con) or die("select failed");
mysql_query("SET NAMES utf8");

类似的代码,但其他查询工作正常,我测试了它,显然是请求中的情况。顺便说一下,我认为它是完全非最佳的方式,但我不擅长SQL和PHP。

那么问题出在哪里以及我哪里出错了?

1 个答案:

答案 0 :(得分:4)

您的查询实际上有两个查询。

"SET SQL_BIG_SELECTS=1;
SELECT
  ci.id AS item_id,
  ar.title, ar.introtext, ....."

删除查询的第一行,它应该没问题。这是因为mysql_query()方法仅支持一个查询。但我认为终端IIRC已取消了这一限制。

如果您需要第一个语句,只需执行两个查询方法:

mysql_query("SET SQL_BIG_SELECTS=1");
$query = "..."; // Rest of your query here