I'm trying to use db connection parameter inside function, i tried to global it but it does not working.
$host = 'localhost';
$username = 'b**s';
$password = '1******m';
$dbname = 'b*********e';
$connection = new mysqli($host, $username, $password, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
When i'm executing the query it returning error, becuase i didn't pass $connection parameter inside function.
function insertData(){
{......}
if($connection->query($sql)){
$response['success'] = 'User record successfully added!';
}
}
Can anyone guide me what is best to use without passing parameter inside function. I would like to appreciate if someone guide me.
In your function you should do something like
global $connection;
then use it below like
if($connection->query($sql)){
$response['success'] = 'User record successfully added!';
}
This is well documented in manual, i suggest you go have a look.
Create a database class and access it by object
<?php
class Database {
private static $db;
private $connection;
private function __construct() {
$this->connection = new MySQLi(/* credentials */);
}
function __destruct() {
$this->connection->close();
}
public static function getConnection() {
if (self::$db == null) {
self::$db = new Database();
}
return self::$db->connection;
}
}
?>
Then just use $db = Database::getConnection(); wherever I need it.
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.
i have a question about php.
I was wondering how can i add this code to a new object so i can later just add it to existing code and use it.
<?php
$mysqli = new mysqli("localhost", "root", "", "kooliasi");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
printf ("System status: %s\n", $mysqli->stat());
$mysqli->close();
?>
Thanks !
Make a class for the connection:
class Database{
private static $link = null ;
public static function getConnection ( ) {
if (self :: $link) {
return self :: $link;
}
$dsn = "mysql:dbname=social_network;host=localhost";
$user = "user";
$password = "pass";
self :: $link = new PDO($dsn, $user, $password); //OR mysqli - matter of preference
return self :: $link;
}
}
Then you can get the connection like this:
Database::getConnection();
This is a Singleton Pattern. You could use this if you like, but it is hard to scale - However, I think it will be fine for your needs. It takes a lot of load off your database.
There is a php.ini setting for prepending a file to every script -> http://www.php.net/manual/en/ini.core.php#ini.auto-prepend-file
You can create a db class where you can keep the connection handle. Add functions to the class as needed. For example
class db{
private $link;
public function __construct(){
$this->link = mysqli_connect(DB_SERVER, DB_USER, DB_PASS,DB_NAME);
}
public function __destruct() {
mysqli_close($this->link);
}
public function query($q){
... add code here for the query
}
}
Then to use the class you call:
$db = new db();
$db->query($parameters_you_want_to_pass);
global $link;
function linkDb() {
$hostname = 'xxxxx';
$username = 'xxxxxx';
$password = 'xxxxxx';
$database = 'xxxxxx';
$link = mysqli_connect($hostname, $username, $password);
if (!$link) {
echo ('Error: Could not make a database link using provided credentials');
die();
}
if (!mysqli_select_db($link, $database)) {
echo ('Error: Could not connect to database');
die();
}
return $link;
}
function unlinkDb() {
mysqli_close($link);
}
Above code file is included at the top of second file and i am trying to close the database connection,
unlinkDb();
but its saying
"ERROR: Undefined variable: link "
i am confuse.
You need to use the global keyword inside of your function:
function unlinkDb() {
global $link;
mysqli_close($link);
}
Then use it as such:
$link = linkDb();
unlinkDb();
Although a better solution is to not use the global keyword and pass $link as a parameter to linkDb():
$link = linkDb();
unlinkDb($link);
Use function definations as here:
function linkDb(&$link) {...}
function unlinkDb(&$link) {...}
If you prefer to keep the connection inside your class (I'm assuming I'm looking at a class) you can define it as a variable and refer to it from inside the instantiated object;
This way you can close/open the connection from anywhere inside your object by calling $this->linkDb(); and/or $this->unlinkDb();
class DBClass {
private $link;
function linkDb(){
$this->link = mysqli_connect($hostname, $username, $password);
}
function unlinkDb() {
mysqli_close($this->link);
}
}
You can also pass it via the function itself (as mentioned before), assuming you're NOT working in a class:
function linkDb(){
$link = mysqli_connect($hostname, $username, $password);
// Do fancy stuff
unlinkDb($link);
}
function unlinkDb($link){
mysqli_close($link);
}
i made the modifications to a code and changed it to following:
function linkDb()
{
$link = '';
..............
}
function unlinkDb($link) {
mysqli_close($link);
}
in the other file, where i am opening a connection i did this:
$link = linkDb();
and in the same file call a function to close DB this way:
unlinkDb($link);
Now its working the way, that i needed. I would to thanks all here who tried to help me out.