Repeat query there is database using for in PHP

Asked

Viewed 38 times

1

I have the following appointment

$turmas= $wpdb->get_results(
    $wpdb->prepare(
        "SELECT nome FROM turmas WHERE id= '%d' ",
        $_POST['idSerie']), ARRAY_A );

When I get $_POST['idSerie'] with an index only it works, but when I get a array no, I need to make a for to take each index, perform this query and save to another array.

For example: if the user marks two series I have to return the classes of these two series.

I’m trying to do it this way, only it’s not working.

$count = count($_POST['idSerie']);
$turmas[];
for ($i = 0; $i < $count; $i++)
    {       
        $turmas[] = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT nome FROM turmas WHERE id= '%d' ",
                $_POST['idSerie'][i]), ARRAY_A);        
    }
  • In case you need him to get the id within the array that will come from idSerie?

  • yes, the variable $_POST['idSerie'] is like this ["10", "11"], I need to separate and search the classes with id 10 me then classes with id 11

  • then It would be 2 queries or can be done in the same query ?

  • would be two queries, or even how many series the user select, if you can do this in one query only, even better, but this array does not have a fixed number, the user can select as many series as he wants

  • Ta good I’ll do so that is just a query there you test. and give me a feedback

1 answer

0

I created a treatment to check if the $_POST[] received is an array or not, if it concatenates the ids and prepares for query, otherwise it simply inserts into query

$count = count($_POST['idSerie']);
$id_query = '';
if(is_array($_POST['idSerie'])){

    foreach ($_POST['idSerie'] as $key => $value) {
        $id_query+=  $value.', ';
    }
    $id_query = substr($id_query, 0, -2);
}else {
    $id_query = $_POST['idSerie'];
}      

$wpdb->get_results($wpdb->prepare("SELECT nome FROM turmas WHERE id IN ({$id_query}) "),ARRAY_A) ;       

In this example I will seek based on all ids, if wanted separate from to hit within the query, using order by id, or making a looping of querys (do not recommend).

  • i saved this value within a variable $test = $wpdb->get_results($wpdb->prepare("SELECT name FROM classes WHERE id IN ('%d') ", $id_query),ARRAY_A); and put in an array to send by json, only it returns twice empty arrays like this: {Array(0)}, it has to join this query in an array and send once

  • Do me a favor, ne this variable $wpdb wheel one var_dump($wpdb); put the result on it so I can see what’s coming back.

  • made an update returns me the test of this update I did. please.

Browser other questions tagged

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