SELECT with PDO and variable

Asked

Viewed 4,076 times

1

How is it possible to make a SELECT in MYSQL with PDO next to this below:

$buscarNoticiaTitulo = "noticias.titulo LIKE '%teste%'";
$sqlNoticias = $pdo->prepare('SELECT * FROM noticias WHERE :buscarNoticiaTitulo');
$sqlNoticias->execute(array("buscarNoticiaTitulo" => $buscarNoticiaTitulo));
$resultadoSqlNoticias = $sqlNoticias->fetchAll();

The above example does not give any error, but also does not return anything. If I do without PDO it returns the news with the title "Test 123 testing"

3 answers

2

Do not use single quote in query noticias.titulo LIKE '%teste%, pass the jokers on execute() and correctly assemble the like query gets out of the placeholder.

$buscarNoticiaTitulo = "valor";
$sqlNoticias = $pdo->prepare('SELECT * FROM noticias WHERE noticias.titulo LIKE :buscarNoticiaTitulo');
$sqlNoticias->execute(array("buscarNoticiaTitulo" => '%'. $buscarNoticiaTitulo .'%'));
  • The problem is that the $buscarNoticiaTitulo variable receives several values from an array, so I was mounting it like this: $buscarNoticiaTitulo = "noticias.titulo LIKE '%teste%' OR noticias.titulo LIKE '%orelha%'" It can receive infinite words, according to the user’s search... @rray

  • @caiocafardo needs to change all logic, to generate the placeholder and mount the ORs, pera ai

  • @caiocafardo maybe this question will help: Search System - Select within another

  • Is there an error in the answer? can I correct.

2

Well, I ended up getting it that way:

$buscarNoticiaTitulo = "noticias.titulo LIKE '%teste%'";
$sqlNoticias = $pdo->prepare('SELECT * FROM noticias WHERE '.$buscarNoticiaTitulo.'');
$sqlNoticias->execute();
$resultadoSqlNoticias = $sqlNoticias->fetchAll();

I do not know if it is the most correct way, but it works. Then I will take a look at this question and if you know something more correct put here!

0

$teste = 'noticia tal';

$sqlNoticias = $pdo->prepare('SELECT * FROM noticias WHERE titulo LIKE :titulo');
$sqlNoticias->execute(array(
 ':titulo' => '%'.$teste.'%'
));

$resultado = $sqlNoticias->fetchAll();

Browser other questions tagged

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