SELECT with PDO and variable

1

How can I do a SELECT in MYSQL with PDO next to it 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 does not return anything. If I do without PDO it returns the news with the title "Test 123 Testing Test"

    
asked by anonymous 25.02.2016 / 19:30

2 answers

2

Do not use single quotation mark in query noticias.titulo LIKE '%teste% , pass wildcards in execute() and set query correctly as it gets outside of placeholder.

$buscarNoticiaTitulo = "valor";
$sqlNoticias = $pdo->prepare('SELECT * FROM noticias WHERE noticias.titulo LIKE :buscarNoticiaTitulo');
$sqlNoticias->execute(array("buscarNoticiaTitulo" => '%'. $buscarNoticiaTitulo .'%'));
    
25.02.2016 / 19:35
2

Well, I ended up getting it this 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's the right way, but it works. Then I will calmly see this issue and if I know anything more correct put here!

    
25.02.2016 / 20:15