create variable from the result of a query and use that variable in another query

Asked

Viewed 882 times

0

is the following, to make a query in the database with php! The code I use is the following:

<?php

$rs = $pdo->query(" SELECT * FROM licitacoes WHERE ID_USER = '$IDLOGADO' ")->fetchAll();

if(!$rs){ print_r($pdo->errorInfo()); }foreach ($rs as $row){

    echo $row['ID_LICITI'] ;}

?>

The result of this consultation is: 2 | 0

I want to turn that resulting into a variable so I can use it in another query! Something like this

<?php

$rs = $pdo->query(" SELECT * FROM outratabela WHERE ID_LICITI = $resultado or  ID_LICITI = $resultado")->fetchAll();

if(!$rs){ print_r($pdo->errorInfo()); }foreach ($rs as $row){

    echo $row['ID_LICITI'] ;}

?>

As you can see I want you to create a Where in the first $result and in case there is more than one result I want to add the OR according to the results.

I want to do this because the results of the first query are parameters to filter the results of the second query, but this "filter" will be given by the same amount of results of the previous query, which will be at most 9 results.

Of course that was the way I thought (and it’s not working out very well, because I don’t know how to do it, I’m lost here), however if how to do otherwise (a more facial) I thank you

1 answer

2

The simplest way would be to use a implode to transform the array of the first query into a comma-separated string and play it on the clasp IN sql.

The problem is that variables passed directly in the sql statement are subject to sql Injection attacks, as is using PDO the ideal would be to utlizar Prepared statements. The logic to solve this problem can be seen here and here

$sql = 'SELECT * FROM outratabela WHERE ID_LICITI '; //segunda consulta.
if(count($rs) > 1){

   $sql .= 'IN('. implode($rs, ',') .')';

   $itens = $pdo->query($sql)->fetchAll();
}
  • failed to concatenate the string -> $sql .= 'IN(

  • @Adirkuhn, thank you really missed the point hehe :)

Browser other questions tagged

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