Link to home
Start Free TrialLog in
Avatar of Kokko
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!
Avatar of Rik-Legger
Rik-Legger
Flag of undefined image

What kind of an error do you get?
Avatar of Kokko
Kokko

ASKER

Parse error: syntax error, unexpected T_VARIABLE, expecting T_FUNCTION in /Applications/XAMPP/xamppfiles/htdocs/memberAccount.inc on line 48

And line 48 is where I have
 $this->db = new mysqli('localhost', 'root', '', 'abcd');
Avatar of Randy Downs
maybe try double quotes like this
$this->db = new mysqli = new mysqli("localhost", "my_user", "my_password", "world");
Avatar of Kokko

ASKER

Number-1,

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.");
		}
	}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of global_expert_advice
global_expert_advice
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial