include "includes/dbh.inc.php";
$data = file_get_contents("dumps/datadump-hung1.json");
$post = json_decode($data, true);
foreach($post['sessionResult']['leaderBoardLines'] as $userArr){
$carname .=$userArr['car']['carModel'];
} echo $carname;
这回显了像这样的车型编号= 19115,而不是19 1 15
[当我尝试将它们与我的数据库进行匹配以回显数字响应的汽车名称时:
$carGETdb = "SELECT carName FROM cars WHERE carID IN ($carname)";
$result = mysqli_query($conn, $carGETdb);
$row = mysqli_fetch_array($result)["carName"];
echo $row;
它没有发布任何东西,因为没有汽车与19115相关联,但是3辆不同的汽车与19、1和15相关联
有没有一种方法可以将每个数组都单独存储,因此我可以将它们与数据库匹配,并以名称代替数字来回显?
?
子句中使用适当数量的IN
参数构建准备好的语句$carIds = array_map(function($userArr) {
return $userArr['car']['carModel'];
}, $post['sessionResult']['leaderBoardLines']);
// [ 19, 1, 15 ]
$placeholders = implode(', ', array_fill(0, count($carIds), '?'));
// "?, ?, ?"
$bindTypes = str_repeat('i', count($carIds));
// "iii"
$stmt = $conn->prepare(
"SELECT `carID`, `carName` FROM `cars` WHERE `carID` IN ($placeholders)");
$stmt->bind_param($bindTypes, ...$carIds);
$stmt->execute();
$stmt->bind_result($carId, $carName);
$carNames = [];
while ($stmt->fetch()) {
$carNames[$carId] = $carName;
}
var_dump($carNames);
使用您的代码...
include "includes/dbh.inc.php";
$data = file_get_contents("dumps/datadump-hung1.json");
$post = json_decode($data, true);
$carname = [];
foreach($post['sessionResult']['leaderBoardLines'] as $userArr){
$carname[] = $userArr['car']['carModel'];
}
$carnames = implode(',', $carname);
echo $carnames;
然后,在查询数据库时,使用以下语句,可以使用隐含值(但这绑定到sql注入攻击)。您应该改为使用参数化查询。但是,我不会对您的代码进行太多更改,因此您可以看到发生了什么。
$carGETdb = "SELECT carName FROM cars WHERE carID IN ($carnames)";
$result = mysqli_query($conn, $carGETdb);
$row = mysqli_fetch_array($result)["carName"];
echo $row;