Jump to content

array


poe

Recommended Posts

i have this function at querys a db and returns an array.

function getAll($sql) {
	$data = array();
	$result = $this->query($sql);
	while($row = mysql_fetch_assoc($result)) {
		$data[] = $row;
	}
	return $data;
}

 

now, if i know the result is going to be just 1 row...

 

i there a way to alter it so it returns and i can access by $myarray instead of $myarray[0].

 

ie this:

Array (
   [uid] => 2
   [email] => chris@home.com
   [owner] => chris
)

 

instead of:

Array(
   [0] => Array (
      [uid] => 2
      [email] => chris@home.com
      [owner] => chris
   )
)

Link to comment
Share on other sites

because you aren't writing a multi deminsonal array, but a flat array you will need to do something like

<?php
function getAll($sql) {

$result = $this->query($sql);
$count = mysql_num_rows($result);
if(mysql_num_rows($result) >0){
	$data = array();
	$i = 0;
	while($row = mysql_fetch_assoc($result)) {
		foreach($row as $key => $value){
			$data[$i][$key] = $value;
		}
		$i++;
	}
}
else{
	$data = 0;
}
return $data;
}
?>

 

Then you will want to make sure $var = getALL($sql); $var >0 if its not then you got no results

Link to comment
Share on other sites

New function:

 

<?php

$sql = "SELECT `email` FROM `tablename` WHERE some_condition";
$email = getOne($sql);

function getOne($sql) {
   if ( !$result = $this->query($sql) ) {
       die("Query failed:" . mysql_error());
   }
   $row = mysql_fetch_row($result);
   return $row[0];
}

?>

 

PhREEEk    

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.