将PHP数组作为SQL WHERE子句的参数传递

时间:2017-04-19 20:23:31

标签: php mysql arrays

调整here的答案,尝试将数组作为MySQL中WHERE子句的参数传递。语法似乎没问题,但我只是从相应的JSON返回null。我认为明白它应该做什么,但还不够,我可以解决它可能出错的地方。该函数的代码是;

public function getTheseModulesById($moduleids) {
    require_once 'include/Config.php';
    $con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
    // Check connection
    if (!$con)
      {
        die("Connection error: " . mysqli_connect_error());
      }
    // selecting database
    mysqli_select_db($con, DB_DATABASE) or die(mysqli_connect_error());

    $in = join(',', array_fill(0, count($moduleids), '?'));
    $select = "SELECT * FROM modules WHERE id IN ($in)";
        $statement = $con->prepare($select);
        $statement->bind_param(str_repeat('i', count($moduleids)), ...$moduleids);
        $statement->execute();
    $result = $statement->get_result();

    $arr = array();
    while($row = mysqli_fetch_assoc($result)) { 
        $arr[] = $row;
    }

    mysqli_close($con);
    return $arr;
}

代码调用它的代码看起来像;

$id = $_POST['id'];

    $player = $db->getPlayerDetails($id);   
    if ($player != false) {
        $pid = $player["id"];
        $moduleids = $db->getModulesByPlayerId($pid);   //this one is okay
        $modules = $db->getTheseModulesById($moduleids); //problem here

        $response["player"]["id"] = $pid;           
        $response["player"]["fname"] = $player["fname"];
        $response["player"]["sname"] = $player["sname"];
        $response["modules"] = $modules;
        echo json_encode($response);

[编辑] 我应该说,moduleids是字符串。

0 个答案:

没有答案