Page 1 of 1

connection class issue

Posted: Thu Nov 19, 2015 10:00 pm
by cybershot
I have a test database called Gas with one table called stats. I am trying to
I have a class to connect to a database like so

Code: Select all

class database {
       function connect(){
		$server = "private";
		$db_user = "private"; // Enter your username
		$db_pass = "private"; // Enter your password
		$db_name = "private"; // Enter your database name
	
		$mysqli = new MySQLi($server, $db_user, $db_pass, $db_name);
		
		if($mysqli->connect_errno){
			echo "Failed to connect to database: (" . $mysqli->connect_errno . ")" . $mysqli->connect_error;
		}
	}

    public function select($table, $rows = '*', $where = null, $order = null){   
	$q = 'SELECT '.$rows.' FROM '.$table;
        if($where != null)
            $q .= ' WHERE '.$where;
        if($order != null)
            $q .= ' ORDER BY '.$order;
       
	 (47)  $query = mysqli_query($q);
	var_dump($q);
}

$mysqli = new database;
The var dump above gives me this
string 'SELECT * FROM stats'

but I am getting this error message on the index, I have marked the error line above with a (47)
Warning: mysqli_query() expects at least 2 parameters, 1 given

in my index file, I did this

Code: Select all

	$conn = $mysqli->connect();
	if($conn){
		echo "Connected";
	} else {
		echo "no connection";
	}
	$mysqli->select('stats','*');
?>

I am getting the error "No connection". I don't understand why it's not connecting.

Re: connection class issue

Posted: Fri Nov 20, 2015 7:00 am
by Celauran
Warning: mysqli_query() expects at least 2 parameters, 1 given
http://php.net/manual/en/mysqli.query.php

You need to either pass the connection in to the function, or you need to call the method on the mysqli object.
I am getting the error "No connection". I don't understand why it's not connecting.
Is $mysqli an instance of your database class? Your connect method doesn't return anything.

Re: connection class issue

Posted: Fri Nov 20, 2015 3:56 pm
by Christopher
Besides all the little problems in your code, you need to maintain the MySQLi object within your class:

Code: Select all

class database
{
       protected $mysqli;
       protected $errmsg = '';

        function connect()
	{
		$server = "private";
		$db_user = "private"; // Enter your username
		$db_pass = "private"; // Enter your password
		$db_name = "private"; // Enter your database name
	
		$this->mysqli = new MySQLi($server, $db_user, $db_pass, $db_name);
		
		if($this->mysqli->connect_errno){
			$this->errmsg = "Failed to connect to database: (" . $this->mysqli->connect_errno . ")" . $this->mysqli->connect_error;
		}
		return $this->errmsg == '';
	}

	public function select($table, $rows = '*', $where = null, $order = null)
	{   
		$q = 'SELECT '.$rows.' FROM '.$table;
		if($where != null) {
			$q .= ' WHERE '.$where;
		}
		if($order != null) {
			$q .= ' ORDER BY '.$order;
       		}
		$query = $this->mysqli->query($q);
		var_dump($q);
	}
}
$mysqli = new database();
$conn = $mysqli->connect();
if ($conn) {
	echo "Connected";
} else {
	echo "No connection";
}
$mysqli->select('stats','*');

Re: connection class issue

Posted: Fri Nov 20, 2015 8:56 pm
by cybershot
@Celauran
Thanks for the info. I see now that I needed to return the connection.


@Christopher
I know there are probably lots of issues with my code. I am learning this for the first time. Trying to piece it together using tutorials. One of the issues I have seen is that a lot of the tutorials out there are out of date and use deprecated functions. I was trying to keep the class as simple as possible. Thanks for the assistance

Re: connection class issue

Posted: Sat Nov 21, 2015 10:20 am
by Christopher
cybershot wrote: I know there are probably lots of issues with my code. I am learning this for the first time. Trying to piece it together using tutorials. One of the issues I have seen is that a lot of the tutorials out there are out of date and use deprecated functions. I was trying to keep the class as simple as possible. Thanks for the assistance
If you want to walk through creating some of these basic classes, just start a thread and let us know what your goal is (e.g., a database connection class). We can discuss the design issues and build the code in a structured way.

Re: connection class issue

Posted: Sat Nov 21, 2015 12:24 pm
by cybershot
This is my goal.

I have 16 receipts from gas stations that I have collected over the last several months. I wrote the mileage on them as well. So I thought it would be a great project to learn how to create a database class by logging these receipts. So I created a database on localhost called Gas and a table called stats. I figured this table would consist of these items

ID - Primary key
miles - the miles at time of fill up
amount - how much the gas cost
gallons - how many gallons
date - the date of purchase

I figured this database could teach me many things.

1. I would need to use code to organize all the receipts. I don't want to sit here and try to figure out each date of purchase. I want to just put them in and let the code organize by date
2. I would be able to do math on the gallons to figure out my mileage
3. I could do math on the amount to figure out my total cost of driving my car
4. I could do math on the date to see how many days of driving I get between fill ups

I am considering buying a new truck. I think knowing how much It cost me to drive my car around would really help when deciding if going from a car that should be getting about 26 miles to the gallon is worth trading to a truck that gets about 19. My car is a 2001 so I figure I have lost some mileage and the gap wouldn't be that bad. Of course I could just use a simple spreadsheet but then I wouldn't learn anything about databases and classes. This is an actual real world example that can be used by anyone

Creating the database in phpmyadmin isn't that hard but creating a class that connects in an OOP way is proving a little more difficult. I understand some of the principals but I ran into trouble trying to figure out the difference between

mysqli_connect
mysqli_query
$conn = new MySqli

For example, I put the name of the database in the some of them but for some reason my code told me that no database was selected. This didn't make sense.

For me, I see many different ways to make a class. There are the easy ways and there are the more difficult ways. The more difficult ways include advanced php programming skills. If that makes sense.

Like you could easily use a procedural method of connecting and working with the database and then take it one step up by creating a class and then you could go one step further by making your class use more advanced techniques. So my final goal would be

Code: Select all

class Database
{
    public function connect()   {   }
    public function disconnect()    {   }
    public function select()        {   }
    public function insert()        {   }
    public function delete()        {   }
    public function update()    {   }
}
Then I want to make a front end way of entering the information. So that is what I am up to.

Re: connection class issue

Posted: Sun Nov 22, 2015 8:54 am
by Celauran
A few thoughts on the subject. First, unless you're really attached to mysqli, I'd choose PDO. I find bound parameters/values to be implemented far more sensibly and require less code in PDO. That said, either MySQLi or PDO have OO interfaces to connect to the database. You don't need to handle that. Rather, it sounds like you want a wrapper around some of the functionality they expose. You don't want your credentials hardcoded into the class itself. Pass them in as constructor arguments instead. If they change or if you need to connect to a second database as well, you don't need to modify your class. Secondly, if we're working with constructors anyway, it's better to pass the dependency in as a constructor argument rather than create the dependent object directly inside your class. Makes it somewhat more flexible.

Contrived, incomplete example:

Code: Select all

class FuelUsage
{
    protected $db;

    public function __construct(PDO $pdo)
    {
        $this->db = $pdo;
    }

    public function storeReceipt($date, $cost, $volume) {
        // do stuff
    }

    public function retrieveReceipts() {}

    // etc.
}

$pdo = new PDO('credentials_go_here');
$fuel = new FuelUsage($pdo);

$fuel->storeReceipt('2015-11-21', 20.00, 45);
Hope that makes sense.