PHP Code:
// this *should* be causing an error as well.
//$mysqli=new new mysqli('localhost', 'uname', 'pass', 'db');
// only use "new" once.
$mysqli = new mysqli( 'localhost','uname','pass','db' );
Assuming your connection script is running before you use the functions, I don't see why you'd be having any problems...
can you post the complete error (do print $mysqli->error;) and the complete code of the function?
-----------------------edit-----------------------
Also, while what you're doing should "work" just fine, it's doing so in a clumsy way and not really taking advantage of object-oriented programming. For example, you might organize it something like this (and please, feel free to ignore me if you'd rather focus on "getting it to work" first):
PHP Code:
<?php
class myDB{
// your database credentials
const DBhost = 'localhost';
const username = 'uname';
const password = 'pass';
const DBname = 'db';
private $connection; // holds your mysqli connection
private $statements; // holds your prepared statement objects
public function __construct(){
try{
// connect to database
if( ($this->connection = new mysqli( self::DBhost,self::username,self::password,self::DBname )) === false ){
throw new Exception( 'Could not connect to database.' );
}
}catch( Exception $e ){
// bad error handling. don't do it this way in RL :)
exit( $e->getMessage() );
}
}
public function getUser( $param ){
try{
// prepare statement if not already done
if( empty( $this->statements[__METHOD__] ) ){
if( ($this->statements[__METHOD__] = $this->connection->prepare( "MY ? STATEMENT" )) === false ){
throw new Exception( 'Failed to prepare statement: '.$this->connection->error );
}
}
// bind input param
if( ($this->statements[__METHOD__]->bind_param( 's',$param )) === false ){
throw new Exception( 'Failed to bind param: '.$this->connection->error );
}
// execute statement
if( ($this->statements[__METHOD__]->execute()) === false ){
throw new Exception( 'Failed to execute statement: '.$this->connection->error );
}
// bind result
if( ($this->statements[__METHOD__]->bind_result( $result )) === false ){
throw new Exception( 'Failed to bind results: '.$this->connection->error );
}
// fetch result
if( $this->statements[__METHOD__]->fetch() === false ){
throw new Exception( 'Failed to fetch results: '.$this->connection->error );
}
// return result
return $result;
}catch( Exception $e ){
exit( $e->getMessage() );
}
}
}
this could be abstracted even more; for example, you could have a single method that prepared/executed any of your statements, and you would specify the statement in the args. but look at this first.
Bookmarks