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] => [email protected]
   [owner] => chris
)

 

instead of:

Array(
   [0] => Array (
      [uid] => 2
      [email] => [email protected]
      [owner] => chris
   )
)

Link to comment
https://forums.phpfreaks.com/topic/78185-array/
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
https://forums.phpfreaks.com/topic/78185-array/#findComment-395649
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
https://forums.phpfreaks.com/topic/78185-array/#findComment-395655
Share on other sites

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.