1

I try to retrieve a array from one table What is wrong with this code?

$_fbexclude = mysql_query("SELECT fbempfang FROM fbinvite WHERE fbreturn = '1' ");
$fbexcludearray= mysql_fetch_array($_fbexclude);

// Convert the array 
$excludes = implode(',', $fbexcludearray);

From echo $excludes; It only gives me just the following response: 1000033xxx161,1000033xxx161 Twice the same fbempfang

2
  • You're fetching the rows only once, therefore it creates an array of only one element $fbexcludearray["fbempfang"]. This may cause the problem (i suppose you want to get an array of ALL the rows) Commented Jan 15, 2012 at 0:36
  • yes its correct, i want to get an array with all rows Commented Jan 15, 2012 at 0:37

3 Answers 3

5

See if the following gives you what you want (FIXED):

$_fbexclude = mysql_query("SELECT fbempfang FROM fbinvite WHERE fbreturn = '1'");
$fbexcludearray = array();
while ($row = mysql_fetch_assoc($_fbexclude)) {
  $fbexcludearray[] = $row['fbempfang'];
}

// Convert the array 
$excludes = implode(',', $fbexcludearray);

mysql_fetch_array() and it's siblings (_assoc, _row) only retrieve one row at a time. This means that your original code will only give you the first returned row - to work around this, we use the loop you see above.

The reason you see the same data twice is because mysql_fetch_array() returns a mixed indexed and associative array, which contains all the data twice over. For this reason, it is much better to use mysql_fetch_assoc() or mysql_fetch_row(), as you rarely need both formats.

In fact, it is much better to use mysqli, but the same information applies to that as well.

Sign up to request clarification or add additional context in comments.

1 Comment

Fantástico, justamente o que estava procurando e precisando, esse post resolveu a minha vida, obrigado @DaveRandom.
3

Use right SQL query:

SELECT GROUP_CONCAT(`fbempfang`) as imploded from `fbinvite`  WHERE fbreturn = '1'

It's return string as PHP implode(',', array(…));

Comments

1

Try this on for size:

$implode_arr = array();
$_fbexclude = mysql_query("SELECT fbempfang 
                           FROM fbinvite 
                           WHERE fbreturn = '1'");
while($row = mysql_fetch_array($_fbexclude)) {
    $implode_arr[] = $row['fbempfang'];
}

// Convert the array 
$excludes = implode(',', $implode_arr);

You need to loop over the mysql_fetch_* functions because they only return one of the result rows at a time. For more information and examples see the manual page for mysql_fetch_assoc().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.