[web] PHP - mysql_num_rows

Started by
8 comments, last by walle 16 years, 11 months ago
I'm having a slightly odd problem with mysql_num_rows that I've been stuck on for a day now.

// PROBLEM QUERY ----
$userAuthorizationQuery = $this->query("SELECT * FROM btxsys_users WHERE username=
" . $this->prepval($_SESSION[$this->configSessionNames["Username"]]) . " 
AND password=
" . $this->prepval($_SESSION[$this->configSessionNames["Password"]])
);

if (mysql_num_rows($userAuthorizationQuery) == 0)
{
    etc...
}
The error? Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\xampp\htdocs\includes\Class.Page.php on line 166. Now, I know the temptation is unbearable, so I'll go ahead and answer the main question - YES, the variables for username and password contain information ('Username', 'Password', prepval() adds the quotes, and I've tried entering username and password manually but same error). mysql_error also reports nothing. I've looked at this from every angle possible... anyone read the problem point?
Advertisement
Well, I would say that the query is failing and you don't get a valid result back. I reckon $this has a database connection and query() returns a result. Test the query in a external program, like query browser or something.
Agreed, print out the exact query it's doing and cut and paste that into some other tool ( web or command line based ) to see what result it returns. If it's not valid then you know the issue is with the sql statement. If it does return a valid data set then the issue is elsewhere.

========
Andrew
Agreed. Furthermore, for good coding practices, you should ALWAYS test your return results to verify they are valid before using them.
"Iacta alea est" - Julius Caesar"So far as I know, I've never been defeated by a 'powerful over-arching potentiality' before"
Appreciate the replies, however I don't think its in the query - all queries I try return bad results ("SELECT * FROM btxsys_users" returns same error, as well as any other query).

Alright, new update - it must be a problem with the class, observe the following...

// VALID resource$query = mysql_query("SELECT * FROM btxsys_users");// NOT VALID$query = $page->query("SELECT * FROM btxsys_users");// $page->query()function query( $sql ){    return $sql;}


I don't think there would be any interference between, but somethings wrong? If needed I can paste the class, but its a big class, don't want to cloud the space with unneeded things.

[Edited by - AaronA on May 13, 2007 7:48:41 PM]
You mean
$result = mysql_query("SELECT * FROM btxsys_users");
right?

Post the class if you can, seams like there is a problem within it.
Don't see the difference besides variable name, which shouldn't make a difference :P

Well, here comes the class, debug at will and caution, its not tidy, some stuff even isn't used.

<?define("PAGE_COOKIES", "pcookies");define("PAGE_SESSIONS", "psessions");define("PAGE_IP", "pip");define("PAGE_NOAUTH", "pnoauth");define("PAGE_RELOAD", "preload");define("PAGE_GUEST", "0");define("PAGE_USERS", "1");define("PAGE_ADMINISTRATION", "2");define("PAGE_DEVELOPER", "3");define("USERNAME", "username");define("PASSWORD", "password");define("USERID", "userID");define("LEVEL", "userLevel");class Page{	var $pageURL; // Current URL [www.website.com/script/script.php]	var $pageURLex; // Current URL [/script/script.php]	var $pageReferer; // Where the user has come from.	var $userAgent; // Browser [Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586)]	var $userIP; // IP Address in which the user is viewing the page.	var $userLevel; // Authorization level for the user.	var $userInfo; // Holds assoc of user information.	var $serverName; // Server Name	var $serverSoftware; // Server identification string	var $serverProtocol; // Protocol in which the server is running. [HTTP/1.0]	var $configAuthMethod; // Authorization Method (PAGE_COOKIES, PAGE_SESSIONS, PAGE_IP, PAGE_NOAUTH)	var $configSessionNames = 		array("ID" => "sessionID", "Username" => "sessionUsername", "Password" => "sessionPassword"); 		// Array of session/cookie names		var $configSessionTimers; // Array of tmpsession timers.	var $configIPBlockFile; // File of IPs to block, seperated by \n.	// Rogiers MySQL Wrapper Variables --------	var $host;	var $user;	var $pass;	var $db;	var $conn;	// -----------------------------------------	/* 	Constructor	Page(); Sets variables, uses sessions as auth.	Page(PAGE_SESSIONS); Sets variables, uses sessions as authorization.	Page(PAGE_COOKIES); Sets variables, uses cookies as authorization.	Page(PAGE_NOAUTH); Sets variables, no authorization.	*/	function Page($inputAuthorizationMethod = PAGE_SESSIONS)	{		$this->pageURL = $_SERVER["PHP_SELF"];		$this->pageURLex = __FILE__;		$this->serverName = $_SERVER["SERVER_NAME"];		$this->serverSoftware = $_SERVER["SERVER_SOFTWARE"];		$this->serverProtocol = $_SERVER["SERVER_PROTOCOL"];		$this->pageReferer = $_SERVER["HTTP_REFERER"];		$this->userAgent = $_SERVER["HTTP_USER_AGENT"];		$this->userIP = $_SERVER["REMOTE_ADDR"];		$this->configAuthMethod = $inputAuthorizationMethod;	}	function null()	{		return NULL;	}	/*	Set user information	setUserInfo();	*/	function setUserInfo()	{		if ($inputAuthorizationMethod == PAGE_SESSIONS)		{			if (isset($_SESSION[$this->configSessionNames["Username"]]) && isset($_SESSION[$this->configSessionNames["Password"]])) {				$userInformationQuery = $this->query("SELECT * FROM btxsys_users WHERE username=" . $this->prepval($_SESSION[$this->configSessionNames["Username"]]) . " AND password=" . $this->prepval($_SESSION[$this->configSessionNames["Password"]]) . " AND userID = " . $this->prepval($_SESSION[$this->configSessionNames["ID"]]));				$this->userInfo = $this->fetch_assoc($userInformationQuery);			} else {				$this->userInfo = false;			}		} elseif ($inputAuthorizationMethod == PAGE_COOKIES)		{			if (isset($_COOKIE[$this->configSessionNames["Username"]]) && isset($_COOKIE[$this->configSessionNames["Password"]])) {				$userInformationQuery = $this->query("SELECT * FROM btxsys_users WHERE username=" . $this->prepval($_COOKIE[$this->configSessionNames["Username"]]) . " AND password=" . $this->prepval($_COOKIE[$this->configSessionNames["Password"]]) . " AND userID = " . $this->prepval($_COOKIE[$this->configSessionNames["ID"]]));				$this->userInfo = $this->fetch_assoc($userInformationQuery);			} else {				$this->userInfo = false;			}		}	}	/*	Login a user.	THIS MUST be called before auth(),	otherwise any user can login. Example...	(user just sent sign-in form)	...	login("username", "password");	auth(PAGE_USERS, "forbidden.php");	...	if (user(USERNAME) == "Guest")	{		print("Sorry, but your login information did not match our records.");	}	*/	function login($inputUsername, $inputPassword)	{		if ($this->configAuthMethod == PAGE_SESSIONS)		{			$_SESSION[$this->configSessionNames["Username"]] = $inputUsername;			$_SESSION[$this->configSessionNames["Password"]] = $inputPassword;		} elseif ($this->configAuthMethod == PAGE_COOKIES)		{			setcookie($this->configSessionNames["Username"], $inputUsername);			setcookie($this->configSessionNames["Password"], $inputPassword);		}	}	/*	Get User information	user(USERNAME);	user(PASSWORD);	user(USERID);		TODO: ADD TO THE USER_ DEFINES AS btxsys_Users GROWS!!!!!!	*/	function user($inputInformationRequested)	{		if ($this->userInfo == false) return "Guest";		return $this->userInfo[$inputInformationRequested];	}	/*	PROBLEM AREA !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!	Authorization - Select who can view the page,	then try and auth the user. If the user is	not logged in, or there is no auth, the user	will be concidered a guest. The last parameter	is a filename to direct the unauthed users to.	auth(PAGE_GUEST, "forbidden.php");	auth(PAGE_USER, "forbidden.php");	auth(PAGE_ADMINISTRATION, "forbidden.php");	auth(PAGE_DEVELOPER, "forbidden.php");	*/	function auth($inputLevelAllowed, $inputRedirectFilename)	{		if ($this->configAuthMethod == PAGE_NOAUTH)		{			$this->userLevel = PAGE_GUEST;		}		if ($this->configAuthMethod == PAGE_SESSIONS)		{			if (!isset($_SESSION[$this->configSessionNames["Username"]]) || !isset($_SESSION[$this->configSessionNames["Password"]]))			{				$this->userLevel = PAGE_GUEST;			} elseif (isset($_SESSION[$this->configSessionNames["Username"]]) && isset($_SESSION[$this->configSessionNames["Password"]])) {				$userAuthorizationQuery = $this->query("SELECT * FROM btxsys_users WHERE username=" . $this->prepval($_SESSION[$this->configSessionNames["Username"]]) . " AND password=" . $this->prepval($_SESSION[$this->configSessionNames["Password"]]));				if (mysql_num_rows($userAuthorizationQuery) == 0)				{					$this->userLevel = PAGE_GUEST;					session_unset($_SESSION[$this->configSessionNames["Username"]]);					session_unset($_SESSION[$this->configSessionNames["Password"]]);				} elseif (mysql_num_rows($userAuthorizationQuery) == 1) {					$userAuthorizationAssoc = $this->fetch_assoc($userAuthorizationQuery);					$this->userLevel = $userAuthorizationAssoc["userLevel"];				}			}		} elseif ($this->configAuthMethod == PAGE_COOKIES)		{			if (!isset($_COOKIE[$this->configSessionNames["Username"]]) || !isset($_COOKIE[$this->configSessionNames["Password"]]))			{				$this->userLevel = PAGE_GUEST;			} elseif (isset($_COOKIE[$this->configSessionNames["Username"]]) && isset($_COOKIE[$this->configSessionNames["Password"]]))			{				$userAuthorizationQuery = $this->query("SELECT * FROM btxsys_users WHERE username=" . $this->prepval($_COOKIE[$this->configSessionNames["Username"]]) . " AND password=" . $this->prepval($_COOKIE[$this->configSessionNames["Password"]]));				if (mysql_num_rows($userAuthorizationQuery) == 0)				{					$this->userLevel = PAGE_GUEST;					setcookie($_COOKIE[$this->configSessionNames["Username"]], false);					setcookie($_COOKIE[$this->configSessionNames["Password"]], false);				} elseif (mysql_num_rows($userAuthorizationQuery) == 1) {					$userAuthorizationAssoc = $this->fetch_assoc($userAuthorizationQuery);					$this->userLevel = $userAuthorizationAssoc["userLevel"];				}			}		}		if ($this->userLevel < $inputLevelAllowed)		{			header("location: " . $inputRedirectFilename);			exit();		}	}	/*	Banlist - Denys access to users specified in the	banlist file. IPs in the banlist file should be	seperated with \n.	banlist("mybanlist.txt");	Returns false if file cannot be opened.	*/	function banlist($inputBanlistFilename)	{		$banlistFileHandle = fopen($inputBanlistFilename, "r");		if (!$banlistFileHandle) return false;		$banlistFileContents = stream_get_contents($banlistFileHandle);		$banlistIPs = explode("\n", $banlistFileContents);		$banlistIPCount = count($banlistIPs);		$banlistTempInt = 0;		while ($banlistTempInt != $banlistIPCount+1)		{			if ($banlistIPs[$banlistTempInt] == $this->userIP)			{				header("HTTP/1.0 403 Forbidden");				exit();				return;			}			$banlistTempInt++;		}		fclose($banlistFileHandle);	}	/*	Setup a new session OR cookie (depends on auth method selected) 	for long-term use. Does not need to be inserted 	into configSessionNames, since there is no need for an alias.	Overwrites previous session values. IF SETTING COOKIES,	they must be set BEFORE ANY OUTPUT.	session("mysession", "value");	session("mysession", false);	session("mysession", 1.2);	Value is false by default.	Returns false if session is set.	Returns true on success.	*/	function session($inputSessionName, $inputSessionValue = false)	{		if ($this->configAuthMethod == PAGE_SESSIONS) 		{			$_SESSION[$inputSessionName] = $inputSessionValue;			if ($_SESSION[$inputSessionName] != $inputSessionValue) return false;			return true;		} elseif ($this->configAuthMethod == PAGE_COOKIES)		{			setcookie($inputSessionName, $inputSessionValue);			if ($_COOKIE[$inputSessionName] != $inputSessionValue) return false;			return true;		}		return false;	}	/*	Get custom session value, must have been set.	This is more of an alias function.	getsession("mysession");	Returns session data on success.	Returns NULL if session was not set.	getsession("mysession"); Returns value.	*/	function getsession($inputSessionName)	{		if ($this->configAuthMethod == PAGE_SESSIONS)		{			if (!isset($_SESSION[$inputSessionName])) return $this->null();			return $_SESSION[$inputSessionName];		} elseif ($this->configAuthMethod == PAGE_COOKIES)		{			if (!isset($_COOKIE[$inputSessionName])) return $this->null();			return $_COOKIE[$inputSessionName];		}		return false;	}	/*	Delete a session.	This will not allow you to unset Page sessions	defined in $configSessionNames, returns false in this	instance.	endsession("mysession"); Returns true.	endsession("sessionUsername"); Returns false and does not unset (its in $configSessionNames)	*/	function endsession($inputSessionName)	{		if ($inputSessionName == $this->configSessionNames["ID"] || $inputSessionName == $this->configSessionNames["Username"] || $inputSessionName == $this->configSessionNames["Password"]) return false;				if ($this->configAuthMethod == PAGE_SESSIONS)		{			session_unset($inputSessionName);		} elseif ($this->configAuthMethod == PAGE_COOKIES)		{			setcookie($_COOKIE[$inputSessionName], false); // Not sure if this is right...		}		return true;	}		/*	Setup a new temporary session for short-term use.	This sets a session, and update() deletes it depending on how many minuites it is set to last.	tmpsession("mysession", "value", 1); // Set mysession to value for 1 MINUITE	tmpsession("mysession", "value", PAGE_RELOAD); // Set mysession to value until PAGE IS RELOADED	FIXME: I really don't feel like messing with this at the moment.	PROBLEM: Do not know if I can overwrite key values.	PROBLEM: Relies on calling an update() function.	PROBLEM: Requires a page reload regardless (see above problem).	function tmpsession($inputSessionName, $inputSessionValue = false, $inputTimeToDeletion = PAGE_RELOAD)	{		$timeToDeletion = time()+$inputTimeToDeletion*60;		array_push($configSessionNames, $inputSessionName => $inputSessionValue);		array_push($configSessionTimers, $inputSessionName => $timeToDeletion);		$_SESSION[$inputSessionName] = $inputSessionValue;	}	*/	/*******************************************************************	Most of the following database functions are by Rogier Pennink	some may have been slightly modified, or extended by me.	*******************************************************************/		/** The database Connection */	function database( $host = "", $user = "", $pass = "", $db = "" )	{		$this->host = $host;		$this->user = $user;		$this->pass = $pass;		$this->db = $db;	}	/** The connect function */	function connect()	{		$this->conn = mysql_connect( $this->host, $this->user, $this->pass );		/* check connection */		if ( mysql_errno() ) 		{			return false;		}		mysql_select_db( $this->db, $this->conn );		if ( mysql_errno() )		{			return false;		}			return true;	}	/**	 * The quoteSmart function with a slightly shorter name to not mess up scripts so much	 */	function prepval( $value )	{		if ( get_magic_quotes_gpc() )		// Strip slashes if magic quotes is on		{			$value = stripslashes( $value );		}		if ( !is_numeric( $value ) )		// Add mysql's slashes if not numeric		{			$value = "'" . mysql_real_escape_string( $value ) . "'";		}				return $value;	}		/** The query function */	function query( $sql )	{		return $sql;	}	/** The fetch_assoc function */	function fetch_assoc( $resource )	{		return mysql_fetch_assoc( $resource );	}	/** The fetch_array function */	function fetch_array( $resource )	{		return mysql_fetch_array( $resource );	}	/** The getRowCount function */	function getRowCount( $resource )	{		return mysql_num_rows( $resource );	}	/** The disconnected function */	function disconnect()	{		mysql_close( $this->conn );				/* check for errors */		if ( mysql_errno() ) 		{			 return false;		}		return true;	}	/**	* mysqlInfo returns version and debug information about the MySQL server. You can specify	* to return a formated version with a delimiter of choice (optional). If you don't specify	* the delimiter it will return an array of MySQL information.	* Order of information (array):	*	0: Client Library Version	*	1: MySQL Connection Method	*	2: Protocol	*	3: MySQL Version	*	4: Ping Response	*	5: Uptime	*	6: Threads	*	7: Questions	*	8: Slow Queries	*	9: Opens	*	10: Flush Tables	*	11: Open Tables	*	12: QPS (Average)	*	13: Thread ID	*	14: Client Encoding	* @param string Optional delimiter to append, leave empty to return an array.	* @return Array if a delimiter was not provided, otherwise returns a string.	* @author Aaron Amann	*/	function mysqlInfo( $string = "" )	{		$mysqlInfo_LibVer = mysql_get_client_info();		$mysqlInfo_ConMethod = mysql_get_host_info();		$mysqlInfo_Protocol = mysql_get_proto_info();		$mysqlInfo_Version = mysql_get_server_info();		if ( mysql_ping() )		{			$mysqlInfo_PingResponse = true;		} else {			$mysqlInfo_PingResponse = false;		}		$mstat = mysql_stat();		$mysqlInfo_Uptime = $mstat[0];		$mysqlInfo_Threads = $mstat[1];		$mysqlInfo_Questions = $mstat[2];		$mysqlInfo_SlowQs = $mstat[3];		$mysqlInfo_Opens = $mstat[4];		$mysqlInfo_Flushed = $mstat[5];		$mysqlInfo_Opened = $mstat[6];		$mysqlInfo_QPS = $mstat[7];		$mysqlInfo_ThreadID = mysql_thread_id();		$mysqlInfo_Encode = mysql_client_encoding();		if ( strlen( $string ) == 0 )		{			return array($mysqlInfo_LibVer, $mysqlInfo_ConMethod, $mysqlInfo_Protocol, $mysqlInfo_Version, $mysqlInfo_PingResponse, $mysqlInfo_Uptime, $mysqlInfo_Threads, $mysqlInfo_Questions, $mysqlInfo_SlowQs, $mysqlInfo_Opens, $mysqlInfo_Flushed, $mysqlInfo_Opened, $mysqlInfo_QPS, $mysqlInfo_ThreadID, $mysqlInfo_Encode);		} else {			return "Client Library Version: " . $mysqlInfo_LibVer . $string . "Connection Method: " . $mysqlInfo_ConMethod . $string . "Protocol: " . $mysqlInfo_Protocol . $string . "Version: " . $mysqlInfo_Version . $string . "Ping Response: " . $mysqlInfo_PingResponse . $string . "Uptime: " . $mysqlInfo_Uptime . $string . "Threads: " . $mysqlInfo_Threads . $string . "Questions: " . $mysqlInfo_Questions . $string . "Slow Queries: " . $mysqlInfo_SlowQs . $string . "Opens: " . $mysqlInfo_Opens . $string . "Flush Tables: " . $mysqlInfo_Flushed . $string . "Queries Per Second: " . $mysqlInfo_QPS . $string . "Thread ID: " . $mysqlInfo_ThreadID . $string . "Client Encoding: " . $mysqlInfo_Encode;		}	}}?>


16kb source bomb :)
But you are not doing any query. You just return the query that is passed to the function.

Change this
// $page->query()
function query( $sql )
{
return $sql;
}

to

// $page->query()
function query( $sql )
{
return mysql_query($sql);
}

And I'll think it will work, because then you get a result back.

And the variable names would not change anything, correct. But I think it is important to name your variables to what they are containing. There is a big difference between a variable containing a query string and a variable that is containing a sql result set.

Wow... I cannot believe I missed that :|, it was right in front of me... just wow. Well thanks, a ton, obviously it works now. :)
No problem, nice to be to any help :)

This topic is closed to new replies.

Advertisement