Returning multiple values from a function

  • (5 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »

60 Replies - 3337 Views - Last Post: 20 February 2013 - 11:48 AM Rate Topic: -----

#1 Darkranger85  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 190
  • Joined: 31-August 12

Returning multiple values from a function

Posted 16 February 2013 - 07:27 AM

Hey again guys,

I'm creating a new login/registration system based on a tutorial from phpacademy.org. But since it's a tutoria;, it's a little on the basic side. So I'm trying to expand it as I go to fit my needs.

For example his passwords use md5 for the sake of simplicity, however I'm using crypt with a randomly generated salt that is stored in the database.

There are two functions that I'm working with for the login system, here they are.

function userid_from_username (){
	$username = sanitize($username);
	$query = mysql_query("SELECT `id`, `salt`
						  FROM `user_data`
						  WHERE`username` = '$username'
						");	
	
	return mysql_result($query, 0, 'id');
}

function login ($username, $password){
	$user_id = userid_from_username($username);
	$salt; //Define once I figure out how to get the value back from the function above
	$username = sanitize($username);
	$password = crypt($password, $salt);
	
	$query = mysql_query("SELECT COUNT(`id`)
						  FROM `user_data`
						  WHERE `username` = '$username'
						  AND `password` = '$password'
						");
	
	return (mysql_result($query, 0) == 1) ? $user_id : false;
}



I suppose it's actually 3 functions. The sanitize function simply runs the username variable through mysql_real_escape_string and returns it.

(I know that the mysql functions are recommended to be replaced by PDO or mysqli, and once I am comfortable with PDO I will, but at the moment I am still having trouble with that.)

So basically what I'm trying to do is make the top function return both the user_id and the salt. I tried using an array and then telling it to return the array but I got an error about mysql_result not being able to jump to 0 or 1.

I also tried using mysql_fetch_assoc and then returning the array from that but when I tried to access the array it said that it was undefined.

Unfortunatly I lost the changes I had made to that point.

Is This A Good Question/Topic? 0
  • +

Replies To: Returning multiple values from a function

#2 Eric115  Icon User is offline

  • coderさん
  • member icon

Reputation: 63
  • View blog
  • Posts: 698
  • Joined: 19-January 09

Re: Returning multiple values from a function

Posted 16 February 2013 - 08:16 AM

Hi,
What error were you getting about the array?

I think something like this should work?

function userid_from_username (){
	$username = sanitize($username);
	$query = mysql_query("SELECT `id`, `salt`
	 FROM `user_data`
	 WHERE`username` = '$username'");	
	$my_results = Array();
        $my_results[] = mysql_result($query, 0, 'id');
        $my_results[] = mysql_result($query, 0, 'salt');
	return ;
}



Let me know if that helps!
Was This Post Helpful? 1
  • +
  • -

#3 andrewsw  Icon User is online

  • say what now
  • member icon

Reputation: 6409
  • View blog
  • Posts: 25,903
  • Joined: 12-December 12

Re: Returning multiple values from a function

Posted 16 February 2013 - 08:34 AM

I assume Eric meant to return the array:

return $my_results;
// called as 
$some_other_array = userid_from_username();

You can even return them into a list
list($user_id, $salt) = userid_from_username();

I would rename the function to represent the return value:
user_info();

and I would pass the username as a parameter to make it less deterministic/ more flexible.
Was This Post Helpful? 2
  • +
  • -

#4 andrewsw  Icon User is online

  • say what now
  • member icon

Reputation: 6409
  • View blog
  • Posts: 25,903
  • Joined: 12-December 12

Re: Returning multiple values from a function

Posted 16 February 2013 - 08:40 AM

Mmm deterministic is not quite the term I am looking for. I mean:

the result from a function should be deterministic; that is, its output should be completely determined by its input.

This isn't possible with your current function though, as the name of the table, fields, etc., is hard-coded in your function.
Was This Post Helpful? 0
  • +
  • -

#5 Darkranger85  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 190
  • Joined: 31-August 12

Re: Returning multiple values from a function

Posted 16 February 2013 - 08:52 AM

Ok, using you guys advice this is what I have come up with so far.

I'm sure the problem is that I'm trying to access the returned array incorrectly.

It says the salt and id variables are undefined in the second function.

function userid_from_username ($username){
	$username = sanitize($username);
	$query = mysql_query("SELECT `id`, `salt`
						  FROM `user_data`
						  WHERE`username` = '$username'");
	
		$results = Array();
        $results[] = mysql_result($query, 0, 'id');
        $results[] = mysql_result($query, 0, 'salt');	
	
	return $results;
}

function login ($username, $password){
	$userid_salt = userid_from_username($username);//Sends username to above function to return id and salt
	
	$user_id = $userid_salt['id'];
	$salt = $userid_salt['salt'];
	$username = sanitize($username);
	$password = crypt($password, $salt);
	
	$query = mysql_query("SELECT COUNT(`id`)
						  FROM `user_data`
						  WHERE `username` = '$username'
						  AND `password` = '$password'");
	
	return (mysql_result($query, 0) == 1) ? $user_id : false;
}



I will rename the function to something more appropriate as well.

This post has been edited by Darkranger85: 16 February 2013 - 08:53 AM

Was This Post Helpful? 0
  • +
  • -

#6 andrewsw  Icon User is online

  • say what now
  • member icon

Reputation: 6409
  • View blog
  • Posts: 25,903
  • Joined: 12-December 12

Re: Returning multiple values from a function

Posted 16 February 2013 - 09:16 AM

$user_id = $userid_salt['id'];

You haven't assigned a key to the array-elements so they need to be accessed by index:
$user_id = $userid_salt[0];


Use print_r() and similar to help you debug your code.
Was This Post Helpful? 1
  • +
  • -

#7 Darkranger85  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 190
  • Joined: 31-August 12

Re: Returning multiple values from a function

Posted 16 February 2013 - 09:30 AM

Sorry, I thought the 'id' in the in the mysql_result also set the element name. My mistake lol

Works great! :)
Was This Post Helpful? 0
  • +
  • -

#8 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3717
  • View blog
  • Posts: 13,492
  • Joined: 08-August 08

Re: Returning multiple values from a function

Posted 16 February 2013 - 10:22 AM

It may work but it isn't great. You shouldn't be using mysql functions because they're insecure. Using prepared statements eliminates the need to sanitize. If you made this a class you could set attributes from within the method so there would be no need to return anything.

Untested and unfinished:
class site_user {
	protected $id;
	protected $salt;
	
	function get_attrib($attr){
		return $this->$attr;
	}
	
	function userid_from_username ($username, $pdo){
		$query = "SELECT `id`, `salt` FROM `user_data` WHERE`username` = ?";
		$userinfo = $pdo->prepare($query);
		$userinfo->execute(array($username));
		foreach($userinfo as $data) {
			$this->id = $data['id'];
			$this->salt = $data['salt'];
		}
	}
	
}

Was This Post Helpful? 0
  • +
  • -

#9 Darkranger85  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 190
  • Joined: 31-August 12

Re: Returning multiple values from a function

Posted 16 February 2013 - 11:12 AM

Yeah, I want to change my mysql functions over to PDO but I spent 3 days trying to figure out how to properly use it and started to get very frustrated.

At the moment I'm following a structured tutorial series so I thought the best idea would be to get it working and then go back and replace the mysql with PDO because if I try and do it now I'm going to be struggling to follow along with the rest of the tutorial because we will be using different techniques.
Was This Post Helpful? 0
  • +
  • -

#10 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3717
  • View blog
  • Posts: 13,492
  • Joined: 08-August 08

Re: Returning multiple values from a function

Posted 16 February 2013 - 12:06 PM

View PostDarkranger85, on 16 February 2013 - 02:12 PM, said:

Yeah, I want to change my mysql functions over to PDO but I spent 3 days trying to figure out how to properly use it and started to get very frustrated.

Read this one. It's the best one I've seen.

View PostDarkranger85, on 16 February 2013 - 02:12 PM, said:

...so I thought the best idea would be to get it working and then go back...

Almost always a bad idea. I say almost only to allow for the possibility that there might some day be some evidence of a situation where it might not be a bad idea.
Was This Post Helpful? 3
  • +
  • -

#11 Eric115  Icon User is offline

  • coderさん
  • member icon

Reputation: 63
  • View blog
  • Posts: 698
  • Joined: 19-January 09

Re: Returning multiple values from a function

Posted 17 February 2013 - 12:56 AM

View Postandrewsw, on 16 February 2013 - 08:34 AM, said:

I assume Eric meant to return the array:

return $my_results;
// called as 
$some_other_array = userid_from_username();

You can even return them into a list
list($user_id, $salt) = userid_from_username();

I would rename the function to represent the return value:
user_info();

and I would pass the username as a parameter to make it less deterministic/ more flexible.


Whoops, I knew I forgot something here >.<
Was This Post Helpful? 0
  • +
  • -

#12 Darkranger85  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 190
  • Joined: 31-August 12

Re: Returning multiple values from a function

Posted 17 February 2013 - 09:59 PM

Ok, I've taken your advice and scraped the old mysql functions.

I also read the article you links and the articles listed in that one.

I'm working on my very first function that needs to connect to the database and I'm having a real hard time getting it to work (surprise! lol).

First of all I had a hard time getting the include path to work right. So finally I just put the connect.php file in the same directory as the functions file.

Now, I'm getting these errors:

Notice: Undefined variable: PDO in C:\wamp\www\Projects\Planet Ruin v2\core\users.php on line 6

Fatal error: Call to a member function prepare() on a non-object in C:\wamp\www\Projects\Planet Ruin v2\core\users.php on line 6

I defined the pdo variable in the connect.php file and included that file on the users file. Not sure why I can't access it as I've had no trouble accessing other variables and arrays inside of included files.

I can only assume I'm either stupidly overlooking something or it has to do with the fact that a PDO object functions differently than a normal variable or array. Though I don't remember reading about this in the articles and videos that I have seen.

users.php

<?php
include 'connect.php';

function user_exists($username){
	$query = $PDO->prepare("SELECT COUNT(`id`) FROM `user_data` WHERE `username` = ?");
	$query->execute(array($username));
	
	$result = $query->fetchObject();
	echo $result;
}
?>



connect.php

<?php
$host = 'localhost';
$database = 'game_db';
$username = 'root';
$password = '';

$PDO = new PDO('mysql:host=localhost;dbname=game_db', $username, $password);
?>


Was This Post Helpful? 0
  • +
  • -

#13 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6246
  • View blog
  • Posts: 24,014
  • Joined: 23-August 08

Re: Returning multiple values from a function

Posted 18 February 2013 - 04:39 AM

You've made $PDO a global variable. In order to access it within the user_exists function, you will need to add global $PDO; at the start of this function to let PHP know that you're using this global variable.

You should shortly expect someone to come in and tell you that global variables as a rule are bad, however.
Was This Post Helpful? 0
  • +
  • -

#14 andrewsw  Icon User is online

  • say what now
  • member icon

Reputation: 6409
  • View blog
  • Posts: 25,903
  • Joined: 12-December 12

Re: Returning multiple values from a function

Posted 18 February 2013 - 04:53 AM

I might upset a few people by suggesting that $PDO can be global :whatsthat:

That is, don't include connect.php in any page that doesn't need the connection. Otherwise, the entire page is likely to need this connection object.

The alternatives are to pass the connection between every method, or to keep opening and closing the connection (bad).

I'm not saying that I do this myself currently, but just throwing it out there.. and awaiting the brickbats :)

Of course, global variables are bad, but for something that is global, it is okay.

This post has been edited by andrewsw: 18 February 2013 - 04:54 AM

Was This Post Helpful? 0
  • +
  • -

#15 Darkranger85  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 190
  • Joined: 31-August 12

Re: Returning multiple values from a function

Posted 18 February 2013 - 07:11 AM

The way the tutorial goes is that I have an init.php script that requires the connect.php file itself as well as other things such as starting the session.

I tried to include that file first but it gave an error about a session already being started.
Was This Post Helpful? 0
  • +
  • -

  • (5 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »