Jump to content

How to store a value from a result set


gwh

Recommended Posts

Hi everyone,

 

I have the following database query:

 

	$sql = "SELECT category FROM categories WHERE catID='$id'";
	$result = mysqli_query($link, $sql);
	if (!$result)
	{
		$error = 'Error getting category to display.';
		include 'error.html.php';
		exit();
	}

	$category = $result;

 

Since most queries return more than one row and multiple columns in a row, I know that the result set is usually stored in an array so it can be accessed for further use as in the following snippet:

 

while ($row = mysqli_fetch_array($result))
{
$categories[] = array('catID' => $row['catID'], 'category' => $row['category']);
}

 

But since my result set will return only one result, ie the category that matches $id, I wondered what is the best way to store the value from the result. I've tried to use:

 

$category = $result;

 

...but this didn't work so I thought this mustn't be the way to do it.

 

Can someone comment on this? I mean am I supposed to store every result set in an array even if only one value is returned?

 

Appreciate any comments/help.

Link to comment
https://forums.phpfreaks.com/topic/188844-how-to-store-a-value-from-a-result-set/
Share on other sites

Thanks for the reply,

 

I changed it according to what you said and then tried to output the value on another page with the following code:

 

    <?php
if ($recordsExist) {

  echo '<p class="warning">'. $category . ' category has dependent records. Can\'t be deleted.</p>';
  }
else {
?>

 

The above code output the following:

 

Array category has dependent records. Can't be deleted.

 

Instead of the name of the category is outputting, "Array".

 

I tried doing a print_r ($category); and it gave the following:

 

Array ( [0] => Shirts [category] => Shirts )

 

Do you know why it's not outputting the category value?

 

Its the same as calling mysqli_fetch_row();

You see mysqli_fetch_array without that flag will return an associative array AND a numerical array, passing that flag means it will only return the numerical one as the associative one isnt needed in this case.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.