Solved

Connecting to Database from PHP Class

Posted on 2011-03-25
6
290 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 30

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
Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

 

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

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

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

Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
The Windows functions GetTickCount and timeGetTime retrieve the number of milliseconds since the system was started. However, the value is stored in a DWORD, which means that it wraps around to zero every 49.7 days. This article shows how to solve t…
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)
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

717 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