我正在尝试使用 PDO 准备语句运行查询,该语句允许我让用户选择一个字段,然后为该字段输入值,并将其包含在我的查询中。
所以在这个基本查询中:
$sql = "SELECT LastName, FirstName FROM administrators WHERE Status=:Status ";
$stmt->bindParam(':Status',$Status, PDO::PARAM_STR);
效果很好。
但我有一个搜索表单,允许说用户选择显示名字、姓氏的下拉菜单,然后是一个文本框来输入搜索词
$sql = "SELECT LastName, FirstName FROM administrators WHERE Status=:Status **AND FIELD = TERM**";
到目前为止,我还没有在网上找到任何好的例子。任何指导表示赞赏。
我在用:
$params = array();
if (!empty($SearchField) && !empty($SearchFor))
{
$params['SearchField'] = $SearchField;
$params['SearchFor'] = $SearchFor;
}
但我收到错误:致命错误:未捕获的异常 'PDOException' 带有消息'SQLSTATE [42S22]:找不到列:'where 子句'中的 1054 未知列 'SearchField''
更新代码:
这是我在表单中使用的代码:
<input id="searchtext" name="searchtext" type="text" placeholder="Search" value="<?php echo GetParam('searchtext'); ?>" />
<select name="searchby">
<option value="">Search By</option>
<option id="LastName" value="LastName" <?php if(GetParam('searchby') == 'LastName'){echo "selected='selected'";}?>>Last Name</option>
<option id="FirstName" value="FirstName" <?php if(GetParam('searchby') == 'FirstName'){echo "selected='selected'";}?>>First Name</option>
<option id="RoleName" value="RoleName" <?php if(GetParam('searchby') == 'RoleName'){echo "selected='selected'";}?>>Role Name</option>
</select>
<input type="submit" id="submit" name="command" value="search" />
这是我的方法的代码:
public function GetAllUsers($Status = 'A',$SearchField = '',$SearchFor = '')
{
$db=DB::getInstance();
$sql = "SELECT administrators.AdminId, AdminEmail, LastName, FirstName, PrimaryPhone, CellPhone, administrators.Status, LoginDateTime, RoleName FROM administrators INNER JOIN permissions on permissions.AdminId=administrators.AdminId INNER JOIN roles on roles.RoleId=permissions.RoleId INNER JOIN sessions on sessions.AdminId=administrators.AdminId WHERE Status=:Status ";
$stmt=$db->prepare($sql);
$stmt->bindParam(':Status',$Status, PDO::PARAM_STR);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_OBJ);
}