Solved

Connecting to Database from PHP Class

Posted on 2011-03-25
6
277 Views
Last Modified: 2012-05-11
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!
0
Comment
Question by:Kokko
6 Comments
 
LVL 8

Expert Comment

by:Rik-Legger
ID: 35218658
What kind of an error do you get?
0
 

Author Comment

by:Kokko
ID: 35218670
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');
0
 
LVL 29

Expert Comment

by:Randy Downs
ID: 35218751
maybe try double quotes like this
$this->db = new mysqli = new mysqli("localhost", "my_user", "my_password", "world");
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

Author Comment

by:Kokko
ID: 35218783
Number-1,

Thank you, but that doesn't seem to be it.
0
 
LVL 1

Expert Comment

by:global_expert_advice
ID: 35218942
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

0
 
LVL 1

Accepted Solution

by:
global_expert_advice earned 500 total points
ID: 35218958
If you want you can use the full class file which i use:

<?php

class Database 
{
	private $server   = ""; //database server
	private $user     = ""; //database login name
	private $pass     = ""; //database login password
	private $database = ""; //database name
	private $query_id=0;
	private $link_id = 0;
	public $affected_rows = 0;
	
	# desc: constructor ( Connection )
	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.");
		}
	}
	
	# Check Sql Query
	function query($sql) 
	{
		$this->query_id = mysql_query($sql);
		
		if (!$this->query_id)
		{
			$this->oops("<b>MySQL Query fail:</b> $sql");
		}
		$this->affected_rows = mysql_affected_rows();
		return $this->query_id;
				
	}
	
	# For Select Query	
	function query_select($sql)
	{
		$this->query_id=mysql_query($sql);
		if(!$this->query_id)
		{
			$this->oops("<b>MySQL Query fail:</b> $sql");
		}
		$this->affected_rows = mysql_affected_rows();
	}
	
	# Fetch Recoreds
    function fetch_record()
	{
		return mysql_fetch_array($this->query_id);
	} 
	
	# Insert Query
	function query_insert($table, $data) 
	{
		$q="INSERT INTO ".$table;
		$FieldsValue='';
		$FieldName='';
		
		foreach($data as $key=>$val)
		{
			$FieldName.=$key.", ";
			$FieldsValue.="'".$val."', ";
		}
		
		$query_str = $q. "(". rtrim($FieldName, ', ') .") VALUES (". rtrim($FieldsValue, ', ') .");";
		$this->query($query_str);
	}
	
	# Update Query
	function query_update($table, $data, $where)
	{
		$q="UPDATE ".$table." SET ";
		
		foreach($data as $key=>$val)
		{
			 $q.=$key."= '". $val. "', ";
		}
		
		 $query_str= rtrim($q, ', ') . ' WHERE '.$where;
		 $this->query($query_str);
	}
	
	# Delete Query
	function query_delete($table,$where) 
	{
		$query_str="delete from ".$table." where ".$where;
		$this->query_id = mysql_query($query_str);
		
		if (!$this->query_id)
		{
			$this->oops("<b>MySQL Query fail:</b> $sql");
		}
		$this->affected_rows = mysql_affected_rows();
		
	}
	function file_Extension($FileName)
	{
  	  $pathInfo = pathinfo($FileName);
  	  return $pathInfo['extension'];
	}
?>

Open in new window

0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

861 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

25 Experts available now in Live!

Get 1:1 Help Now