Solved

Connecting to Database from PHP Class

Posted on 2011-03-25
6
274 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
Comment Utility
What kind of an error do you get?
0
 

Author Comment

by:Kokko
Comment Utility
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
Comment Utility
maybe try double quotes like this
$this->db = new mysqli = new mysqli("localhost", "my_user", "my_password", "world");
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 

Author Comment

by:Kokko
Comment Utility
Number-1,

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

Expert Comment

by:global_expert_advice
Comment Utility
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
Comment Utility
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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

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.
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…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

743 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

16 Experts available now in Live!

Get 1:1 Help Now