Jump to content

mysqli code from a book


TreColl

Recommended Posts

I know very basic PHP and am now trying to use MySQL with it....

 

Ok, so im trying to create a new script using a book I was bought.

This script requires a user to authenticate themselves...

 

I have replicated what the book says, but it doesn't seem to work...

 

 

This is where the login form directs too:

session_start();


//create short variable names
$username = $_POST['username'];
$password = $_POST['passwd'];

if ($username && $password)
//they have just tried logging in
{
	try
	{
		login($username, $password);
		//if they are in the database register the user id
		$_SESSION['valid_user'] = $username;
	}
	catch(Exception $e)
	{
		//unsuccessful login
		do_html_header('Problem: ');
		echo 'You could not be logged in.<br />
			You must be logged in to view this page. ';
		do_html_url('login.php', 'Click here to return to login page');
		do_html_footer();
		exit;
	}
}

do_html_header('Profile');
check_valid_user();

do_html_profile($username);

do_html_footer();

 

My issue appears to be with the login() function... which is....

function login($username, $password)
// check username and password with db
// if yes, return true
// else throw exception
{
  // connect to db
  $conn = db_connect();

  // check if username is unique
  
  $result = $conn->query("select * from `user` where `username`='$username' and `password` = 'sha1('password')'");

  if (!$result)
     throw new Exception('Could not log you in.');
  
  if ($result->num_rows>0)
     return true;
  else 
     throw new Exception('Could not log you in.');
}

 

And that uses the db_connect() function...

function db_connect()
{
$result = new mysqli('localhost', 'root', '', 'users');
if(!$result)
throw new Exception('Could not connect to database');
else
return $result;

}

 

Note: I using root with no pass for mysql as i am just doing this on my (offline) testing server, there is no important information in the db.

 

Whenever I log in. I get a message saying that I wasn't, it failed.... (No MySQL error, but I can remove an exception and get it to say that I weren't logged in to db!?)

Link to comment
Share on other sites

Okay, so I changed the login function to this...

 

function login($username, $password)
// check username and password with db
// if yes, return true
// else throw exception
{
  // connect to db
  $conn = db_connect();

  // check if username is unique
  
  $result = $conn->query("select * from `user` where `username`='$username' AND `password` = 'sha1('password')'");

  if (!$result)
     throw new Exception('Could not log you in.');

  
  if ($result->num_rows>0)
     return true;
  else 
  		echo mysql_error();
     //throw new Exception('Could not log you in.');
}

 

And straight away my ouput was...

 

Logged in as trecoll.

Warning: mysql_query() [function.mysql-query]: Access denied for user 'ODBC'@'localhost' (using password: NO) in C:\Users\Rob\Documents\www\users\fns\forum_output_fns.php on line 204

 

Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in C:\Users\Rob\Documents\www\users\fns\forum_output_fns.php on line 204

select * from `user` WHERE `username` ='trecoll'

Error: Access denied for user 'ODBC'@'localhost' (using password: NO)

 

You'll probably notice that its dropping the password off the end of the query too??

Link to comment
Share on other sites

1) You need to use the correct user credentials...

 

2) I made a MySQLException class that seems to work for me.  It could help you too.

<?php
class MySQLiException extends Exception
{

    public function __construct($message, $code = 0) {

        parent::__construct($message, $code);
    }


    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }

    public function MySQLiError($live = FALSE) {
       $msg = parent::getMessage() . "\n<br />\n";
if ($live != TRUE) {
	$msg .= mysqli_error() . "\n<br />\nOccured on line: " . parent::getLine();
}
return $msg;
    }
    public static function throwMySQLi($msg, $code = 0) {
       throw new MySQLiException($msg, $code);
    }
}
?>

 

Usage:

require 'MySQLiException.class.php';

try {

$conn = mysqli_connect("blah", "blah", "blah") OR MySQLiException::throwMySQLi;

}

catch (MySQLiException $e) {

  echo $e->MySQLiError();

}

 

Although...you can just use MySQLi in OOP form, which is nicer.  I actually made this class for normal MySQL functions and just added 'i' for you to the function names, lol.

Link to comment
Share on other sites

1) You need to use the correct user credentials...

 

I am... They just dont seem to be used!?

 

2) I made a MySQLException class that seems to work for me.  It could help you too.

<?php
class MySQLiException extends Exception
{

    public function __construct($message, $code = 0) {

        parent::__construct($message, $code);
    }


    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }

    public function MySQLiError($live = FALSE) {
       $msg = parent::getMessage() . "\n<br />\n";
if ($live != TRUE) {
	$msg .= mysqli_error() . "\n<br />\nOccured on line: " . parent::getLine();
}
return $msg;
    }
    public static function throwMySQLi($msg, $code = 0) {
       throw new MySQLiException($msg, $code);
    }
}
?>

 

Usage:

require 'MySQLiException.class.php';

try {

$conn = mysqli_connect("blah", "blah", "blah") OR MySQLiException::throwMySQLi;

}

catch (MySQLiException $e) {

   echo $e->MySQLiError();

}

 

Although...you can just use MySQLi in OOP form, which is nicer.  I actually made this class for normal MySQL functions and just added 'i' for you to the function names, lol.

 

So I could just re-write my dbconnect() function to your usage example above and then create the class?? and then I could use it normally?? - I cant test this right now, am not on my testing server.. but will do when I get home...

Link to comment
Share on other sites

  • 2 weeks later...
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.