I wrote this code
require('Database.class.php');
function get_info (){
$db = new Database($config['server'], $config['user'], $config['pass'], $config['database'], $config['tablePrefix']);
$db->connect();
$sql = $db->query('SELECT * FROM ja_cat');
while ($options = $db->fetch_array($sql)) {
$cat[].=" ".$options['title'];
}
$db->close();
return $cat;
then I get this Mysql error
Mysql Error : No database selected .
but when I put the require instruction inside the function it's work fine
My guess is Database.class.php creates some variables that are probably global in scope that it relies upon. If you require it inside the function and it works, that supports that theory. Is that your class? Can you change it? Can you post it?
Basically $config needs a global qualifier inside the function.
Make this the first line IN your get_info() function:
global $config;
Also, you may want to define $db outside of the function at the start of the code and then close the connection at the end, instead of having to re-connect multiple times.
You have to import the global variable $config into the scope of the function:
function get_info() {
global $config;
}
Related
I have php class like
class muhasebe {
public $smh_id;
public function smh_kayitekle($data){
global $conn;
$stok_miktar_hareket="INSERT INTO `smh`( `urun`, `iscilik`, `birim`, `adet`, `miktar`)
VALUES
('$urun',
'$iscilik',
'$birim',
'$adet',
'$miktar')";
$conn ->exec($stok_miktar_hareket);
*****$this ->smh_id***** = $conn->lastInsertId();
}
}
when run code, part between **** not working.
$conn is a pdo variable my aim is to use smh_id in another function in the class. when I use $this->smh_id without $this prefix ($smh_id), it is okey
but then I can not use in other function.
If smh_id is a variable you have to write
$this->$smh_id = //code here
I've a file data.php with different classes.
And in other file I make the require call.
<?php
include_once('data.php');
$db= new dataManager(); // here
class Manager{
//$db= new dataManager(); here doesn't work an error occurs
function savingData($ob )//obj
{
$db.saveData($ob);//error undefined variable $db
}
try with -> to call function with objects in php
$db->saveData($ob);
Also you need to pass $ob to manager class function
$newobj= new Manager();
$newobj->savingData($ob);
Okey after search I remembered global word
only we need to add
global $variable; in every function.
works yet.
<?php
include_once('data.php');
$db= new dataManager(); // here
class Manager{
function savingData($ob )//obj
{
global $db; //<---
$db.saveData($ob);//error solved
}
My database class works perfectly and I call it like this $db = new Database('user', 'pass', 'db', 'host');. I top of my script I am defining this database, but later in the script I am trying to use the connection inside a function, but it seems to that the $db is not global, so my function can't access it. I have the possibility to create a new database class connection inside every function in my script, but I really would like to access the $db as a global access point.
Here is some code:
require_once('database_class.php');
$db = new Database('user', 'pass', 'db', 'host');
// I can reach the $db here and make the $db->PDO->'statement'();
function userExists($user) {
$bool = false;
// But in here I can't access $db...
$query = $db->PDO->query('SELECT * FROM login WHERE username = "$user"');
$result = $query->fetch();
if ($result) {
// User exists
$bool = true;
}
return $bool;
}
Put global $db at the beginning of the function like so:
function userExists($user) {
global $db;
// Rest of code here
Variables within functions only exist locally by default in PHP. To use a variable declared outside of a function which is not passed as an argument (e.g $user) you need to use a global variable as shown above.
You could probably just modify your functions to take the $db var as an argument. e.g. :
function userExists($user, $db) {
...
}
Objects are passed by reference by default (see here) so you won't be inadvertently making copies of the $db object with each call.
I use classes for connections and queries too. But it would help that you define already in your class the variables needed for connection, so you don't have to repeat them in every page of code.
and maybe this? use the db as an argument.
function userExists($user, $db) { //codecodecode }
I'm trying to refactor some code but I'm kinda confused. I define my database connection like so:
try{
global $conn;
$conn = new PDO("mysql:host=$host",$root,$pw); [...]
Now I'd like a function for retrieving table rows but it needs $conn. Is there any way in which I can pass $conn into this function? I tried to set it as a default value but that doesn't work:
function get($table,$conn=$conn,$limit=10){ [...]
I then tried the use keyword but I think it's only available for anonymous functions:
function get($table,$limit=10)use($conn){
$query = $conn->query(" [...]
How do other people do this? Am I missing something obvious here?
function get($table, $limit=10)
As you already wrote in your question, this function header is incomplete. The function itself can not do what it needs to do without having $conn.
As this is a function in the global namespace, the most straight forward thing could be to use a global variable:
function conn_get($table, $limit=10) {
global $conn;
I also name-spaced the function to make the relation clear. The problem with this are two things:
global functions are expensive to maintain
global variables are expensive to maintain
So what you normally do in that case is to wrap this into a class:
class Conn
{
private $conn;
public function __construct(PDO $conn) {
$this->conn = $conn;
}
public function get($table, $limit=10) {
$query = $this->conn->query("[...]");
...
}
}
You then pass around a Conn object which can be used:
$pdo = new PDO("mysql:host=$host", $root, $pw);
$conn = new Conn($pdo);
And then:
$conn->get('ColorTable', 200);
The private variable takes over the role of the global variable with the benefit that every method inside the same object can access it. So everything now is in it's own space and contrary to the global space, will not go into each others way that fast. This is easy (easier) to change and maintain over time.
When you call the function i.e:
$table_rows = get($table, $conn);
You are passing local variables inside the function scope.
However you can't define a not-static variable as default: $conn=$conn will throw a fatal error.
In PHP, use is the way to go for anonymous / lambda-functions but not for ordinary functions.
If you have the database connection flying around in global scope, you can either pass it as a normal variable to your functions like so:
function get(PDO $conn, $table,$limit=10) {
$query = $conn->query(" [...]
}
Other than that (bad practice!) is to get the global $conn variable into the function like so:
function get($table,$limit=10) {
$query = $GLOBALS['conn']->query(" [...]
}
However, an object oriented approach is recommended! You might want to inject the Database Class via dependency injection into the classes, where you need it.
the most simple thing you can do is to create a function that will return you the $conn variable
function conn (){
$conn = NULL;
...some database connection setup etc...
return $conn;
}
and call it to other functions that you need to use it
function getDb(){
conn()->query(" [...]");
}
the conn() function will be available to all your functions on your PHP script.
but if you plan to make a more complex web application I recommend you to use a PHP framework or make a PHP class and apply OOP principles that would handle the database connection for you.
If I create an object inside of the main scope:
INDEX.PHP:
$db = new database();
Then how can I use this same object inside of a completely different class?
ANYTHING.PHP:
class anything {
function __construct(){
$db->execute($something); # I want to use the same object from INDEX.PHP
}
}
Would I need to make $db a global or is there a 'better' more obvious way?
You could just use global to find it:
class anything {
function __construct(){
global $db;
$db->execute($something);
}
}
Or, you could pass it in when creating a new anything:
class anything {
function __construct($db) {
$db->execute($something);
}
}
It really depends on what makes the most sense for you.
For the DB you may want to use Singleton pattern
class anything
{
public function load($id)
{
$db = DB::getInstance();
$res = $db->query('SELECT ... FROM tablename WHERE id = '.(int)$id);
// etc...
}
}
You may want to extend it if you need different DB connections at the same time (i.e main db and forum's db). Then you'll use it like DB::getInstance('forum'); and store instances in associative array.
You could pass it as an argument, like this
function __construct($db){
$db->execute($something);
}
then when you instance anything, do it as anything($db)
As Paolo and ONi suggested you can define $db as global inside the method or pass it into the constructor of the class. Passing it in will create a reference to that object so it will in fact be the same $db object. You could also use the $GLOBALS array and reference $db that way.
$GLOBALS["db"];
I'm assuming that index.php and anything.php are linked together somehow by include() or require() or some similar method?
In Paolo's post:
After you pass it, you can then assign it to a class variable like this:
class anything {
var $db_obj;
function __construct($db) {
$this->db_obj = $db;
}
function getUsers() {
return $this->db_obj->execute($something);
}
}