Amy
Amy

Reputation: 5

Storing the result of an SQL call in a php variable

I have the code below and it's working as it should however instead of echoing the results to the screen, I need to store the results in a php variable called $var. How would I go about doing that?

<?php
$sql = "SELECT id_member FROM smf_members WHERE FIND_IN_SET(24,additional_groups)";

$con = mysql_connect('localhost', 'sqluser', 'sqlpass');
if (!$con) {
   die('Could not connect: ' . mysql_error());
}

mysql_select_db("test_db");
$result = mysql_query($sql, $con);

while ($row = mysql_fetch_array($result)) {
   echo $row['id_member'];
}

mysql_close($con);
?>

Upvotes: 0

Views: 6129

Answers (4)

Tristan
Tristan

Reputation: 3885

Depending on what you want to achieve here is a few possible ways of doing this

$var = "";

while ($row = mysql_fetch_array($result)) {
  $var .= $row['id_member'] . "\n";
}

$var = array();

while ($row = mysql_fetch_array($result)) {
  $var[] = $row['id_member'];
}

Upvotes: 4

Rolice
Rolice

Reputation: 3103

<?php
$sql = "SELECT id_member FROM smf_members WHERE FIND_IN_SET(24,additional_groups)";

$con = mysql_connect('localhost', 'sqluser', 'sqlpass');
if (!$con) {
    die('Could not connect: ' . mysql_error());
}

mysql_select_db("test_db");

$result = mysql_query($sql, $con);

$v = array(); // $v instead of $var, since var is a keyword and may cause troubles

while ($row = mysql_fetch_array($result)) {
array_push($v, $row['id_member']); 
// or
//$v[] = $row['id_member'];
}

mysql_close($con);

?>

Upvotes: 2

Joe Flynn
Joe Flynn

Reputation: 7204

replace echo with $var[].

That will push each result onto the end of the array. It would probably be good to define the variable first.

$var = array();
while ($row = mysql_fetch_array($result)) {

  $var[] = $row['id_member'];
}

Upvotes: 2

Shef
Shef

Reputation: 45599

If the select statement will return more than one result, then you need to store the values in an array:

$member_ids = array();
while ($row = mysql_fetch_array($result)) {
  $member_ids[] = $row['id_member'];
}

If the select statement will return a single result (you can make sure by appending a LIMIT 1 to the value of the $sql variable).

$row = mysql_fetch_array($result);
$member_id = $row['id_member'];

Upvotes: 1

Related Questions