PHP MySQL选择脚本

PHP MySQL选择脚本,php,mysql,Php,Mysql,我正在开发一个需要从MySQL数据库中选择数据的应用程序。我目前正在通过浏览器测试PHP脚本,以确保它返回正确的数据。问题是当前它返回异常“数据库错误!”。我已经包括了我的PHP脚本 通过城市获取机构。php <?php /* * Following code will get all agencies matching the query * Returns essential details * An agency is identified by agency id */ req

我正在开发一个需要从MySQL数据库中选择数据的应用程序。我目前正在通过浏览器测试PHP脚本,以确保它返回正确的数据。问题是当前它返回异常“数据库错误!”。我已经包括了我的PHP脚本

通过城市获取机构。php

<?php

/*
* Following code will get all agencies matching the query
* Returns essential details
* An agency is identified by agency id
*/

require("DB_Link.php");

$city =  ($_GET['City']);

//query database for matching agency
$query = "SELECT * FROM agency WHERE City = $city";

//Execute query
try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute();
}
catch (PDOException $ex)    {
    $response["success"] = 0;
    $response["message"] = "Database Error!";
    die(json_encode($response));
}

//Retrieve all found rows and add to array
$rows = $stmt->FETCHALL();


if($rows)   {
    $response["success"] = 1;
    $response["message"] = "Results Available!";
    $response["agencys"] = array();

    foreach ($rows as $row) {
        $agency         = array();
        $agency["AgencyID"] = $row["AgencyID"];
        $agency["AgencyName"]   = $row["AgencyName"];
        $agency["Address1"] = $row["Address1"];
        $agency["City"]     = $row["City"];
        $agency["State"]    = $row["State"];
        $agency["Zip"]      = $row["Zip"];
        $agency["Lat"]      = $row["Lat"];
        $agency["Lon"]      = $row["Lon"];

        //update response JSON data
        array_push($response["agencys"], $agency);
    }

    //Echo JSON response
    echo json_encode($response);

} else  {
    $response["success"] = 0;
    $response["message"] = "No Agency found!";
    die(json_encode($response));
}

?>

这里是DB_Link.php

<?php 

// These variables define the connection information the MySQL database 
// set connection...


$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'); 


try 
{ 

        $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); 
} 
catch(PDOException $ex) 
{ 

        die("Failed to connect to the database: " . $ex->getMessage()); 
} 


$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 


$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); 


if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) 
{ 
        function undo_magic_quotes_gpc(&$array) 
        { 
            foreach($array as &$value) 
            { 
                if(is_array($value)) 
                { 
                    undo_magic_quotes_gpc($value); 
                } 
                else 
                { 
                    $value = stripslashes($value); 
                } 
            } 
        } 

        undo_magic_quotes_gpc($_POST); 
        undo_magic_quotes_gpc($_GET); 
        undo_magic_quotes_gpc($_COOKIE); 
} 


header('Content-Type: text/html; charset=utf-8'); 


session_start(); 


?>

查询中需要有变量$city。这样做:

$query = "SELECT * FROM Agency WHERE City = " . $city;

您应该将您的查询重写为该语句,因为它是一个预先准备好的语句,您的查询将更加安全(并且有效)

此外,您还应该检查是否设置了$\u GET

像这样:

try { 
        $stmt = $dbh->prepare("SELECT * FROM agency WHERE city = :city");
        $stmt->execute(array('city' => $city));
        $rows = $stmt->FETCHALL();


if($rows)   {
    $response["success"] = 1;
    $response["message"] = "Results Available!";
    $response["agencys"] = array();

    foreach ($rows as $row) {
        $agency         = array();
        $agency["AgencyID"] = $row["AgencyID"];
        $agency["AgencyName"]   = $row["AgencyName"];
        $agency["Address1"] = $row["Address1"];
        $agency["City"]     = $row["City"];
        $agency["State"]    = $row["State"];
        $agency["Zip"]      = $row["Zip"];
        $agency["Lat"]      = $row["Lat"];
        $agency["Lon"]      = $row["Lon"];

        //update response JSON data
        array_push($response["agencys"], $agency);
    }

    //Echo JSON response
    echo json_encode($response);

} }

 catch (PDOException $ex) {

           //or include your error statement - but echo $ex->getMessage()
            die('Error!: ' . json_encode($ex->getMessage()));

     }

给出DB_Link.php的代码。您是否尝试查看PDO异常的内容?如果您可以直接在服务器上运行SQL语句(比如使用mysql命令行程序),这将使调试和查看错误消息变得更加容易,那么可以为您提供有关问题所在的信息;您应该在错误消息中回显
$ex->getMessage()
。即使您使用的是预先准备好的语句,由于您构造查询的方式,您的代码也容易受到SQL注入的影响。$\u GET['City']是否返回了正确的值?如果是,是字符串吗?sql中可能需要单引号。另外,将$ex->getMessage()添加到“Database Error!”字符串中可能会有所帮助。使用双引号字符串时,双引号字符串中的变量名的值将被替换。调用正确。我在想当使用单引号时会发生什么。做了建议的更改,现在我在第20change$dbh->prepare to$db->prepare的第20行得到了“调用非对象上的成员函数prepare()”,抱歉,我不知道您使用的是什么变量,但这些只是测试信条。我已经搬走了。还做了下一个更改,现在我在第30行看到“对非对象调用成员函数FETCHALL()。非常感谢你的帮助。在过去的两天里,我一直没有注意到这一点。啊,您必须将$statement更改为$stmt,然后它将适合您的代码的其余部分。我有第二个脚本,它有两个值,而不仅仅是一个值。那么这会使这行“$stmt->execute(array('city'=>$city));”看起来像这样“$stmt->execute(array('userid'=>$userid)&('agencyid'=>$agencyid));
try { 
        $stmt = $dbh->prepare("SELECT * FROM agency WHERE city = :city");
        $stmt->execute(array('city' => $city));
        $rows = $stmt->FETCHALL();


if($rows)   {
    $response["success"] = 1;
    $response["message"] = "Results Available!";
    $response["agencys"] = array();

    foreach ($rows as $row) {
        $agency         = array();
        $agency["AgencyID"] = $row["AgencyID"];
        $agency["AgencyName"]   = $row["AgencyName"];
        $agency["Address1"] = $row["Address1"];
        $agency["City"]     = $row["City"];
        $agency["State"]    = $row["State"];
        $agency["Zip"]      = $row["Zip"];
        $agency["Lat"]      = $row["Lat"];
        $agency["Lon"]      = $row["Lon"];

        //update response JSON data
        array_push($response["agencys"], $agency);
    }

    //Echo JSON response
    echo json_encode($response);

} }

 catch (PDOException $ex) {

           //or include your error statement - but echo $ex->getMessage()
            die('Error!: ' . json_encode($ex->getMessage()));

     }