Проблема PHP с использованием $ _POST в цикле - PullRequest
0 голосов
/ 19 января 2012

edit - я решил проблему с кнопкой «добавить друга», теперь я пытаюсь получить идентификатор пользователя из цикла ниже.Я хочу иметь возможность получить идентификатор пользователя для имени, которое ищет пользователь (имя, которое передается в функцию findUsers, $ friend).Поэтому я хочу использовать результат ['userid'] и отправить его в базу данных.

Я прокомментировал код, в котором у меня возникают проблемы с получением значения для идентификатора пользователя.

<input type="hidden" name="userId" value="' . $result['userid'] . '" />

Есть ли определенный способ использования скрытых входов или просто значение задано неправильно?

<?php
 include_once 'config.php';

class Friends{

 function addFriend($userId) {
  return $userId; //this is supposed to return the value of the user's id selected in the loop below via the if statements towards the bottom.
}

function findUsers($friend){
$search = mysql_query("SELECT * from users where username='$friend'");
if (mysql_num_rows($search) > 0){
// $this->addFriend($friend);
 $userLocation = mysql_query("select * from userinfo where username='$friend'");
        $locationResult = mysql_fetch_array($userLocation);
        $locationResultArray = $locationResult['userlocation'];
        $locationExplode = explode("~","$locationResultArray");
 if (mysql_num_rows($search)) {
  // Table column names
   echo '<table><tr><td>Username</td><td>Location</td></tr>';
  while($result = mysql_fetch_array($search)) {
    echo '<tr>
    <td><a href="profile.php?userid=' . $result['userid'] . '">'.   $result['username'] . '</a></td>
    <td>' . $locationExplode[0] . ', ' . $locationExplode[1] . '</td>
    <td>
    <form method="post" name="friendRequest" action="">
    <input type="hidden" name="userId" value="' . $result['userid'] . '" />
    <input type="submit" name="addFriend" value="Add Friend" />
    </form>
    </td></tr>';
    }

   }
  }
 }
}

$friends = new Friends();
    if (isset($_POST['userId'], $_POST['addFriend'])) {
    echo "friend button pressed"; //this message is displayed
    if ($friends->addFriend($_POST['userId'])) {
            echo "userID set"; //this message is displayed
            echo $_POST['userID']; //this is not displayed
 } else {
 // some error code here
 }
}


// Edit this to test here
// $friends->findUsers('<username>');
?>

1 Ответ

3 голосов
/ 19 января 2012

Этот способ добавления друга является неправильным, потому что когда вы нажимаете кнопку «Добавить друга», это отправит $_POST['addFriend'], а затем в цикле проверки все пользователи добавятся в друзья.

Здесь указан правильный код:

<?php
function addFriend($userId){
  // check is 'userId' exist, if not, then return 0;
}

if (isset($_POST['userId'], $_POST['addFriend'])) {
  if (addFriend($_POST['userId'])) {
    // some display code here
  } else {
    // some error code here
  }
}
while($result = mysql_fetch_array($search)) {
?>
<tr><td>
<form method="post" name="friendRequest" action="">
<input type="hidden" name="userId" value="<?php echo $result['userid']; ?>" />
<input type="submit" name="addFriend" value="Add Friend" />
</form>
</td></tr>
<?php } ?>

EDIT1:

Вы не можете использовать приведенный выше код в функции.Я исправил много ошибок, которые я вижу в вашем коде, но все еще выглядит странно.

Я не понимаю, что вы хотите сделать с вашим кодом, но я сделал это:

<?php
function addFriend($userId) {
  return 1; //using 1 for testing purposes
}

function findUsers($friend) {
  $search = mysql_query('SELECT `userid`, `username`, `userlocation` FROM `users` JOIN `userinfo` ON `users`.`username` = `userinfo`.`username` WHERE `user`.`username` = ' . $friend);
  if (mysql_num_rows($search)) {
    // Table column names
    echo '<table><tr><td>Username</td><td>Location</td></tr>';

    while($result = mysql_fetch_array($search)) {
      $locationExplode = explode('~', $result['userlocation']);
      echo '<tr>
<td><a href="profile.php?userid=' . $result['userid'] . '">'. $result['username'] . '</a></td>
<td>' . $locationExplode[0] . ', ' . $locationExplode[1] . '</td>
<td>
<form method="post" name="friendRequest" action="">
<input type="hidden" name="userId" value="' . $result['userid'] . '" />
<input type="submit" name="addFriend" value="Add Friend" />
</form>
</td></tr>';
    }
  }
}

if (isset($_POST['userId'], $_POST['addFriend'])) {
  if (addFriend($_POST['userId'])) {
    echo "test"; //I'm simply trying to get the input to work, can't get it to post. Just using this for a test.
  } else {
    // some error code here
  }
}

// Edit this to test here
// findUsers('<username>');
?>

EDIT2:

Ну, вам просто нужно поместить код моих функций в класс, а затем использовать другой код вне класса, например:

<?php
include_once 'config.php';

class Friends{
  function addFriend($userId) {
    return 1; //using 1 for testing purposes
  }

  function findUsers($friend) {
    $search = mysql_query('SELECT `userid`, `username`, `userlocation` FROM `users` JOIN `userinfo` ON `users`.`username` = `userinfo`.`username` WHERE `user`.`username` = ' . $friend);
    if (mysql_num_rows($search)) {
      // Table column names
      echo '<table><tr><td>Username</td><td>Location</td></tr>';

      while($result = mysql_fetch_array($search)) {
        $locationExplode = explode('~', $result['userlocation']);
        echo '<tr>
<td><a href="profile.php?userid=' . $result['userid'] . '">'. $result['username'] . '</a></td>
<td>' . $locationExplode[0] . ', ' . $locationExplode[1] . '</td>
<td>
<form method="post" name="friendRequest" action="">
<input type="hidden" name="userId" value="' . $result['userid'] . '" />
<input type="submit" name="addFriend" value="Add Friend" />
</form>
</td></tr>';
      }
    }
  }
}

$friends = new Friends();
if (isset($_POST['userId'], $_POST['addFriend'])) {
  if ($friends->addFriend($_POST['userId'])) {
    echo "test";
  } else {
    // some error code here
  }
}

// Edit this to test here
// $friends->findUsers('<username>');
?>

EDIT3:

Это потому, что функция addFriend неверна ... Вам нужно передать значение идентификатора пользователя в качестве аргумента и затем отобразить его следующим образом:

function addFriend($userId) {
  return $userId; //this is supposed to return the value of the user's id selected in the loop below via the if statements towards the bottom.
}
...