7

I want to be able to store (not echo) some data that has been selected from a mysql database in a php array. So far, I have only been able to echo the information, I just want to be able to store it in an array for later use. Here is my code:

$query = "SELECT interests FROM signup WHERE username = '$username'";
$result = mysql_query($query) or die ("no query");
while($row = mysql_fetch_array($result))
{
echo $row['interests'];
echo "<br />";
}

2 Answers 2

20

You could use

$query = "SELECT interests FROM signup WHERE username = '".mysql_real_escape_string($username)."'";
$result = mysql_query($query) or die ("no query");

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

This will basically store all of the data to the $result_array array.

I've used mysql_fetch_assoc rather than mysql_fetch_array so that the values are mapped to their keys.

I've also included mysql_real_escape_string for protection.

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

Comments

2

You can "store" it by not accessing it from the result set until you need it, but if you really want to just take it and put it in a variable…

$query = "SELECT interests FROM signup WHERE username = '$username'";
$result = mysql_query($query) or die ("no query");

$interests = array();
while(false !== ($row = mysql_fetch_assoc($result))) {
  $interests[] = $row;
}

Comments

Your Answer

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