1

下の[ユーザー名]リンクをクリックすると、並べ替えられず、理由がわかりません。

 if(isset($_GET['field'])) {

    $orderby = $_GET['field'];
$orderby2 = $_GET['sort'];

}else{
$orderby = "id";
$orderby2 = "ASC";
} if($_GET['sort'] == "ASC") {
    $sortby = "DESC";
}else{
    $sortby = "ASC";

}

並べ替えへのリンク:

<th style="text-align: center;padding:10px;white-space: nowrap;" width="auto" class="rounded-company" scope="col"><a href="dash.php?field=user_name&sort=<?php echo $sortby;?>">Username</a></th>

if(isset($_REQUEST['txtKey'])) {

   $con = "%".$_REQUEST['txtKey']."%";
}

    $result = $db->dbh->prepare("SELECT * FROM ruj_users WHERE user_name like :textKey ORDER BY :order :order2");
    $result->bindValue(":textKey", isset($con) ? $con : null, PDO::PARAM_STR);
    $result->bindParam(":order", $orderby, PDO::PARAM_STR);
    $result->bindParam(":order2", $orderby2, PDO::PARAM_STR);
    $result->execute();
    $result = $result->fetchAll(PDO::FETCH_ASSOC);

    $result2 = $db->dbh->prepare("SELECT * FROM ruj_users WHERE user_name like :textKey ORDER BY :order :order2");
    $result->bindValue(":textKey", isset($con) ? $con : null, PDO::PARAM_STR);
    $result->bindParam(":order", $orderby, PDO::PARAM_STR);
    $result->bindParam(":order2", $orderby2, PDO::PARAM_STR);
    $result2->execute();
    $resultCount = $result2->rowCount();

    if(isset($_REQUEST['txtKey']))$str='&field='.$_GET['field'].'&sort='.$_GET['sort']."&txtKey=".$_REQUEST['txtKey'];

私が何をしているのか、何かが足りないのか教えてください。

4

1 に答える 1

2

bindParam()列名の代わりに使用することはできません。式の値のみを使用できます。したがって、文字列補間を使用する必要があります。

$result = $db->dbh->prepare("SELECT * FROM ruj_users WHERE user_name like :textKey ORDER BY $orderby $orderby2);

残念ながら、これによりSQLインジェクションが可能になるため、これを行う前に入力を検証する必要があります。例えば

if (preg_match('/[^a-z0-1_]/i', $orderby)) {
    // report invalid sort field
}
if (!preg_match('/^(asc|desc)$/i', $orderby2)) {
    // report invalid sort direction
}
于 2013-03-13T16:33:23.887 に答える