我试图将特定列中的唯一值放入一个数组中,这样我就可以验证发送到我的 PHP 的内容以避免 mySQL 注入(inject)。这是我拥有的:
$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$sessiont = 'SET SESSION group_concat_max_len=6000';
$fixed = $dbh->query($sessiont);
$stmt = $dbh->prepare("select distinct `category` as cats FROM {$table}");
$stmt->execute();
$row = $stmt->fetch();
$categories = explode(",",$row["cats"]);
$whatCategory = isset($_GET['category']) ? "{$_GET['category']}" : '';
if (in_array($whatCategory, $categories))
{
$sql = "select distinct value from {$table} where category = '{$whatCategory}';";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
header('Content-type: application/json');
echo json_encode($result);
}
else
{
echo ("unauthorized!");
}
现在,这只是给我 category
列中的第一个值,并没有创建有效的数组,这意味着我正在“未经授权!”
如果我像这样替换上面的 $categories
:
$categories = array ('category1','category2','category3');
然后它就起作用了(即,我没有得到 unauthorized!
)
最佳答案
完全未经测试,但查看您最初使用的 sql,您会得到几行可能包含“cats”,而不是一个包含逗号分隔值 cats 的字段。也许您希望使用 group_concat( category
) 作为“猫”来返回单行?
然后您继续测试“$whereCategory”是否在类别数组中。我没有看到之前提到 $whereCategory!
关于php - 通过 PHP 从 mySQL 将列中的不同值获取到数组中的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28633299/