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'.
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
Im trying to insert data into mysql database.
I have class connection
class connection{
function __construct(){
$servername = 'localhost';
$username = 'root';
$password = '';
$database='products2';
// Create connection
$conn = new mysqli($servername, $username, $password,$database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
return false;
}else{
echo "succesful connection!</br>";
$this->query=$conn;
return true;
}
}
}
And another class in witch I try to insert data into database(i try to do this in __construct of that class)
$sql="INSERT INTO products (name,price,category,f_material,f_size) VALUES ('nosaukums','cena','kategorija,'materials','izmers')";
$db=new connection();
$result=$db->query($sql);
However I get this errror:
Fatal error: Call to undefined method connection::query() in ....
In order to use the query (from mysqli class) method you need to create a new method public function query() {}. This method will be able to use the mysqli method. In the end, you will be able to acheive the same result but by applying 'query' on your own object ($db) like so $result = $db->query($sql);
Here's the class :
<?php
class connection{
// define a variable for the database connection
private $conn;
// when an instance of 'connection' class is created a connection is made through mysqli
public function __construct()
{
$servername = 'localhost';
$username = 'root';
$password = '';
$database='products2';
// the connection is stored inside the private variable
$this->conn = new mysqli($servername, $username, $password,$database);
// Check connection
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
return false;
} else{
echo "succesful connection!</br>";
return true;
}
}
// method used to send a query to database
public function query($sql)
{
// here you use the connection made on __construct() and apply the method query. Basically we are using inside our method (called query) a method (call query too) from the mysqli class
$this->conn->query($sql);
return true;
}
}
Calling the method :
<?php
// prepare the SQL request
$sql = "INSERT INTO products (name,price,category,f_material,f_size) VALUES ('nosaukums','cena','kategorija,'materials','izmers')";
// create a new instance of the class connection
$db = new connection();
// run the method $sql on the newly created instance $db
$result = $db->query($sql);
Because in your last line - $result = $db->query($sql); - you are trying to call a function named 'query'. If you look inside your connection class the only function you have is the constructor.
To fix this you are going to need to add a function called "query" (note this is not an ideal name for the function).
Here is some commented code (not guaranteed to be error free!)
class connection{
protected $conn; // add conn so that you can use it later
function __construct()
{
$servername = 'localhost';
$username = 'root';
$password = '';
$database='_mvc';
// Assign $this->conn to a database object
$this->conn = new mysqli($servername, $username, $password, $database);
// Remember we are checking >>THIS<< conn now
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
return false;
}else{
// no need to assign anthing here as the database object has already been assigned to $this->conn
echo "succesful connection!</br>";
return true;
}
}
// here is the missing function
public function query($sql) {
// now we are accessing the database objects query method and massing the SQL
return $this->conn->query($sql);
}
}
$sql =
"INSERT INTO products (name,price,category,f_material,f_size)
VALUES ('nosaukums','cena','kategorija,'materials','izmers')";
$db = new connection();
$result = $db->query($sql);
I would recommend you jump straight into php data objects and be done with it because PDO is the best 'standard' way to access databases these days.
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.
Similar questions have been asked but I believe they do not cover my case.
I experimented with a few ways to pass db class to other classes for access and found that the below works well.
My question is: is there anything wrong with that approach and whether Dependency Injection will be a better solution?
class Database{
private $db_host = "localhost";
private $db_user = "root";
private $db_password = "";
private $db_name = "dbName";
private $pdo;
public $instance;
function __construct() {
try{
//create a PDO connection and assign it to some handler
$this->pdo = new PDO('mysql:host='. $this->db_host.';dbname='. $this->db_name, $this->db_user, $this->db_password);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// echo "connected";
} catch (PDOException $e) {
exit("Error connecting to database". $e->getMessage());
}
}
public function getPDO(){
return $this->pdo;
}
}
class OtherClass{
require_once 'Database.php';
private $db_instance;
private $dbh;
function __construct() {
$this->db_instance = new Database();
$this->dbh = $this->db_instance->getPDO();
}
}
How about a simple class from which you can create and destroy a connection to the database if its not needed. Lets refractor your code abit.
First create a classname that can be identified easily, something like
class pdo_mysql{
Its a pdo class, but based on mysql, next declare some variables, (The explanation in the comments)
/*
* Description - The name of the database
*/
private $dbname;
/*
* Description - The database username
*/
private $dbuser;
/*
* Description - The database password
*/
private $dbpass;
/*
* Description - The database Host
*/
private $dbhost;
/*
* Description - The database driver
* #Parameters - null
* To do -
* Notes:
*/
private $dbdriver;
/*
* Description - Stores the connection to the database
*/
private $con;
Then lets define the constructor for our class:
/*
* Description - This is the default method that is called when this class is instantiated.
* #Parameters - dbhost|dbdriver|dbname|dbusername|dbpassword
*/
function __construct($dbhost, $dbdriver, $dbname, $dbuser, $dbpass){
$this->dbhost = $dbhost;
$this->dbdriver = $dbdriver;
$this->dbname = $dbname;
$this->dbuser = $dbuser;
$this->dbpass = $dbpass;
}
Note that when the class is instantiated, most class variables are set.
Then our connection function:
/*
* Description - Creates a connection to the database
* Notes: - Returns true on success || string with an error msg on failure
*/
private function _connect(){
try {
$this->con = new PDO(''.$this->dbdriver.':host='.$this->dbhost.';dbname='.$this->dbname.'', $this->dbuser, $this->dbpass);
$this->con->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
$this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->con->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return true;
} catch (PDOException $e){
return $e->getMessage();
}
}
And finally a function to disconnect our connectio to the database:
/*
* Description - Disconnects database connection
*/
private function _disconnect(){$this->con = null;return true;}
And a finally a function to query the database:
/*
* Description - Retrieves information from the database
*/
function _loadResult($data){}
This class will use data that is pre populated, so lets create for it a function to initialize it: (this should be in a different file/class)
/*
* Description - Get the config options from a file and initiate the database object
* Notes: - Returns a new object of the database connection class on success | false on fail
the config file must contain the following values dbhost|dbengine|dbname|dbusername|dbpassword
*/
static public function getDbo(){
if(!is_readable(/*path to your config file*/)){// lets check that the config file exists and is readable
return 'ERROR - The config file is missing or its unreadable!';
}
$config = parse_ini_file(/*path to your config file*/);
if($config === false){//parse the config file and return an error incase the purse fails
return 'ERROR - Could not parse the config file!';
}
//the following values are populated by the ones parsed from the config file
$dbhost = $config['dbhost'];
$dbclassprefix = $config['dbclassprefix'];
$dbdriver = $config['dbdriver'];
$dbname = $config['dbname'];
$dbuser = $config['dbuser'];
$dbpass = $config['dbpass'];
static $dbobject = null;//create the database object if all went well
if(null === $dbobject){$dbclass = $dbclassprefix.$dbdriver;$dbobject = new $dbclass($dbhost, $dbdriver, $dbname, $dbuser, $dbpass);}
return $dbobject;//return the database object
}
A case usage of the above code:
$db = self::getDbo();//create the database object
if(is_string($db)){//if the return value is a string, then thats an error
//return an error
}
$res = $db->_loadResult($data);//call a function from the database class
This is just a shaddy example from my head to give you some rough ideas, but its fully guaranteed to work if coded correctly, with the above classes and functions, you can change the engine to either PDO_mysqli or another another by changing the value in your config file. Hope you get the idea
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;
}
}