Solved

Connecting to Database from PHP Class

Posted on 2011-03-25
6
281 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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

Styling your websites can become very complex. Here I'll show how SASS can help you better organize, maintain and reuse your CSS code.
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

773 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