php pdo中查询的2个可能值

时间:2014-10-21 07:41:02

标签: php mysql select pdo

<tr>
    <td>Search Role  :</td>
    <td>
        <input type="text" id="txtsearchrole" name="txtsearchrole" value="" class="box required"/>
    </td>
    <td>Role Id  :</td>
    <td>
        <input type="text" name="roleid" class="box required"/>
    </td>
</tr>

这是我的选择陈述

function RetrieveRole(){
    global $dbh;
    //$stmt = $dbh->prepare("SELECT * FROM rolelist WHERE rolelist_id IN (1,2) ");
    if (!empty($_GET['rolename'])) {
        $stmt = $dbh->prepare("SELECT * FROM rolelist WHERE role_name LIKE ?") ;
        $stmt->bindValue(1,"%".$_GET['rolename']."%");
        if($stmt->execute()){
            if($stmt -> rowCount() >0){
            $role_name = array();
                while ($selected_row = $stmt->fetch(PDO::FETCH_ASSOC)){
                    $role_name[] = array('rolename'  => $selected_row['role_name'],'roleid'  => $selected_row['rolelist_id']);
                }
            return  $role_name;

            }else{
                echo "<script type='text/javascript'>alert('No Role found');
                window.location='../pages/dashboard.php';
                </script>";
                exit;
            }           
        }           
    }else{
        echo "<script type='text/javascript'>alert('Search Role Name is Blank');
        window.location='../pages/dashboard.php';
        </script>";
        exit;
    }       
}

这是一个用于搜索或使用角色名称选择查询的代码我能够有效地使其工作我现在得到结果我在其中添加Role Id以便用户可以使用名称或角色ID我正在寻找如何使这成为可能但不幸的是我无法找到这个问题的确切答案,如果有人有来源或建议请这样做我欣赏任何建议或想法

2 个答案:

答案 0 :(得分:1)

首先你必须改变if语句

if (isset($_GET['txtsearchrole']) || isset($_GET['roleid'])) {

然后您必须更改您的查询以包括搜索角色ID:

$stmt = $dbh->prepare("SELECT * FROM rolelist WHERE role_name LIKE ? OR role_id  = ?") ;

然后更改绑定参数部分:

$stmt->execute(array($_GET['txtsearchrole'], $_GET['roleid']));

答案 1 :(得分:0)

尝试这样:

if (!empty($_GET['rolename'] || $_GET['roleid'])) {
        $stmt = $dbh->prepare("SELECT * FROM rolelist WHERE role_name LIKE ? OR role_id = ?") ;
        $stmt->execute(array($_GET['txtsearchrole'], $_GET['roleid']));
        $result = $stmt->fetchAll();