通过PHP从mySQL将列中的不同值获取到数组中的问题


Issue getting distinct values from column into array from mySQL via PHP

我正试图将特定列中的唯一值获取到数组中,这样我就可以验证发送到PHP的内容,以避免mySQL注入。这是我的:

$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)作为"cats"来返回单行?

然后继续测试"$whereCategory"是否在类别数组中。我没有看到以前提到$whereCategory!