PHP PDO使用一个字符串在两列或多列中搜索值
当我希望使用PDO从行中查找值时,我使用以下方法:PHP PDO使用一个字符串在两列或多列中搜索值,php,mysql,pdo,Php,Mysql,Pdo,当我希望使用PDO从行中查找值时,我使用以下方法: //Search whether user exists $sqlQueryEmailLogin = $dbh->prepare("SELECT vendor_id, first_name, last_name, email_login, user_password, passport_id, login_attempts, login_last_attempt FROM $tableVendorDetails WHERE email_l
//Search whether user exists
$sqlQueryEmailLogin = $dbh->prepare("SELECT vendor_id, first_name, last_name, email_login, user_password, passport_id, login_attempts, login_last_attempt FROM $tableVendorDetails WHERE email_login = ?");
$sqlQueryEmailLogin->bindValue(1, $emailLogin);
$sqlQueryEmailLogin->execute();
下面是搜索字段的PHP代码
$emailLogin = 'xyz@abc.com'
现在我想搜索两列或更多列,并使用以下代码
$sql = "SELECT * FROM articles WHERE id = ? AND status = ?";
$stmt = $conn->prepare($sql);
$stmt->bindValue(1, $id);
$stmt->bindValue(2, $status);
$stmt->execute();
我想从字符串中搜索这两列。请问我该怎么办
我使用的字符串值来自带有一个输入框的html表单
我想要一个能够从MySQL表中搜索两个值的字符串,例如。
$search=$id代码>和
$seach = $status;
在这种情况下,两者都会相互抵消这就是我正在使用的
$sql = "SELECT * FROM articles WHERE id = :id AND status = :status";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':id' => $id , ':status' => $status));
试试下面的方法
$sql = "SELECT * FROM articles WHERE id = :id AND status = :status";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':id', $id);
$stmt->bindValue(':status', $status);
$stmt->execute();
参见文档您应该使用或
而不是和
。这样,您将获得按id或状态匹配的所有行
SELECT * FROM articles WHERE id = ? OR status = ?
您可以使用@gbestard描述的方法来简化它。但你也应该这样做:
$search = 'asdf'; // fill this with your form input
$sql = "SELECT * FROM articles WHERE id = :id OR status = :status";
$stmt = $conn->prepare($sql);
$stmt->execute(array(
':id' => $search,
':status' => $search,
));
注意查询中对或
的更改,并多次提供$search
。。。。第二个例子的问题是?我不明白这个问题。只需从$\u POST
或$\u GET
中的表单输入设置$id
和$status
“一个带有一个输入框的html表单”-您可以与我们共享该html吗?我想要一个能够从MySQL表中搜索两个值的字符串,例如$search=$id;$seach=$status;在这种情况下,两者都会相互取消哦,你的意思是像->prepare(“从id=?或status=?)的文章中选择*”
,然后->执行([$search,$search])
?虽然我同意这种风格更可取,但它如何解决他的问题呢?它们都是等价的,这是对的。它通过使用:status
定义查询变量来解决问题。请参阅PHP文档,以验证@Lex是否阅读了该文档?OPs代码段应该与参数的问号和数字索引一起工作。因此,如果这不起作用,没有理由认为这会起作用。嗨,谢谢你的解决方案。我还得试试。为什么不使用id=?和状态=?。我要找我的将军knowledge@user2333968你仍然可以这样做。。。但在我工作过的公司,这种符号是首选的,因为它更具可读性(因此易于维护代码)。我已经更新了缩进,以显示更高的可读性。请注意数组中最后一个元素后面的逗号,以及使用换行符和缩进的更好格式。