PHP PDO多个查询不会获得任何值

时间:2017-11-08 07:04:20

标签: php pdo

我已经在此代码之前进行了内部联接,但似乎每次我有多个查询它都不起作用。但是当我做单一查询时,它似乎很好并且正常工作。请高手帮帮我。谢谢!

<?php
include('db.php');
include('function.php');
if(isset($_POST["personal_info_id"]))
{
    $id1 = $_POST["personal_info_id"];
    $id2 = $_POST["personal_info_id"];
    $sql = "SELECT * FROM hr_details WHERE personal_info_id = '$id1'";
    $sql .="SELECT * FROM personal_info WHERE personal_info_id = '$id2'";
    $output = array();  
    $statement = $connection->prepare($sql);
    $statement->execute();
    $result = $statement->fetchAll();
    foreach($result as $row)
    {
        $output["firstname"] = $row["firstname"];
        $output["middlename"] = $row["middlename"];
        $output["lastname"] = $row["lastname"];
        $output["address"] = $row["address"];
        $output["birthdate"] = $row["birthdate"];
        $output["gender"] = $row["gender"];
        $output["religion"] = $row["religion"];
        $output["civil_status"] = $row["civil_status"];
        $output["biometrics"] = $row["biometrics"];
        if($row["image"] != '')
        {
        $output['user_image'] = '<img src="upload/'.$row["image"].'" class="img-thumbnail" width="50" height="35" /><input type="hidden" name="hidden_user_image" value="'.$row["image"].'" />';
        }
        else
        {
          $output['user_image'] = '<input type="hidden" name="hidden_user_image" value="" />';
         }

    }

    echo json_encode($output);

}
?>

2 个答案:

答案 0 :(得分:1)

这样做不起作用吗?

SELECT * FROM hr_details hd, personal_info pi WHERE hd.personal_info_id=pi.personal_info_id AND personal_info_id = id

您必须注意不要使用prepare

直接在SQL查询中传递变量

http://php.net/manual/en/pdo.prepare.php

$sql = 'SELECT * FROM hr_details hd, personal_info pi WHERE hd.personal_info_id=pi.personal_info_id AND personal_info_id = :id';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':id' => $_POST["personal_info_id"]));
$red = $sth->fetchAll();

答案 1 :(得分:0)

虽然可以运行multiple queries in one call with PDO但没有一个理由这样做。你的案子都不是例外。它永远不会像你想象的那样工作。而不是像这样在一个调用中填充多个查询,您需要使用JOIN进行单个查询。

您的代码的另一个问题是货物崇拜准备声明。它看起来像一个真实的但没有保护。您应该在准备好的查询中使用参数。

$sql = "SELECT * FROM hr_details hd, personal_info pi WHERE 
        hd.personal_info_id=pi.personal_info_id AND hd.personal_info_id=?";
$statement = $connection->prepare($sql);
$statement->execute([$_POST["personal_info_id"]]);
$result = $statement->fetchAll();