如何在PHP中查询数组并返回每个元素的单个行/项

时间:2011-02-01 18:17:04

标签: php javascript mysql

我正在编写一个社交网络应用程序,我遇到了一些问题。我会问其中一个因为我不知道这个论坛的规则,即我是否可以发布一个以上的问题。我正在学习PHP,就像我编写代码一样。 我有一个表用户,其中有一个名为pal_array的字段,其中包含作为您朋友的用户的user_id。我的例子,我的朋友阵列有2个user_id。

我希望能够查询所有用户的好友,并能够显示他们的详细信息,例如拇指图片,姓名等。我不知道如何正确使用。

我的代码来自pals.php:

<?php
//Establish the Web Intersect Profile Interaction Token here
if(!isset($_SESSION['wipit']))//Check to see if session wipit is set yet
{
    session_register('wipit');//Be sure to register the session if it is not yet set
}
$thisRandNum = rand(9999999999999,999999999999999999);
$_SESSION['wipit'] = base64_encode($thisRandNum);
?>
<script type="text/javascript" charset="utf-8">
//jquery functionality for toggling member interaction containers
function toggleInteractContainers(x)
{
    if($('#'+x).is(":hidden"))
    {
        $('#'+x).slideDown(200);
    }else
    {
        $('#'+x).hide();
    }
    $('.interactContainers').hide();
}
// Pal accepting 
var palRequestURL = "request_as_pal.php";
var thisRandNum = "<?php echo $thisRandNum; ?>";
function acceptPalRequest (x) {
    $.post(palRequestURL,{ request: "acceptPal", reqID: x, thisWipit: thisRandNum } ,function(data) {
            $("#req"+x).html(data).show();
    });
}
function denyPalRequest (x) {
    $.post(palRequestURL,{ request: "denyPal", reqID: x, thisWipit: thisRandNum } ,function(data) {
           $("#req"+x).html(data).show();
    });
}
// End Pal accepting 
// Pal removal
function removeAsPal(a,b) {
    $("#remove_pal_loader").show();
    $.post(palRequestURL,{ request: "removePal", mem1: a, mem2: b, thisWipit: thisRandNum } ,function(data) {
        $("#remove_friend").html(data).show().fadeOut(12000);
    }); 
}
// End Pal removal 
</script>
<?php require_once('Connections/connections.php'); ?>
<?php
//query username
$user_id = $_SESSION['UserSession'];
mysql_select_db($database_connections, $connections);
$query_user_info = "SELECT username FROM users WHERE user_id='$user_id'";
$user_info = mysql_query($query_user_info, $connections) or die(mysql_error());
$row_user_info = mysql_fetch_assoc($user_info);

//code for displaying all your pals
$query_pal_array = "SELECT pal_array FROM users WHERE user_id='$user_id'";
$pal_array_result = mysql_query($query_pal_array, $connections) or die(mysql_error());
$row_pal_array = mysql_fetch_assoc($pal_array_result);

$pal_array = $row_pal_array['pal_array']; 

$palList = "";
if($pal_array !="")
{
    $palArray = explode(",",$pal_array);
    $palCount = count($palArray);
    $palArray = array_slice($palArray,0,15);
    $i = 0;//how many times we loop over
    foreach($palArray as $key =>$array_value)
    {
        $i++;
    //increment by one
        $palList = "$array_value";      
    }
}
else
{
    $palCount = "0";
}
?>
<table width="500" border="0">
    <tr>
    <td height="20"><div class="heading_text_18"><?php echo $row_user_info ['username']; ?>'s&nbsp;pals <?php echo $palCount ?></div>  </td>
    </tr>
    <tr>
      <td class="interactionLinksDiv" align="right" style="border:none;"><a href="#" onclick="return false" 
      onmousedown="javascript: toggleInteractContainers('pal_requests');">Pal Requests</a></td>
    </tr>
    <tr>
      <td height="5"></td>
    </tr>
</table>
<div class="interactContainers" id="pal_requests">
<?php
//container for accepting/rejecting pal requests
$pal_requests = "SELECT * FROM pal_requests WHERE mem2='$user_id' ORDER BY pal_request_id ASC LIMIT 50";
$pal_request_query = mysql_query($pal_requests) or die(mysql_error());
$pal_request_num_rows = mysql_num_rows($pal_request_query);
if($pal_request_num_rows < 1)
{
    echo '&nbsp;You have no Pal requests at this time.';
    exit();
}
else
{
    while($row_pal_query = mysql_fetch_array($pal_request_query))
    {
    $request_id = $row_pal_query["pal_request_id"];
    $mem1 = $row_pal_query["mem1"];
    $query_user = "SELECT user_first_name, user_last_name, picture_thumb_url FROM users LEFT JOIN picture ON users.user_id = picture.user_id
    AND picture.avatar=1 WHERE users.user_id='$mem1' LIMIT 1";
    $user_info = mysql_query($query_user, $connections) or die(mysql_error());
    while ($row = mysql_fetch_array($user_info)){ $requesterFirstName = $row["user_first_name"]; $requesterLastName = $row["user_last_name"]; }
    {
        if(!empty($row["picture_thumb_url"]))
        {
            $avatar = '<a href="user_view.php?user_id2=' . $mem1 . '"><img src="/NNL/User_Images/' . $row["picture_thumb_url"] . '" width="50" height="50" border="0"/></a>';
        }
        else
        {
            $avatar = '<a href="user_view.php?user_id2=' . $mem1 . '"><img src="/NNL/Style/Images/default_avatar.png" width="50" height="50" border="0"/></a>';
        }
    echo '<hr />
    <table width="100%" cellpadding="5">
     <tr>
       <td width="17%" align="left"><div style="overflow:hidden; height:50px;">'. $avatar .'</div></td>
       <td width="83%"><a class="ordinary_text_12_blue "href="user_view.php?user_id2=' . $mem1 . '">'. $requesterFirstName .' '.   $requesterLastName .'</a> 
       wants to be your Pal<br /><br />
       <span id="req' . $request_id . '">
       <a class="ordinary_text_12" href="#" onclick="return false" onmousedown="javascript:acceptPalRequest(' . $request_id . ');" >Accept</a>
       &nbsp; &nbsp; OR &nbsp; &nbsp;
       <a class="ordinary_text_12" href="#" onclick="return false" onmousedown="javascript:denyPalRequest(' . $request_id . ');" >Deny</a>
       </span></td>
     </tr>
    </table>';    
    }
}            
}
?> 
</div> 
<?php
//get pal avatars
$query_pal_info = "SELECT users.user_id, user_first_name, user_last_name, username, picture_thumb_url, avatar FROM users LEFT JOIN picture ON users.user_id = picture.user_id
AND picture.avatar=1 WHERE users.user_id = $array_value";
$pal_info  = mysql_query($query_pal_info , $connections) or die(mysql_error());
$totalRows_pal_info  = mysql_num_rows($pal_info );
echo $totalRows_pal_info; 

echo "\n<table>";
$i = 5;
while ($row_pal_info  = mysql_fetch_assoc($pal_info))
{
if($i==5) echo "\n\t<tr>";
$thumbnail_user = $row_pal_info['picture_thumb_url'] != '' ? $row_pal_info['picture_thumb_url'] : '../Style/Images/default_avatar.png';
echo "<td width='100' height='100' align='center' valign='middle'><a href = 'user_view.php?user_id2=$array_value'>
  <img src='/NNL/User_Images/$thumbnail_user' border='0'/></a></td>\n";
$i--;
if($i==0) {
echo "\n\t</tr>\n\t<tr>";
$i = 5;
} 
}
if($i!=5) echo "\n\t\t<td colspan=\"$i\"></td>\n\t</tr>";
echo "\n</table>";
?> 

靠近底部,我有这个查询

$query_pal_info = "SELECT users.user_id, user_first_name, user_last_name, username, picture_thumb_url, avatar FROM users LEFT JOIN picture ON users.user_id = picture.user_id
AND picture.avatar=1 WHERE users.user_id = $array_value"; 

变量$ array_value包含pals的user_id数组。我怎样才能展示个别朋友?我还有一个问题,为什么我的interactContainers div下面的任何内容都不会显示。

提前致谢

2 个答案:

答案 0 :(得分:1)

重要
在回答这个问题之前,我必须确保你理解你正在做的事情的不安全感。您真的需要阅读SQL injection并重新评估您的查询设计方式。您应该转义所有值(包括来自数据库的值)。

<强>答案
好的,所以说应该做什么,有一个pal表,它只是将用户链接到其他用户。字段为user_idpal_id。这两个都是用户表中user_id字段的外键。

然后您可以编写这样的查询来获取朋友信息:

SELECT usr.*
FROM pal
INNER JOIN users
ON pal.pal_id = users.user_id
WHERE pal.user_id = XXX (User's ID here)

存储“好朋友”的数组方法将变得非常古老,一旦你开始想要做更精细的事情(比如找到好朋友等等)就会很快。

如果您真的想要使用IN关键字,可以执行现在的查询(尽管我建议您更改数据库结构;这也可以消除转义的麻烦)这个字符串)。假设您的$pal_array变量有一个用逗号分隔的用户ID列表: $query_pal_info = "SELECT users.user_id, user_first_name, user_last_name, username, picture_thumb_url, avatar FROM users LEFT JOIN picture ON users.user_id = picture.user_id AND picture.avatar=1 WHERE users.user_id IN ($pal_array)";

答案 1 :(得分:0)

您需要使用逗号加入数组并使用IN。