简体   繁体   中英

Query not returning correct results in function

The following function is set up to:

  1. Collect the user_id from my database, as you can see below WHERE subscriber = '$user' . And then:
  2. return the possible multiple values that user_id are.

However, when I've tried to use this function, it has only collected an array, with the key 0 , and value user_id . For apparent reasons I want the array to contain the numerical value that is in the user_id column in my database with the key user_id .

function get_subscribitions($user)
{
    $user = mysql_real_escape_string ($user);

    $sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";

    $result = mysql_query($sql);

    $rows = array();

    while ($row = mysql_fetch_assoc($result)) {
        $rows[] = $row;
    }

    mysql_free_result($result);

    return $rows;
}

Can anyone please pinpoint where I'm making the error leading to these related problems?

Any help appreciated, thank you in advance!

Try instead

$sql = "SELECT user_id FROM `subscribe` WHERE subscriber = '$user'";

Notice the single quotes missing from around user_id

It should be:

 function get_subscribitions($user)
{

$user = mysql_real_escape_string ($user);

  $sql = "SELECT user_id FROM `subscribe` WHERE subscriber = '$user'";

 $result = mysql_query($sql);

  $rows = array();

  while ($row = mysql_fetch_assoc($result)) {
      $rows[] = $row['user_id'];
  }

  mysql_free_result($result);

  return $rows;
}

There were unnecessary quotes in the query and you were not reading the $row array properly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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