I just started to fool around with php5 and I am having a small difficulty retrieving information from a database. It works fine when I fetch a table with many records by using foreach loops.
But now I retrieve only one record and I don't really know the syntax for that. I tried many different ways but still have not found the answer.
the print_r($result) returned this:
MysqlImprovedResult Object ( [_current:protected] => [_key:protected] => [_valid:protected] => [_result:protected] => mysqli_result Object ( ) )
Help anyone??
Thanx
class DBConnect
{
private static $_HOST = "localhost";
private static $_USER = "user";
private static $_PASS = "pass";
private static $_DB = "db";
protected $_connection;
public function __construct()
{
$this->_connection = @new mysqli(self::$_HOST, self::$_USER, self::$_PASS, self::$_DB);
if (mysqli_connect_errno()) {
throw new RuntimeException('Cannot access database: '. mysqli_connect_error());
}
}
public function getResultSet($sql)
{
$results = new MysqlImprovedResult($sql, $this->_connection);
return $results;
}
public function __destruct()
{
$this->_connection->close();
}
}
class MysqlImprovedResult implements Iterator, Countable
{
protected $_current;
protected $_key;
protected $_valid;
protected $_result;
public function __construct($sql, $connection)
{
if (!$this->_result = $connection->query($sql)) {
throw new RuntimeException($connection->error . '. The actual query submitted was: ' . $sql);
}
}
public function rewind()
{
if (!is_null($this->_key)) {
$this->_result->data_seek(0);
}
$this->_key = 0;
$this->_current = $this->_result->fetch_assoc();
$this->_valid = is_null($this->_current) ? false : true;
}
public function valid()
{
return $this->_valid;
}
public function current()
{
return $this->_current;
}
public function key()
{
return $this->_key;
}
public function next()
{
$this->_current = $this->_result->fetch_assoc();
$this->_valid = is_null($this->_current) ? false : true;
$this->_key++;
}
public function count()
{
return $this->_result->num_rows;
}
}
function login($userid, $pass){
$hashed_pass = hash('sha1', $pass);
$query = 'SELECT user_id, fname, lname FROM users WHERE user_id='.$userid.' AND pass="'.$hashed_pass.'";';
try {
$conn = new DBConnect();
$result = $conn->getResultSet($query);
print_r($result);
//HOW TO RETRIEVE USER DATA
} catch (Exception $e) {
echo $e->getMessage();
}
}