Mysql query based on checkbox result

Asked

Viewed 69 times

1

I’m having trouble creating a mysql query based on checkbox.

1. I have a form based on a select that contains a checkbox by line

<input type="checkbox" name="check[]" value="<?php echo $linhas['id'];?>" > 

2. I make an implode to catch the "id"

$check_id = implode(',', $_POST["check"]);

3. $check_id dump results in the "id" I want (clicked)

var_dump($check_id)."<br>"; // retorno do var_dump é string(3) "1,3"

4. finally I would like to create a query to display the data with based on the selected "id".

$comprado = mysqli_query($conn, "

            SELECT pedidos.id as id_comprado, qtde
            FROM pedidos
            WHERE id_comprado = '$check_id'

            ");

5. These are the errors displayed

Warning: mysqli_num_rows() expects Parameter 1 to be mysqli_result, Boolean Given in xxx on line 108

My line 108 is $comprados = mysqli_num_rows($comprado);

Warning: mysqli_fetch_array() expects Parameter 1 to be mysqli_result, Boolean Given in xxx on line 132

My line 132 begins with while($comprados = mysqli_fetch_array($comprado)){...

1 answer

0


Solving your problem is simple. In your query, use IN instead of =. Thus:

$comprado = mysqli_query($conn, "
    SELECT pedidos.id as id_comprado, qtde
    FROM pedidos
    WHERE pedidos.id IN (".$check_id.")
");

EDIT: I edited the query, now it will work. The nickname given in AS cannot be used in WHERE.

  • I made the suggested change, but the errors remain. I used the IN earlier, with another structure and had not been able to.

  • Try printing the amount of $purchased to verify what the real mistake is. For the errors of lines 108 and 132 are derived from the result of $purchased not having been valid.

  • @Hugobarreto I edited my answer, now I believe that it will not fail.

  • I went to try to do directly in sql as you suggested and discovered this error in Where too, worked, but brought only one result. In sql I did as follows to simulate "SELECT id, Qtde, situacao FROM requests WHERE id IN ('1,2,4')", and the result was that only the information of id "1"... this occurred also by changing the query in php.

  • @Hugobarreto only returned one in your case because you put '1,2,4' between simple quotes, actually you have to put ('1', '2', '4') or (1,2,4). Saw the difference?

  • Perfect. Beginner rsrs error. at least I spent 5 days testing other codes/ term that will be useful in other problems. Solved!

  • @Hugobarreto If this answer has solved, stackoverflow has the option to mark it as the correct one, so other people when looking for the same mistake keep in mind that it has helped you and can help them as well.

  • I wasn’t finding this option, but now I think it was... vlw and even

Show 3 more comments

Browser other questions tagged

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