im trying to understand oophp a litle bit but now im stuck in getting information out of my database. What am i doing wrong? After the tip off PDO I tried the following but also no results...
index.php
<?php
include('classes/database.class.php');
$db = new Database();
$db->connect();
$res = $db->select();
print_r($res);
?>
database.class.php
<?php
class Database {
private $db_host = 'localhost'; // Database Host
private $db_user = 'root'; // Gebruikersnaam
private $db_pass = 'root'; // Passwoord
private $db_name = 'quickscans'; // Database naam
public function connect()
{
try
{
$db = new PDO('mysql:host='.$this->db_host.';dbname='.$this->db_name,$this->db_user,$this->db_pass);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function disconnect()
{
$db = null;
}
public function select()
{
$sql = 'SELECT id FROM bedrijf';
$results = $db->query($sql);
foreach($results as $row)
{
echo $row['id'].'<br>';
}
}
}
?>
Maybe this code is a bit cleaner.. but still no results :(.
You aren't assigning any instance variables in this class.
The query method has no access to the connection you create because the object has no state.
Your constructor for the class should create the connection, and then queries can be called on this property.
class Database {
private $db_host = 'localhost'; // Database Host
private $db_user = 'root'; // Gebruikersnaam
private $db_pass = 'root'; // Passwoord
private $db_name = 'quickscans'; // Database naam
public function __construct(){
$this->connect();
}
public function connect()
{
try
{
$this->connection = new PDO('mysql:host='.$this->db_host.';dbname='.$this->db_name,$this->db_user,$this->db_pass);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function disconnect()
{
$this->connection = null;
}
public function select()
{
$sql = 'SELECT id FROM bedrijf';
$results = $this->connection->query($sql);
foreach($results as $row)
{
echo $row['id'].'<br>';
}
}
}
The $this keyword sets instance variables for the class, so the connection property becomes a PDO instance that other methods can act upon. Without this, the varibles created in the methods, in this case $db are just orphaned in the local function scope and not accessible in the greater class.
Utilizing this approach elminates the need to run connect() in the calling context. You don't need to use the constructor to do this if you don't want to, you'll just always need to connect first in order to create the connection property and have it available to the rest of the class. Also note you can name the property whatever you like, I just used connection because it made the most sense in the API.
Also, as commented, to make this a bit more usable you should have the select method return the query results array rather than having it output directly.
public function select()
{
$sql = 'SELECT id FROM bedrijf';
$results = $this->connection->query($sql);
if(!empty($results)){
return $results
}else{
return false;
}
}
Related
i'm updating from PHP5.6 to PHP7.0 and this doesn't work anymore:
$con=mysqli_connect(DATABASE_SERVER,DATABASE_USER,DATABASE_PASSWORD) or die(DATABASE_ERROR);
mysqli_select_db($con, DATABASE_NAME) or die(DATABASE_ERROR);
class DoSomeStuff()
{
function GetSomeDate()
{
$result=mysqli_query($con, "SELECT * FROM my_table");
}
}
Looks like the $con variable is not available inside the class.
Do i have to to something like this?
global $con=mysqli_connect()
Thanks!
The main pattern used is something like, pass database connection into constructor (dependency injection) and then store it in an instance variable ($this->con in this case). Then later database calls just use $this->con for the database connection...
$con=mysqli_connect(DATABASE_SERVER,DATABASE_USER,DATABASE_PASSWORD) or die(DATABASE_ERROR);
mysqli_select_db($con, DATABASE_NAME) or die(DATABASE_ERROR);
class DoSomeStuff
{
private $con;
// Create instance with connection
public function __construct( $con ) {
// Store connection in instance for later use
$this->con = $con;
}
public function doSomething() {
// Run query using stored database connection
$result=mysqli_query($this->con, "SELECT * FROM my_table");
}
}
// Create instance, passing in connection
$some = new DoSomeStuff ($con);
$some->doSomething();
heres something I've worked with recently
class Database {
private $_conn = null;
public function getConnection($password) {
if (!is_null($this->_conn)) {
return $this->_conn;
}
$this->_conn = false;
try {
$this->_conn = new PDO("mysql:host=localhost;dbname=databasename", 'root',
$password);
$this->_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
return $this->_conn;
}
}
function conOpen() {
$servername = "localhost";
$username = "root";
$password = "password";
$db = new Database();
$conn = $db->getConnection($password);
return $conn;
}
Then use it like this
$con = conOpen();
You can check out PDO connection here
I have a class with a connection to a database
$db = new db();
class db {
public $server = 'localhost';
public $user = '';
public $passwd = '******';
public $db = '';
public $dbCon;
function __construct() {
$this->dbCon = mysqli_connect($this->server, $this->user, $this->passwd, $this->db);
}
function __destruct() {
mysqli_close($this->dbCon);
}
}
Now i want to make an other class and using the connection like this:
class Categories (
function GetCategory($cat) {
$myQuery = "SELECT * FROM test GROUP BY $cat";
$results = mysqli_query($this->dbCon, $myQuery);
return $results;
}
)
How can i use the connection in a other class?
Can somebody help me out whit this?
Make the $dbCon in your db class a static variable, so you can access it from category's using db::$dbcon as the connection variable. You could also make a static function returning the static dbcon variable, usefull tot check if it is actually a link and not null.
This is just one solution of many possibilities, but probably the easiest to implement because it isn't likely you need more connections to a db, so a static is perfect for it.
A static is nothing more then a variable living in the namespace it is defined in, you don't need to initialize the class in order to access it. It's value is shared across all instances of the object, so creating multiple DB class instances allows you tot just return a static if it was set in a previous DB class instance.
class db{
static $link;
static function connect(){
if(self::$link = mysqli_connect(....)){
return self::$link;
} else {
die('could not connect to db');
}
}
static function getcon(){
return isset(self::$link) ? self::$link : self::connect();
}
}
class Categories{
function GetCategory($cat){
$myQuery = "SELECT * FROM test GROUP BY $cat";
return mysqli_query(db::getcon(), $myQuery);
}
}
Create an object of the db class in the categories class. Then use that object to query the db accordingly. Also make sure you use a static variable in the db class. SO that the connection variable is created once and will be used all along the application.
Your db class may look like this
class db {
public $server = 'localhost';
public $user = '';
public $passwd = '******';
public $db = '';
public static $dbCon;
function __construct() {
$this->dbCon = mysqli_connect($this->server, $this->user, $this->passwd, $this->db);
}
function __destruct() {
mysqli_close($this->dbCon);
}
}
Your categories class may look like this
class Categories {
$connection=db::$dbCon;
if(!$connection){
$db=new db();
$connection=db::$dbCon;
}
function GetCategory($cat) {
$myQuery = "SELECT * FROM test GROUP BY $cat";
$results = mysqli_query($this->connection, $myQuery);
return $results;
}
}
So, I'm in the middle of writing a web application for one of my clients, and I've decided to keep the database connection in a class. The following code is what I have:
class databaseConnection {
private $hostname = 'hn.app.dev';
private $username = 'root';
private $password = '';
private $database = 'hn_app_dev';
public function connect() {
$host = mysqli_connect($this->hostname, $this->username, $this->password);
if ($host) {
$connection = mysqli_select_db($host, $this->database);
if (!$connection) {
die('An error occured while trying to connect to the database.');
}
return $connection;
}
}
}
I am using the standard PHP function of mysqli_query to send queries to the database. I am using the following to send queries to the database:
function fetch_from_db($query) {
$connection = new databaseConnection();
$query = mysqli_query($connection->$connection, 'QUERY');
}
I'm new to using classes in my code. I'm still learning, as we all are. I've checked about but cannot find a fix for my issue. I know what the issue is: it's an issue with the class being an object, and something to do with fetching the returned $connection variable from it.
How can I fix this issue so that I can connect correctly to my database? Also, could anyone point me in the direction of some documentation that I could learn the fix so I can tackle this in future.
Thank you!
There are a lot of different ways you could write a object to handle connections and queries to the database.
What matters most is what your trying to achieve.
I would think these would be a few features you would like to have.
Single Connection
Runs SQL and returns mysqli results.
Access to the connection for escaping values.
It looks like you want to store your credentials within the object it self. ( I would suggest passing these in as a value in __construct()
These are a few basic features, that could easily be expanded apon.
class databaseConnection {
//private $hostname = 'hn.app.dev';
//private $username = 'root';
//private $password = '';
//private $database = 'hn_app_dev';
private $connection; // this is where the object will store the connection for other methods to access it
public function __construct($host, $username, $password, $database)
//public function connect() {
$this->connection = mysqli_connect($host, $username, $password);
if ($host) {
$this->connection->select_db($database);
if (!$this->connection) {
die('An error occured while trying to connect to the database.');
}
return $connection;
}
}
// this is so databaseConnection $db can access the connection for escaping MySQLi SQL
public function connection(){
return $this->connection;
}
function fetch_from_db($query) {
//$connection = new databaseConnection(); // I don't believe you really want to create a instance of this object inside of itself
//$query = mysqli_query($connection->$connection, 'QUERY');
$query = $this->connection->query($query); // we will use the object oriented style instead of the above procedural line
return $query; // return the results to the $results var in the bottom example
}
// this is a magic function that is called when the object is destroyed, so we will close the connection to avoid to many connections
function __destruct(){
$this->connection()->close();
}
}
// make a new datbaseConnection class with specific credentials
$db = new databaseConnection('localhost', 'someuser', 'somepass', 'somedb');
$sql = 'SELECT * FROM tableName LIMIT 100';
// call the fetch_from_db function from the new databaseConnection $db
$results = $db->fetch_from_db($sql);
// print the results
while($result = $results->fetch_assoc()){
print_r($result); // print_r on each row selected from db
}
You can learn more about OOP and PHP Objects in the Manual and there are many tutorials available online about specifically classes to manage database connections and queries.
http://php.net/manual/en/language.oop5.php
Hope this helps!
If you're going to keep it in a class, you never call the connect() function. But if you want it connected when you initiate the class, change the connect() function to __construct() and remove the return and assign it to a public variable.
class databaseConnection {
private $hostname = 'hn.app.dev';
private $username = 'root';
private $password = '';
private $database = 'hn_app_dev';
public $connection;
public function __construct() {
$host = mysqli_connect($this->hostname, $this->username, $this->password);
if ($host) {
$connection = mysqli_select_db($host, $this->database);
if (!$connection) {
die('An error occured while trying to connect to the database.');
}
$this->connection = $host;
}
}
}
After that, you can get the database connection in your function like:
function fetch_from_db($query) {
$connection = new databaseConnection();
$query = mysqli_query($connection->connection, 'QUERY');
}
Now, after having said all that, you don't want to create a new instance in every function to access the database. So possibly making it static and create an init() function of sorts so it takes less memory in the overall application.
For class documentation PHP's Classes/Objects page will help. Specifically the 'Examples' link.
<?php
class databaseConnection {
private $hostname = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'onlinylh_sggsfaculty';
public function connect() {
$host = mysqli_connect($this->hostname, $this->username, $this->password,$this->database);
if ($host) {
return $host;
}
else{
echo "Error";
}
}
}
function fetch_from_db($query) {
$conn = new databaseConnection();
$r = mysqli_query($conn->connect(), $query);
}
fetch_from_db()
?>
This Worked For me.
I'm trying to learn OOP programming in PHP. So far i got couple of basic things but i don't know how to echo my results into the page. I made up Database class and Category class i wanna echo the results from read function but i don't know how to do that. Can someone help me refactor this so i can use both classes?
This is my code
class Database {
private $_connection;
private $_host = "localhost";
private $_username = "root";
private $_password = "";
private $_database = "cmsi";
// Conect to database is private and can only be used by getConection function result is returned object of mysqli class
//can be seen in var_dump() function
private function conect() {
//$this refers to class Database and her functions and propertys are being acsessed via -> sign
$this->_connection = new mysqli($this->_host, $this->_username,
$this->_password, $this->_database);
// Error handling
if(mysqli_connect_error()) {
trigger_error("Failed to conencto to MySQL: " . mysql_connect_error(),
E_USER_ERROR);
}
return $this->_connection;
}
//Safest way to iniate conection
public function getConection(){
return $this -> conect();
}
}
class Category{
private $db_sql;
public function __construct($db){
$this->db_sql = $db;
}
public function read(){
$conection = $this->db_sql;
$query = "Select * from category";
$result = $conection -> query($query);
return $result;
}
}
$db = new Database();
$conection = $db->getConection();
$obj = new Category($conection);
$obj->read();
You're almost there. Just store the result set in a variable and loop through it, like this:
// your code
$db = new Database();
$conection = $db->getConection();
$obj = new Category($conection);
// store the result set
$result_set = $obj->read();
// loop through the result set
while($row = $result_set->fetch_array()){
// your code
}
Here I am sharing code of two functions. Both return an instance of a PDO object. But one of them works fine when a statement is inserted using the PDO connection where as other one does not. The same identical code is used in both cases to insert a record.
This is the function whose returned PDO object works with the insert statement.
public function getPDO() {
/** mysql hostname */
$hostName = 'localhost';
/** mysql database name */
$dbName = 'testDB';
/** db user name */
$userName = 'root';
/** db password */
$password = '';
try {
$str = "mysql:dbname=$dbName;host=$hostName";
$db = new PDO($str, $userName, $password );
return $db;
}catch(PDOException $e) {
echo "PDO connection failed. <br />";
echo $e->getMessage();
return null;
}
}
This is the function whose returned PDO object DOES NOT work with the insert statement. In this function the connection string and other connection parameters are read from static values defined in the class.
public function getPDO() {
try {
$connStr = "mysql:dbName=".self::$dbName.";host=".self::$hostName;
$db = new PDO($connStr, self::$userName, self::$password);
return $db;
}catch(PDOException $e) {
echo "PDO connection failed. <br />";
echo $e->getMessage();
return null;
}
}
Here is how the static variables are defined:
/** mysql hostname */
static $hostName = "localhost";
/** mysql database name */
static $dbName = "testDB";
/** db user name */
static $userName = 'root';
/** db password */
static $password = '';
And here is the piece of code which uses the PDO object to insert a record.
public function save() {
//get the PDO
$db_func = new db_functions();
$pdo = $db_func->getPDO();
$query = "INSERT INTO city(name, state, country) VALUES ('Vienna', 'Virginia', 'USA')";
echo $query;
$count = $pdo->exec($query);
if($count > 0) {
echo '</br> Successful </br>';
}else {
echo '</br> Unsuccessful </br>';
}
}
When I use the second function, the PDO object is created successfully but the insert fails. I do not see any error but the count is 0 and no records in the DB.
I am suspecting this has to do with the way I am declaring and using static variables in my code. Thanks for your help.
It's not related to static variables, your second method just doesn't pass the database name properly. It must be 'dbname' instead of 'dbName'.