Jump to content

Return Array of Results


unemployment

Recommended Posts

Right now my function is only returning a single outputted result.  What am I doing wrong? I want to return an array or at least I think I do.  $usernames is an array and each of those usernames should have an email notification status of 0 or 1.  Basically i'm building a system where you can turn off email notifications.

 

function check_email_notification_status($usernames)
{
if (is_array($usernames) === false)
{
	$usernames = array($usernames);
}

$usernames[] = $GLOBALS['user_info']['username'];

foreach ($usernames as $username)
{
	$username = mres(htmlentities($username));
}

$sql = "SELECT
			`mail_status`
		FROM `users`
		WHERE `username` = '{$username}'";

$result = mysql_query($sql);

return (int)mysql_result($result, 0);
}

Link to comment
https://forums.phpfreaks.com/topic/239681-return-array-of-results/
Share on other sites

You need to select multiple results in your query. Here's a few way to do that

 

<?php


function check_email_notification_status($usernames)
{

$return = array(); // Empty array will be filled with return values later


if (is_array($usernames) === false) $usernames = array($usernames);
array_push( $usernames, $GLOBALS['user_info']['username'] );

// Here's where you want to benchmark. You can do this in a few ways

//THIS WAY - Hard on SQL, single query, easy on memory
// &$username will allow you to change the values in the $usernames array
foreach ($usernames as &$username) $username = mres(htmlentities($username));
$query = 'SELECT `username`, `mail_status` FROM `users` WHERE `username` IN (\''. implode('\',\'') . '\')';
$result = mysql_query($sql);
while( $data = mysql_fetch_assoc($result) ) $return[$data['username']] = (int) $data['mail_status'];

// OR THIS WAY - Hard on SQL, multiple queries, easy on memory
foreach( $usernames as $username ) {
	$username = mres(htmlentities($username));
	$query = 'SELECT `mail_status` FROM `users` WHERE `username` = \''.$username.'\'';
	$result = mysql_query( $query );
	$return[$username] = (int) mysql_result( $result,0 );
}

// OR EVEN THIS WAY - Easy on SQL, single query, hard on memory.
$query = 'SELECT `username`, `mail_status` FROM `users`';
$result = mysql_query( $query );
$allUsers = array();
while( $data = mysql_fetch_assoc($result) ) $allUsers[$data['username']] = (int) $data['mail_status'];
foreach( $usernames as $username ) {
	$username = mres(htmlentities($username));
	$return[$username] = $allUsers[$username];
}

return $return;
}

?>

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.