I'm fairly new at PHP and so maybe this is a simple question. This is a class I use to update a database. The problem is that it keeps giving me an error at the line marked * because it can't find $con, which is clearly in the function openconn(). It seems I can't pass the connection to another function. Am I doing something wrong?Thanks
class retreats {
public $retreat_name = '';
function openconn() {
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("PHPTest", $con);
}
function closeconn(){
mysql_close($con);
}
function add_retreat(){
openconn();
$sql="INSERT INTO tbl_retreats (retreat_name) VALUES ('".$this->retreat_name."')";
if (!mysql_query($sql,$con)) *******
{
die('Error: ' . mysql_error());
}
echo "Record Successfully Added";
closeconn();
}
}
$con is a local variable for the function openconn. Try to change your code in this way:
class retreats {
public $retreat_name = '';
private $con;
function openconn() {
$this->con = mysql_connect("localhost","root","root");
if (!$this->con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("PHPTest", $this->con);
}
function closeconn(){
mysql_close($this->con);
}
function add_retreat(){
openconn();
$sql="INSERT INTO tbl_retreats (retreat_name) VALUES ('".$this->retreat_name."')";
if (!mysql_query($sql,$this->con))
{
die('Error: ' . mysql_error());
}
echo "Record Successfully Added";
closeconn();
}
}
A Simple PDO port of your code...
<?php
class pdoDB{
//PDO Connect
function connect($host,$db,$user,$pass){
$this->dbh = new PDO('mysql:host='.$host.';dbname='.$db, $user, $pass);
}
function query($query){
$this->retreat_name = $query;
$this->prepare();
}
function prepare(){
/* Execute a prepared statement by binding PHP variables */
$this->sth = $this->dbh->prepare('INSERT INTO tbl_retreats (retreat_name) VALUES (:value)');
$this->sth->bindParam(':value', $this->retreat_name);
$this->execute();
}
function execute(){
$this->sth->execute();
}
function result(){
if ($this->sth->rowCount() > 0) {
return 'Record Successfully Added';
}else{
return 'Record Not Inserted';
}
}
function close(){
$this->sth = null;
}
}
$db = new pdoDB();
$db->connect('localhost','PHPTest','root','pass');
$db->query('Barcelona'); //or $db->query($_POST['retreat_name']);
echo $db->result();
$db->close();
?>
You need to first declare the $con in the class. Just put it after the public $retreat_name = '';
put
public $retreat_name = '';
private $con;
after that, you can use it in other functions using the $this keyword.
mysql_close($this->con);
it turns out you need to do this
$this->openconn();
instead of just
openconn();
Related
I am using Object oriented Php. For connecting Two database in same host I am using code like this
<?php
class ConOs{
var $dbhost1;
var $dbuser1;
var $dbpass1;
var $dbhost2;
var $dbuser2;
var $dbpass2;
function __construct() {
}
function connect(){
$this->dbhost1="localhost";
$this->dbuser1="user1";
$this->dbpass1="db1";
$this->dbhost2="localhost";
$this->dbuser2="user2";
$this->dbpass2="db2";
$conn1 = mysql_connect($this->dbhost1, $this->dbuser1, $this->dbpass1);
if(! $conn1 ){die('Could not connect: ' . mysql_error());}
mysql_select_db("db1",$conn1);
$conn2 = mysql_connect($this->dbhost2, $this->dbuser2, $this->dbpass2, True);
if(! $conn2 ){die('Could not connect: ' . mysql_error());}
mysql_select_db("db2", $conn2);
mysql_error();
}
}
?>
But $conn1 allways refused. Only $conn2 works. If I put $conn2 first, then only $conn1 works. How it possile to connect both database db1 & db2 ?
My dear stop to use mysql_* functions: use PDO :
class sujet{
private $id;
public function connect(){
try {
$bdd = new PDO('mysql:host=localhost;dbname=dev_bdd', 'root', '');
}catch(Exception $e){
die('Failed'. $e->getMessage());
}
return $bdd;
}
public function connect2(){
try {
$bdd = new PDO('mysql:host=localhost;dbname=teamd2', 'root', '');
}catch(Exception $e){
die('Failed'. $e->getMessage());
}
return $bdd;
}
public function __construct(){}
public function recherche($search){
$resultats = array();
$req = $this->connect2()->prepare('SELECT * FROM sujets WHERE libelle like :search ');
$req->execute(array(
'search' => '%'.$search.'%',
));
while($resultat = $req->fetch()){
array_push($resultats,$resultat);
}
print_r($resultats);
return $resultats;
}
private function queryMatiere(int $id){
$requete = $this->connect()->query("SELECT libelle FROM matieres where id=$id");
$data = $requete->fetch();
return $data['libelle'];
}
}
How do I query MySQL by this class and SET time_zone after every query? I'm having some trouble about where to place the timezone command in the following code block:
class MyDB {
private $connection;
public $last_query;
private $magic_quotes_active;
private $real_escape_string_exists;
function __construct(){
$this->open_connection();
$this->magic_quotes_active = get_magic_quotes_gpc();
$this->real_escape_string_exists = function_exists("mysql_real_escape_string");
}
public function open_connection(){
$this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if(!$this->connection){
die("Database connection failed: " . mysql_connect());
} else {
$db_select = mysql_select_db(DB_NAME, $this->connection);
if(!$db_select){
die("Database selection failed: " . mysql_error());
}
}
}
public function close_connection(){
if(isset($this->connection)){
mysql_close($this->connection);
unset($this->connection);
}
}
public function query($sql) {
$this->last_query = $sql;
$result = mysql_query($sql, $this->connection);
$this->confirm_query($result);
return $result;
}
public function escape_value($value){
if($this->real_escape_string_exists){ // PHP v.4.3.0 or higher
//undo any magic quote effects so mysl_real_escape_string can do the work
if($this->magic_quotes_active){
$value = stripslashes($value);
}
$value = mysql_real_escape_string($value);
} else { // before PHP v.4.3.0
// if magic quotes aren't already on then add slashes manually
if(!$this->magic_quotes_active) {
$value = addslashes($value);
}
// if magic quotes are active, then the slashes already exist
}
return $value;
}
public function fetch_array($result_set){
return mysql_fetch_array($result_set);
}
public function num_rows($result_set){
return mysql_num_rows($result_set);
}
public function insert_id($result_set){
return mysql_insert_id($this->connection);
}
public function affected_rows($result_set){
return mysql_affected_rows($this->connection);
}
private function confirm_query($result){
if(!$result){
$output = "Database query failed: " . mysql_error() . "<br /><br />";
$output .= "Last SQL query: ". $this->last_query;
die($output);
}
}
}
$database = new MyDB();
$db =& $database;
You could set it on the fly like this:
date_default_timezone_set('America/New_York');
When I'm using mysqli without class it's going ok:
index.php
require_once(dirname(__FILE__) . '/config.php');
$mysqli = new mysqli($hostname, $username, $password, $dbname);
$queryText = "SELECT * FROM User";
if($query = $mysqli->query($queryText)) {
$results = $query->fetch_array();
echo $results['userId'];
} else {
echo "Error ";
echo $mysqli->errno . " " . $this->mysqli->error;
}
?>
But when I start using mysqli with class something goes wrong. connectDB doesn't give any error, so i get connected to DB. But then when trying do any query it give me "No database selected error"
Result of index.php is: Error 1046 No database selected
index.php
<?php
require_once(dirname(__FILE__) . '/banana.php');
$banana = new Banana(1);
if ($banana->connectDB()) {
$banana->doQuery();
}
?>
banana.php
<?php
require_once(dirname(__FILE__) . '/config.php');
class Banana {
private $mysqli, $userId, $query;
function __construct($userId) {
$this->userId = $userId;
}
function __destruct() {
$this->mysqli->close();
}
public function connectDB() { // Подключение к БД
$this->mysqli = new mysqli($hostname, $username, $password, $dbname);
if ($this->mysqli->connect_errno) {
echo "Error (" . $this->mysqli->connect_errno . ") " . $this->mysqli->connect_error;
return false;
}
return true;
}
public function doQuery() {
$queryText = "SELECT * FROM User";
if($this->query = $this->mysqli->query($queryText)) {
$results = $query->fetch_array();
echo $results['userId'];
} else {
echo "Error ";
echo $this->mysqli->errno . " " . $this->mysqli->error;
}
}
?>
So it's very frustrating. I'm about 2 weeks in php, but can't find answer for couple days. I guess the answer is obvious but I can't see it.
Thank you for your time and patience.
One of the first problems you will encounter when you run your script is here:
public function connectDB() { // Подключение к БД
$this->mysqli = new mysqli($hostname, $username, $password, $dbname);
Note that all 4 variables you are using in your function call ($hostname, etc.) are undefined in the scope of the method.
There are several ways you can solve this:
Pass the variables as parameters to the method:public function connectDB($hostname, ...
Pass the necessary variable to your class constructor and set configuration properties in your class that you can use later on;
Use constants instead of variables;
Declare your variables global.
I would recommend one of the first 2 and definitely not the last one.
You can read more in the php manual about variable scope.
It looks like you are a copy'n'paste victim. In doQuery() change:
if($this->query = $this->mysqli->query($queryText)) {
$results = $query->fetch_array();
To:
if($this->query = $this->mysqli->query($queryText)) {
$results = $this->query->fetch_array();
I am making a module in which I am fetching users from Database Using OOP.
But due to some reason , records are not fetching, and there is no mysql error.
Here is my Code:
dbsetup_class.php :
<?php
class mySQL{
var $host;
var $username;
var $password;
var $database;
public $dbc;
public function connect($set_host, $set_username, $set_password, $set_database)
{
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
$this->database = $set_database;
$this->dbc = mysqli_connect($this->host, $this->username, $this->password, $this->database) or die('Error connecting to DB');
}
public function query($sql)
{
/* echo "<pre>";
var_dump($this->dbc);
*/
//echo $sql;
return mysqli_query($this->dbc, $sql) or die('Error querying the Database');
}
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql));
return $array;
}
public function close()
{
return mysqli_close($this->dbc);
}
}
?>
And here is my index.php:
<?php
require_once("dbsetup_class.php");
$connection = new mySQL();
$connection->connect('localhost', 'admin', 'admin', 'oop_test');
//die('success');
$myquery = "SELECT * FROM users";
$query = $connection->query($myquery);
$array = $connection->fetch($query);
while($array)
{
echo $array['first_name'] . '<br />';
echo $array['last_name'] . '<br />';
}
$connection->close();
?>
What I am doing here?
Your fetch method expects SQL query, and not the result of a query. You should redefine it as (assuming that the client code is what you want as an interface):
public function fetch($resource)
{
$array = mysqli_fetch_array($resource);
return $array;
}
Also if you have results, your while will be infinite.
class MySQLDatabase {
private $connection;
function __construct(){
$this->open_connection();
}
public function open_connection(){
$this->connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if(!$this->connection){
die("Database connection failed: ". mysql_error());
}
else {
$db_select = mysql_select_db(DB_NAME,$this->connection);
if(!$db_select){
die("Database connection failed: ". mysql_error());
}
}
}
public function close_connection(){
if(isset($this->connection)){
mysql_close($this->connection);
unset($this->connection);
}
}
public function query($sql){
$result = mysql_query($sql,$this->connection);
$this->confirm_query($result);
return $result;
}
public function fetch_array($result_set){
return mysql_fetch_array($result_set);
}
public function num_rows($result){
return mysql_num_rows($result);
}
public function affected_rows(){
return mysql_affected_rows($this->connection);
}
private function confirm_query($result){
if(!$result){
die("Database query failed: ". mysql_error());
}
}
}
$db = new MySQLDatabase();
this is the other bit {read.php}
require_once("db.php");
class Read{
private $table_name= "real_estate";
private $column_name = "Property_type";
function __construct(){
}
public function pro_type() {
global $db;
var_dump($db);
echo "<select name='".$this->column_name."'>";
$sql = sprintf("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '%s' AND COLUMN_NAME = '%s'",$this -> table_name,$this ->column_name);
$result = $db-> query($sql);
$row = $db->fetch_array($result);
$enumList = explode(",", str_replace("'", "", substr($row['COLUMN_TYPE'], 5, (strlen($row['COLUMN_TYPE'])-6))));
foreach($enumList as $value)
echo "<option value=$value>$value</option>";
echo "</select>";
}
}
link.php
require_once("read.php");
$link = new Read();
index.php
<?php
include '../inc/link.php';
$link -> pro_type();
?>
Every thing seems perfect, but it gives an error message saying that a query is being called on a non object. I actually called $db in another script, but nothing seems to be working.
What does the call in your other script look like? Should be something like this:
require_once('includes/mysql.php'); // Where your MySQLDatabase class resides
if(class_exists('MySQLDatabase')) {
$db = new MySQLDatabase();
// Should work from here
$db->query("SELECT * FROM `table` WHERE 1");
} else {
die('Unable to load class.');
}