0

This is a follow on to a previous question.

I have 4 buttons on my home page, each has their own ID associated to them. When someone clicks a button Jquery grabs the button ID and sends it to PHP via Ajax where it is then added as a session variable. If people click multiple buttons it will send the ID of each button. So in the end it is possible that I could have 4 variables in the array.

The Session is created as an array so that it can hold the multiple ID's: Like so:

 <?php
    session_start();

    if ( ! is_array( $_SESSION['ids'] ) ) {
       $_SESSION['ids'] = array();
    }

    if ( ! in_array($_POST['session'], $_SESSION['ids'] ) ) {
       $_SESSION['ids'][] = $_POST['session'];
    }
 ?>

That all works correctly and If i print_r $_SESSION['ids'] it correctly shows the id of each button that was clicked and stored e.g:

[0] => 1, null, [1] => 3, null, [2] => 4

(Where the button id's that were stored are 1, 3 and 4.

The issue now is that I need to query the database for the button ID's that have been stored.

How can I break the array up and get just the values e.g: The button ID 1, 3 and 4. So that I can query the database with them?

1
  • You can use for loop to traverse the buttons session array. What is the problem you are facing? Commented Jan 16, 2013 at 3:57

4 Answers 4

1

You can use the implode() function, described here.

$in = implode(',',$_SESSION['ids']);
mysql_query("SELECT * from yourbd where id in ($in)");//just an eg. mysql_* is deprecated
Sign up to request clarification or add additional context in comments.

Comments

0

Look at this function. Good luck!

Comments

0

Change Array

  foreach ($IdsArray as $myId) {
    $newIds[] = 'my_id = ' . $myId;
  }
  $orSeparatedIds = implode(" OR ", $newIds);

Use in Query

$query = "select my_id from mytable where $orSeparatedIds";

Comments

0
$buttons=$_SESSION['ids'];
$str=implode(', ',$buttons);
$sqlquery = mysql_query("Select * from table where btn_id IN ($str)");      

8 Comments

The issue with that is it then returns the ID's as a single number: E.g: Gets ID 1 and 3 but it places them as 13.
@JPDP ok. can you please print the array $_SESSION['ids'] and paste it here
Print_r = Array ( [0] => [1] => 1 [2] => 3 ) And the echo: 13
@JPDP Sorry, I still do not understand. Do you mean that if you use the code in my answer, you are getting 13?
Thats right, so your code is getting the 2 Id's that are stored in the sessions (in this example they are ID 1 and ID 3. So the output is 13. When I try to query the databse for $btn it thinks I mean 13 instead of 1,3
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.