Kokko
asked on
Connecting to Database from PHP Class
Hi Experts,
I'm using a class to insert new data to database, but it's not working.
public $db;
//This is the line that gives me an error
$this->db = new mysqli('localhost', 'root', '', 'abcd');
if(mysqli_connect_errno())
{
echo 'Error: Connection to database failed: '.mysqli_connect_error();
exit;
}
//Querying AllCustomer Table
public $query;
$this->query = 'INSERT INTO AllCustomers (UserName, UserPass, EmailAddress)
VALUES
('".$this->usernameClass." ',
'".$this->userpassClass."' ,
'"$this->useremailClass."' )';
$this->result = $db->query($this->query);
if($this->result)
{
echo $this->db->affected_rows.' was updated.<br />';
}
else
{
echo 'An error has occurred. The update was not made.<br />';
}
$this->db->close();
Thank you in advance for your help!
I'm using a class to insert new data to database, but it's not working.
public $db;
//This is the line that gives me an error
$this->db = new mysqli('localhost', 'root', '', 'abcd');
if(mysqli_connect_errno())
{
echo 'Error: Connection to database failed: '.mysqli_connect_error();
exit;
}
//Querying AllCustomer Table
public $query;
$this->query = 'INSERT INTO AllCustomers (UserName, UserPass, EmailAddress)
VALUES
('".$this->usernameClass."
'".$this->userpassClass."'
'"$this->useremailClass."'
$this->result = $db->query($this->query);
if($this->result)
{
echo $this->db->affected_rows.'
}
else
{
echo 'An error has occurred. The update was not made.<br />';
}
$this->db->close();
Thank you in advance for your help!
What kind of an error do you get?
ASKER
Parse error: syntax error, unexpected T_VARIABLE, expecting T_FUNCTION in /Applications/XAMPP/xamppf iles/htdoc s/memberAc count.inc on line 48
And line 48 is where I have
$this->db = new mysqli('localhost', 'root', '', 'abcd');
And line 48 is where I have
$this->db = new mysqli('localhost', 'root', '', 'abcd');
maybe try double quotes like this
$this->db = new mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$this->db = new mysqli = new mysqli("localhost", "my_user", "my_password", "world");
ASKER
Number-1,
Thank you, but that doesn't seem to be it.
Thank you, but that doesn't seem to be it.
Try in this way:
function Database($server, $user, $pass, $database)
{
$this->server=$server;
$this->user=$user;
$this->pass=$pass;
$this->database=$database;
$this->link_id=mysql_connect($this->server,$this->user,$this->pass);
if (!$this->link_id)
{
//open failed
$this->oops("Could not connect to server: <b>$this->server</b>.");
}
if(!mysql_select_db($this->database, $this->link_id))
{
//no database
$this->oops("Could not open database: <b>$this->database</b>.");
}
}
# desc: close the connection
function close()
{
if(!mysql_close())
{
$this->oops("Connection close failed.");
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.