简体   繁体   English

PHP会话数组-查询数据库

[英]PHP Session Array - Query Database

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. 我的主页上有4个按钮,每个按钮都有自己的ID。 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. 当某人单击按钮时,Jquery会获取按钮ID并将其通过Ajax发送到PHP,然后将其添加为会话变量。 If people click multiple buttons it will send the ID of each button. 如果人们单击多个按钮,它将发送每个按钮的ID。 So in the end it is possible that I could have 4 variables in the array. 所以最后我可能在数组中有4个变量。

The Session is created as an array so that it can hold the multiple ID's: Like so: 会话被创建为一个数组,以便它可以容纳多个ID:

 <?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 eg: 一切正常,如果我print_r $_SESSION['ids']它正确显示了单击并存储的每个按钮的ID,例如:

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

(Where the button id's that were stored are 1, 3 and 4. (其中存储的按钮ID为1、3和4。

The issue now is that I need to query the database for the button ID's that have been stored. 现在的问题是,我需要在数据库中查询已存储的按钮ID。

How can I break the array up and get just the values eg: The button ID 1, 3 and 4 . 我该如何拆分数组并仅获取值,例如:按钮ID 1, 34 So that I can query the database with them? 这样我就可以用它们查询数据库了?

You can use the implode() function, described here . 您可以使用在此处介绍的implode()函数。

$in = implode(',',$_SESSION['ids']);
mysql_query("SELECT * from yourbd where id in ($in)");//just an eg. mysql_* is deprecated

Look at this function. 看一下这个功能。 Good luck! 祝好运!

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

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";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM