PHP代码在没有放入函数时有效

时间:2012-07-21 12:19:16

标签: php

我正在尝试获取数据并将其编码为JSON。我有这个非常令人困惑的麻烦。我在getAnnotions()函数中放入的代码,当我没有把它放在函数中时,会到达while循环(注释为// This循环)。而当我在getAnnotions()函数中封装相同的代码时,未达到while循环。可能是什么问题?

以下是代码:

    <?php

$city=$_GET["city"];
//$limit="1";
//$place=$_GET["place"];

getAnnotions("1");

function getAnnotions($limit)
{

    $con = mysql_connect("localhost","hidden","*******");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }

    mysql_select_db("merrycod_tummy", $con);

    $result = mysql_query("SELECT * FROM deal where city_names LIKE '%".$city."%'");

    $rows = array();

    while($row = mysql_fetch_array($result))
      {

          $rows[] = $row;


          $result2 = mysql_query("SELECT locationLat,locationLong FROM place where city ='".$city."' AND name='".$row['place_name']."' LIMIT ".$limit);



          while($row2 = mysql_fetch_array($result2))
          {
                $rows[] = $row2;

              //This loop

          }


      }

      echo json_encode($rows);


    mysql_close($con);

}
 ?>

2 个答案:

答案 0 :(得分:4)

因为$city是在全局范围内定义的,而在PHP函数中,另一个范围的变量不能直接使用。您可以将其作为参数传递(建议),也可以在函数开头使用global $city

答案 1 :(得分:0)

我建议你首先在$ result中回显sql,然后运行你在phpmyadmin中回显的代码来查看你的sql是否正确