views:

42

answers:

3
$query = "SELECT users FROM tabl ORDER BY RAND()";
$result = mysql_query ($query)
    or die ("Query '$query' failed with error message: \"" . mysql_error () . '"');

while ($row = mysql_fetch_array($result)) {
    $users[] = $row[0];
}

$current = end($users);
$partners = array();
foreach ($users as $user)
{
        $partners[$user] = $current;
        $current = $user;
}
print_r($partners);

$query2 = "UPDATE tabl SET partner = {$partners[0]} WHERE users = '$users'";
mysql_query ($query2)
    or die ("<br>Query '$query2' failed with error message: \"" . mysql_error () . '"');

That's the code I'm working with. Everything is good until query2. I've tried every variation I can think of, but nothing works.

The table on has two fields: users and partners. The code pulls the users in random order, then assigns them to eachother in a circle. I need to populate the partners field with the assignments.

+1  A: 

Place the update query inside the foreach loop, then you have the partner and user variables to hand without diving into the array later on:

foreach ($users as $user)
{
        $partners[$user] = $current;
        $current = $user;
        $query2 = "UPDATE tabl SET partner = '{$partners[$user]}' WHERE users = '{$user}'";
        mysql_query ($query2)
          or die ("<br>Query '$query2' failed with error message: \"" . mysql_error ()
}
Jon
It's a nice solution, but depending on how many $users there are, that may result in several queries on the database.
Rob
true, but if he's trying to assign a different partner to each user then you're not going to be able to avoid multiple queries...
Jon
This is a quick and easy fix, though I suspect the entire segment in the OP could be collapsed somewhat.
Aramis wyler
This solved it; except that you had one small error, its supposed to be: WHERE users = '$user'" No {braces}. Thank you!
David
You're welcome - The braces won't cause a problem, they sometimes help readability - you used them earlier in the query. Also I wasn't sure from the code whether user column type user was.
Jon
A: 

Use WHERE users IN ('.implode(',',$users).')'

Rob
A: 

I would change the code to:

$current = end($users);
$partners = array();
foreach ($users as $user)
{
    $partners[$user] = $current;
    $current = $user;
    $query2 = "UPDATE tabl SET partner = {$partners[$user]} WHERE users = '$user'";
    mysql_query ($query2)
        or die ("<br>Query '$query2' failed with error message: \"" . mysql_error () . '"');
}
print_r($partners);

But you could also do the following depending on the outcome you desire:

$userList = join(',', $users);
$query2 = "UPDATE tabl SET partner = {$partners[0]} WHERE users IN ($userList)";
mysql_query ($query2)
    or die ("<br>Query '$query2' failed with error message: \"" . mysql_error () . '"');
Joseph
Your top solution was the same as Jon's but came later. The bottom one didn't work out, but that's alright.
David
That's what happens when you are slow. :)
Joseph