Is it possible to give a mysql resource to a $_SESSION variable ?
//mysqldb.inc.php
class mySqlDb
{
private $link;
public function __construct($_host = '', $_db = '', $_user = '', $_pwd = '')
{
$link = mysql_pconnect(...);
}
public function query($data)
{
$r = mysql_query($data, $this->link);
return $r;
}
}
//index.php
session_start();
include_once('mysqldb.inc.php');
$sqlobj = new mySqlDb();
$sqlobj->dbconnect($db_host, $db_name, $db_user, $db_pwd);
$_SESSION['mysqldb'] = $sqlobj;
//check.php
session_start();
include_once('mysqldb.inc.php');
$sqlobj = $_SESSION['mysqldb'];
$sqlobj->query(...);
$sqlobj->query(...) return
Fatal error: main(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "mySqlDb" of the object you are trying to operate on was loaded before unserialize() gets called or provide a __autoload() function to load the class definition in D:\apache\www\check.php on line 4`
If I use $_SESSION['mysqldb'] = serialize($sqlobj) and $sqlobj = unserialize($_SESSION['mysqldb']) I have this error:
Warning: mysql_query() expects parameter 2 to be resource, integer given in D:\apache\www\mysqldb.inc.php on line ...
You cannot persist php resources.
That's it - you just cannot. So you need to connect to database each time.
The $_SESSION documentation notes:
Because session data is serialized, resource variables cannot be stored in the session.
You have this:
$sqlobj = new mySqlDb();
But then you do this:
$_SESSION['mysqldb'] = $sql;
I.e. you're setting $_SESSION['mysqldb'] to an object that doesn't exist. Try $sqlobj instead.
Related
I am unable to fetch record from a MySQL database using PHP. Here is my code.
user.php:
require_once ('../../include/dbconfig.php');
require_once ('common.php');
error_reporting(E_ALL);
ini_set('display_errors', '1');
$userClass=new CommonConnectorFuncs();
$redata=$userClass->insertUserRecordForSignup();
echo $redata;exit;
common.php:
require_once ('../../include/dbconfig.php');
error_reporting(E_ALL);
ini_set('display_errors', '1');
$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") ? "https" : "http";
$imagepath=$protocol. "://" . $_SERVER['HTTP_HOST']."/connector/upload/";
class CommonConnectorFuncs{
function __construct() {
}
// destructor
function __destruct() {
// $this->close();
}
public function insertUserRecordForSignup(){
$sql=mysqli_query($connect,"select * from cn_user_info order by user_id desc");
while ($row=mysqli_fetch_array($sql)) {
$data[]=$row;
}
return $data;
}
}
Here I am trying to fetch record and print through class but it's throwing the below message.
Notice: Undefined variable: connect in common.php on line 16
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in common.php on line 16
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in common.php on line 17
Notice: Undefined variable: data in common.php on line 20
Those query is working fine inside the user.php file but it's not working in common.php file.
As mentioned in comments, this is a scoping issue. Specifically, $connect is not in scope.
Notice: Undefined variable: connect in common.php on line 16
where connect is not defined anywhere.
Moreover, It's exactly as the error states as you're passing arguments to mysqli_query incorrectly. Assumming $connect is your mysqli connection generated at some point by new mysqli() it should be:
$sql = "select * from cn_user_info order by user_id desc";
$result = mysqli_query( $connect,$sql) or die('Could not look up user information; ' . mysqli_error($connect))
Hope it helps!
Make the connect variable a property of your class as by parsing it in your construct function
require_once ('../../include/dbconfig.php');
require_once ('common.php');
error_reporting(E_ALL);
ini_set('display_errors', '1');
$userClass=new CommonConnectorFuncs($connect);
$redata=$userClass->insertUserRecordForSignup();
echo $redata;exit;
In your class,
class CommonConnectorFuncs{
var $Connection;
function __construct($connection) {
try{
if($connection != null){
$this->Connection = $connection;
}else{
throw new Exception('Connection is null. COuld not process further');
}
}catch(Exception $ex){
echo $ex->getMessage();
exit;
}
}
// destructor
function __destruct() {
// $this->close();
}
public function insertUserRecordForSignup(){
$sql=mysqli_query($this->Connection,"select * from cn_user_info order by user_id desc");
while ($row=mysqli_fetch_array($sql)) {
$data[]=$row;
}
return $data;
}
}
The problem is in that you are trying to access a global variable within a function.
First of all, make sure you include the php file with the relevant database connection. And as you are trying to access a global variable there are two ways to achieve this.
Method 1
Create a global variable at the top of the function.
global $connect;
But as Qirel says in this comment, it is a bad practise, so I'd suggest the next.
Method 2
Pass the connection to the function's parameters.
public function insertUserRecordForSignup($connect){
$sql=mysqli_query($connect,"select * from cn_user_info order by user_id desc");
while ($row=mysqli_fetch_array($sql)) {
$data[]=$row;
}
return $data;
}
Hope you find this useful.
I can get by with editing procedural PHP (just), but OOP is a different thing. So I'm not that experienced with what I'm doing here, but I'm trying my best...
I have a file called Quote.object.php containing the following:
$Query = new DbQuery( "INSERT", "quotes", $array );
$this->id = mysqli_insert_id();
mysqli_insert_id needs to be fed a DB connection parameter, but I'm not sure how to do it. There is another file called Mysql.handler.php containing the database connection variable - is there a way that I can make $con available as a parameter of $Query above?
class DbQuery extends DbConnectionInfo{
// file: includes/classes/MysqlQuery.php
// contains functions needed to perform queries on mysql database and functions for necessary data processing for application
// SELECT = new DbQuery("select", table,cols[$value] ,where[$col=$value],order[$value],limit);
// INSERT = new DbQuery("insert", table, data[$col=$value]);
// UPDATE = new DbQuery("update", table, data[$col=$value],where[$col=$value],limit);
// set testing as true for SQL reports in page
var $results;
var $sql;
function __construct($mode,$table = '',$var1 = '',$var2 = '',$var3 = '',$var4='')
//connects to database according to info in DbConnectInfo, runs query, closes connection
{
$temp = '';
$con = mysqli_connect($this->host, $this->user, $this->pass) or die ('There was a problem connecting to the database ' . (ENVIRONMENT == 'Development' ? mysqli_error() . "$this->user, $this->pass, $this->host" : ''));
mysqli_select_db($con,$this->db) or die ('There was a problem connecting to the database' . (ENVIRONMENT == 'Development' ? mysqli_error() : ''));
I'm trying to get $con from DbQuery so I can put it into mysqli_insert_id(). I assume that's what I need? Is there a way to get $con from DbQuery and put into mysqli_insert_id()? Or do you need more information to know this?
NB I've tried to be concise in trying to show just relevant information, apologies if I've missed other helpful info.
You're defining an object, so make $con a class variable, e.g.
function __construct() {
$this->con = mysqli_connect(...);
^^^^^^^----store in object
}
function foo() {
$result = mysqli_query($sql, $this->con);
^^^^^^^^---retrieve from object
}
I am having a strange error while creating objects. While I create an objects in chronological orders as classed defined, it is going on good. But when I change the order or object creation, it gives error.
The classes I am using are as follows:
<?php
class dbClass{
private $dbHost, $dbUser, $dbPass, $dbName, $connection;
function __construct(){
require_once("system/configuration.php");
$this->dbHost = $database_host;
$this->dbUser = $database_username;
$this->dbPass = $database_password;
$this->dbName = $database_name;
}
function __destruct(){
if(!$this->connection){
} else{
mysql_close($this->connection);
}
}
function mysqlConnect(){
$this->connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass) or die("MySQL connection failed!");
mysql_select_db($this->dbName,$this->connection);
}
function mysqlClose(){
if(!$this->connection){
} else{
mysql_close($this->connection);
}
}
}
class siteInfo{
private $wTitle, $wName, $wUrl;
function __construct(){
require_once("system/configuration.php");
$this->wTitle = $website_title;
$this->wName = $website_name;
$this->wUrl = $website_url;
}
function __destruct(){
}
function showInfo($keyword){
if($keyword=="wTitle"){
return $this->wTitle;
}
if($keyword=="wName"){
return $this->wName;
}
if($keyword=="wUrl"){
return $this->wUrl;
}
}
}
?>
The problem is when I create objects in the following order, it is working perfectly:
include("system/systemClass.php");
$dbConnection = new dbClass();
$dbConnection -> mysqlConnect();
$siteInfo = new siteInfo();
But if I change the order to following
include("system/systemClass.php");
$siteInfo = new siteInfo();
$dbConnection = new dbClass();
$dbConnection -> mysqlConnect();
It gives error!
Warning: mysql_connect() [function.mysql-connect]: Access denied for user '#####'#'localhost' (using password: NO) in /home/#####/public_html/#####/system/systemClass.php on line 19
MySQL connection failed!
Your problem comes from the unconventional use of a configuration file that is read ONCE, but should be used in all classes.
When you instantiate the dbclass first, the configuration is read, probably variables get assigned, and you use these in the constructor.
After that, instantiating siteinfo will not read that file again, which is less harmful, because you only end up with an empty object that does return a lot of null, but does work.
The other way round, you get a siteinfo object with all the info, but a nonworking dbclass.
My advice: Don't use a configuration file that way.
First step: Remove the require_once - you need that file to be read multiple times.
Second step: Don't read the file in the constructor. Add one or more parameters to the constructor function and pass the values you want to be used from the outside.
Info: You can use PHP code files that configure stuff, but you shouldn't define variables in them that get used outside. This will work equally well:
// configuration.php
return array(
'database_host' => "127.0.0.1",
'database_user' => "root",
// ...
);
// using it:
$config = require('configuration.php'); // the variable now has the returned array
Below is my class. Fig A
<?php
class qcon{
public static $conn;
function dbcon()
{
if (!$conn)
{
$host = 'x';
$username = 'x';
$password = 'x';
$dbname = 'x';
$conn = mysqli_connect($host , $username , $password ,$dbname);
}
return $conn;
}
}
?>
Which is called here. Fig B
require_once(class file above);
function openSesame()
{
$boogey = new qcon();
$conn = $boogey->dbcon();
if (!$conn)
{
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
Is causing
Notice: Undefined variable: conn in C:\...\xxxx\figAclass.php on line 10
I know I can simply turn errors off, but this seems unwise. I took a look at a generic SO question about the undefined variable notice. Obviously the advice was general - use isset. Had a go at isset and this does not seem correct for what I am trying to do.
Based on the code in figure A and B, is there anything obvious causing the notice to be flagged up. Could you demonstrate a fix that is in line with the existing code shown.
Don't use if (!$conn), which will check to see if the variable is true/false or contains a value, not if it's defined. Use this instead:
if(empty($conn))
This checks to see if the variable is defined, and if it is NULL/empty.
You also want to use $this->conn inside of your class instead, since you're defining it as a variable of the class.
Like I said in my comment above, since you have a static $conn, you need to refer to it like:
public function dbconn()
{
if (!self::$conn) {
// blah
}
return self::$conn;
}
Your error is happening because you're attempting to reference a variable named $conn, but due to scope, no such thing exists.
when you access it, you should use $this->conn, in example:
if(!$this->conn){...}
edited read the question too fast, sorry
You can't use if (!$conn)for this because that will only return 'true' or 'false'.
Use:
if empty($conn) instead.
I'm a .Net developer that have taken over a PHP project. This project has a database layer that looks like this:
<?php
class DatabaseManager {
private static $connection;
const host = "projectname.mysql.hostname.se";
const database = "databaseName";
const username = "userName";
const password = "password";
public function __construct()
{
}
public function instance($_host = null, $_username = null, $_password = null)
{
if(!self::$connection)
{
if(!$_host || !$_username || !$_password)
{
$host = self::host;
$username = self::username;
$password = self::password;
}else{
$host = $_host;
$username = $_username;
$password = $_password;
}
self::$connection = mysql_connect($host, $username, $password);
$this->setDatabase();
}
return self::$connection;
}
public function setDatabase($_database = null)
{
if(!$_database)
{
$database = self::database;
}else{
$database = $_database;
}
$connection = $this->instance();
mysql_select_db($database, $connection) or die(mysql_error());
}
} ?>
I have written a php file that uses this layer but after a while i got these mysql errors implying i didn't close my connections which i hadn't. I try to close them but know i get other weird errors like system error: 111. Very simplyfied my php file looks like this:
<?php
$return = new stdClass();
$uid = '9999999999999';
$return->{"myUid"} = $uid;
$dm = new DatabaseManager();
$dmInstance = $dm->instance();
/* MY CLICKS */
$sql = sprintf("SELECT count(*) as myClicks FROM clicks2011, users2011 WHERE clicks2011.uid = users2011.uid AND users2011.uid = %s AND DATEDIFF(DATE(at), '%s') = 0 AND exclude = 0", mysql_real_escape_string($uid), mysql_real_escape_string($selectedDay));
$result = mysql_query($sql, $dmInstance) or die (mysql_error());
$dbResult = mysql_fetch_row($result);
$return->{"myClicks"} = $dbResult[0];
mysql_close($dmInstance);
echo json_encode($return); ?>
Okay, I'm going to post this as an answer because I think one (possibly both) of these things will help you.
First: You don't need to manually close your MySQL connections. Unless you have set them up so that they persist, they will close automatically. I would avoid doing that unless you determine that every other problem is NOT the solution.
In addition, I would switch to using prepared statements. It's more secure, and pretty future-proof. I prefer PHP's PDO over mysqli, but that's up to you.
If you'd like to look over an example of a simple PDO object to take the many lines out of creating prepared statements and connections and getting results, you can look at my homebrew solution.
Second: "System Error 111" is a MySQL error. From what I've read, it appears that this error typically occurs when you are using PHP and MySQL on the same server, but telling PHP to connect to MySQL via an IP address. Switch your $host variable to 'localhost'. It is likely that this will solve that error.
The problem here is you're calling mysql_close and not specifying a valid mysql connection resource object. You're, instead, trying to close an instance of the DatabaseManager object.
You'll probably want to run mysql_close(DatabaseManager::connection); which is where the DatabaseManager is storing the resource object.
Additionally, I'd personally recommend you learn PDO or use the mysqli drivers. In future releases of PHP the built in mysql functions will be moved into E_DEPRECATED
Try implement __destrcut
public function __destruct()
{
mysql_close(self::$connection)
}
Then simply use unset($dm);