How to query multiple columns

Asked

Viewed 49 times

0

How can I query in several columns the value equal to the field using PDO

$PDO = db_connect();

$busca = $_POST['campo'];
$vbusca = array("%$busca%");

$sql = 'SELECT * FROM livro AS t WHERE nome LIKE ?';

$stmt = $PDO->prepare($sql);
$stmt->execute($vbusca);
$total = $stmt->rowCount();
  • Have you tried writing the like for each column you wish to consult?

  • Would not cause conflict with the execution?

2 answers

1

Only add other values to WHERE along with OR or AND

$PDO = db_connect();

$busca = $_POST['campo'];
$vbusca = array("%$busca%");

$sql = 'SELECT * FROM livro AS t WHERE coluna1 = ? or coluna2 = ?';

$stmt = $PDO->prepare($sql);
$stmt->execute($vbusca);
$total = $stmt->rowCount();

However, your question did not make clear the type of data you return and what you are looking for. You could also make use of the IN if it is multiple values.

$sql = 'SELECT * FROM livro AS t WHERE coluna1 IN (valor1,valor2)';
  • Pdostatement::execute(): SQLSTATE[HY093]: Invalid Parameter number: number of bound variables does not match number of tokens in

  • This error has returned to me

0


You can not forget the parameters in $vbusca = array();, for each more field, you need to add to the parameter. If you want to search for the same content, for example in book title or book type, then it would be like this:

$PDO = db_connect();

$busca = $_POST['campo'];
$vbusca = array("%$busca%", "%$busca%");

$sql = 'SELECT * FROM livro WHERE nome LIKE ? OR tipo LIKE ?';

$stmt = $PDO->prepare($sql);
$stmt->execute($vbusca);
$total = $stmt->rowCount();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.