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
}
Related
Warning: mysqli::query(): Couldn't fetch mysqli in C:\Program Files (x86)\EasyPHP-DevServer-13.1VC9\data\localweb\my portable files\class_EventCalendar.php on line 43
The following is my connection file:
<?php
if(!isset($_SESSION))
{
session_start();
}
// Create array to hold error messages (if any)
$ErrorMsgs = array();
// Create new mysql connection object
$DBConnect = #new mysqli("localhost","root#localhost",
NULL,"Ladle");
// Check to see if connection errno data member is not 0 (indicating an error)
if ($DBConnect->connect_errno) {
// Add error to errors array
$ErrorMsgs[]="The database server is not available.".
" Connect Error is ".$DBConnect->connect_errno." ".
$DBConnect->connect_error.".";
}
?>
This is my class:
<?php
class EventCalendar {
private $DBConnect = NULL;
function __construct() {
// Include the database connection data
include("inc_LadleDB.php");
$this->DBConnect = $DBConnect;
}
function __destruct() {
if (!$this->DBConnect->connect_error) {
$this->DBConnect->close();
}
}
function __wakeup() {
// Include the database connection data
include("inc_LadleDB.php");
$this->DBConnect = $DBConnect;
}
// Function to add events to Zodiac calendar
public function addEvent($Date, $Title, $Description) {
// Check to see if the required fields of Date and Title have been entered
if ((!empty($Date)) && (!empty($Title))) {
/* if all fields are complete then they are
inserted into the Zodiac event_calendar table */
$SQLString = "INSERT INTO tblSignUps".
" (EventDate, Title, Description) ".
" VALUES('$Date', '$Title', '".
$Description."')";
// Store query results in a variable
$QueryResult = $this->DBConnect->query($SQLString);
I'm not great with OOP PHP and I'm not sure why this error is being raised. I pulled this code from elsewhere and the only thing I changed was the #new mysqli parameters. Can anyone help me to understand what is going wrong?
Probably somewhere you have DBconnection->close(); and then some queries try to execute .
Hint: It's sometimes mistake to insert ...->close(); in __destruct() (because __destruct is event, after which there will be a need for execution of queries)
Reason of the error is wrong initialization of the mysqli object. True construction would be like this:
$DBConnect = new mysqli("localhost","root","","Ladle");
I had the same problem. I changed the localhost parameter in the mysqli object to '127.0.0.1' instead of writing 'localhost'. It worked; I’m not sure how or why.
$db_connection = new mysqli("127.0.0.1","root","","db_name");
Check if db name do not have "_" or "-"
that helps in my case
I am trying to fetch table categories data from DB named stores. Here when I run this code it displays the DB error mentioned ie. Could not select the indicated database. How to resolve it? My DB name is correct plus $con variable is also not accessed in index.php while calling the function. Why is it so?
Note: The class code was in MySQL which is now depreciated. I have tried to convert it into MySQL.
index.php
require_once("ajax_table.class.php");
$obj = new ajax_table();
$records = $obj->getRecords($conn);
config.php
define ( 'DB_HOST', 'localhost' );
define ( 'DB_USER', 'root' );
define ( 'DB_PASSWORD', '' );
define ( 'DB_DB', 'stores' );
ajax_table.class.php
class ajax_table {
private $conn;
public function __construct(){
$this->$conn=$this->dbconnect();
}
private function dbconnect() {
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD,DB_DB)
or die ("<div style='color:red;'><h3>Could not connect to MySQL server</h3></div>");
return $conn;
}
function getRecords($conn){
$this->res = mysqli_query($conn,"select * from categories");
if(mysqli_num_rows($this->res)){
while($this->row = mysqli_fetch_assoc($this->res)){
$record = array_map('stripslashes', $this->row);
$this->records[] = $record;
}
return $this->records;
}
//else echo "No records found";
}
I cant see that you have included your config page into your database class?
Add this to your database class:
<?php require_once("config.php"); ?>
It looks like you have the parameters to mysqli_select_db switched. Check out this link which has the syntax and also suggests using the 4th parameter to mysqli_connect to select the database instead. As Rishi's answer noted, you're actually already doing that, so you can remove this call entirely!
Regarding the $conn variable, you are returning $conn from dbconnect, but not doing anything with it. You probably want to have a property on the class:
private $conn;
Then in dbconnect do something like:
$this->conn = $this->dbconnect();
And use $this->conn in getRecords instead of a parameter.
There are several ways you can solve this; the fundamental point is that you need the return from dbconnect to be kept somewhere and made available when you need to talk to the DB.
No need to use mysqli_select_db as you already selecting database in mysqli_connect.
Remove below line from your code
mysqli_select_db(DB_DB,$conn)
or die ("<div style='color:red;'><h3>Could not select the indicated database</h3></div>");
Warning: mysqli::query(): Couldn't fetch mysqli in C:\Program Files (x86)\EasyPHP-DevServer-13.1VC9\data\localweb\my portable files\class_EventCalendar.php on line 43
The following is my connection file:
<?php
if(!isset($_SESSION))
{
session_start();
}
// Create array to hold error messages (if any)
$ErrorMsgs = array();
// Create new mysql connection object
$DBConnect = #new mysqli("localhost","root#localhost",
NULL,"Ladle");
// Check to see if connection errno data member is not 0 (indicating an error)
if ($DBConnect->connect_errno) {
// Add error to errors array
$ErrorMsgs[]="The database server is not available.".
" Connect Error is ".$DBConnect->connect_errno." ".
$DBConnect->connect_error.".";
}
?>
This is my class:
<?php
class EventCalendar {
private $DBConnect = NULL;
function __construct() {
// Include the database connection data
include("inc_LadleDB.php");
$this->DBConnect = $DBConnect;
}
function __destruct() {
if (!$this->DBConnect->connect_error) {
$this->DBConnect->close();
}
}
function __wakeup() {
// Include the database connection data
include("inc_LadleDB.php");
$this->DBConnect = $DBConnect;
}
// Function to add events to Zodiac calendar
public function addEvent($Date, $Title, $Description) {
// Check to see if the required fields of Date and Title have been entered
if ((!empty($Date)) && (!empty($Title))) {
/* if all fields are complete then they are
inserted into the Zodiac event_calendar table */
$SQLString = "INSERT INTO tblSignUps".
" (EventDate, Title, Description) ".
" VALUES('$Date', '$Title', '".
$Description."')";
// Store query results in a variable
$QueryResult = $this->DBConnect->query($SQLString);
I'm not great with OOP PHP and I'm not sure why this error is being raised. I pulled this code from elsewhere and the only thing I changed was the #new mysqli parameters. Can anyone help me to understand what is going wrong?
Probably somewhere you have DBconnection->close(); and then some queries try to execute .
Hint: It's sometimes mistake to insert ...->close(); in __destruct() (because __destruct is event, after which there will be a need for execution of queries)
Reason of the error is wrong initialization of the mysqli object. True construction would be like this:
$DBConnect = new mysqli("localhost","root","","Ladle");
I had the same problem. I changed the localhost parameter in the mysqli object to '127.0.0.1' instead of writing 'localhost'. It worked; I’m not sure how or why.
$db_connection = new mysqli("127.0.0.1","root","","db_name");
Check if db name do not have "_" or "-"
that helps in my case
I realize this is probably super simple but i just started taking peoples advice and im converting a small program from mysql to PDO as an attempt to learn and switch to PDO.
The script is a script that shows you how to build a shopping cart, so keep in mind its focused on a learning audience like myself. Anyway i converted the old script here:
function db_connect()
{
$connection = mysql_pconnect('localhost', 'database_1', 'password');
if(!$connection)
{
return false;
}
if(!mysql_select_db('database_1'))
{
return false;
}
return $connection;
}
to this which does connect fine:
function db_connect() {
//Hostname
$hostname = 'xxx.com';
//username
$username = 'xxx';
//password
$password = 'xxx';
try {
$connection = new PDO("mysql:host=$hostname;dbname=database_1", $username, $password);
}
catch(PDOException $e){
echo $e->getMessage();
}
}
Now in other parts of the script before accessing the database it does this:
$connection = db_connect();
Now i have 2 questions. First is to help me understand better what is going on.
I understand in the original mysql function we connect to the database, if the connection is unsuccessful or the database doesnt exist it returns false. If it does connect to the database then it returns true.
With that i mind i dont understand this:
$connection = db_connect();
Isnt that just assigning true or false to the $connection variable, if so then whats going on in this part of the code.
$price = 0.00;
$connection = db_connect();
if (is_array($cart))
{
foreach($cart as $id => $qty)
{
$query = "SELECT price
FROM products
WHERE products.id = '$id' ";
$result = mysql_query($query);
if($result)
{
$item_price = mysql_result($result, 0, 'price');
$price += $item_price * $qty;
}
}
}
Instead couldn't i just create an include file with the PDO connection and no function and include that at the top of each page i run scripts on. I just don't understand where the $connection = db_connect comes in.
So the 2nd question if my above suggestion is not the answer is how do i return a boolean value from the connection function to return true or false (If i even need to)
There is one essential difference between old mysql and PDO: both these libraries require a resource variable to connect with. If you take a look at mysql_query() function definition, you will notice the second parameter, represents such a resource.
$connection variable returned by your old function by no means contain boolean value but such a resource variable. Which can be used in every mysql_query call.
But while for mysql ext this resource parameter being optional, and used automatically when not set, with PDO you have to address this resource variable explicitly. Means you cannot just call any PDO function anywhere in the code, but only as a method of existing PDO object. Means you have to make this variable available wherever you need PDO.
Thus, you need not a boolean but PDO object.
Here is the right code for the function:
function db_connect()
{
$dsn = "mysql:host=localhost;dbname=test;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
return new PDO($dsn,'root','', $opt);
}
now you can use it this way
$pdo = db_connect();
but note again - unlike with mysql_query(), you have to always use this $pdo variable for your queries.
Further reading is PDO tag wiki
As you guessed from the context, db_connect() is supposed to return the connection object. Your converted version doesn't return anything, which is a problem.
With the mysql module, you can run queries without using the connection object - this is not the case with PDO. You'll need to use the connection object to run any queries -
$result = $connection->query('SELECT * FROM foo');
First off, let me congratulate you for making the effort to learn PDO over mysql_*. You're ahead of the curve!
Now, a few things to understand:
PDO is OO, meaning the connection to the database is represented by a PDO Object.
Your db_connect() function should return the object that gets created.
Passing in the parameters required by PDO will give you more flexibility!
So what we have is:
function db_connect($dsn, $username, $password)
{
$conn = new PDO($dsn, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //This makes sure that PDO will throw PDOException objects on errors, which makes it much easier enter code hereto debug.
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //This disables emulated prepared statements by PHP, and switches to *true* prepared statements in MySQL.
return $conn; //Returns the connection object so that it may be used from the outside.
}
Now, you may have noticed we aren't checking for PDOExceptions inside of the function! That's because you can't handle the error from inside of the function correctly (becuase you don't know what you would want to do? Would you terminate the page? Redirect to an error message?). So you can only know it when you call the function.
So usage:
try {
$connection = db_connect("mysql:host=$hostname;dbname=database", "user", "pass");
}
catch (PDOException $e) {
echo "Database error! " . $e->getMessage();
}
Further Reading!
The PDO Manual entry - is super easy and super useful. I recommend you read all of it.
I am trying to pass an mysqli database connection to a php class. The code I have so far (cut down for simplicity) is as follows:
db.php
$db_host = 'localhost';
$db_name = 'dbname';
$db_user = 'username';
$db_password = 'password';
$db = array('db_host'=>$db_host,
'db_name'=>$db_name,
'db_user'=>$db_user,
'db_password'=>$db_password);
$dbCon = new mysqli( $db['db_host'],
$db['db_user'],
$db['db_password'],
$db['db_name']);
if (mysqli_connect_errno())
{
die(mysqli_connect_error()); //There was an error. Print it out and die
}
index.php
<?php
require_once($_SERVER["DOCUMENT_ROOT"] . "/db.php");
$sql = "SELECT id FROM usr_clients";
$stmt = $dbCon->prepare( $sql );
if ($stmt)
{
$stmt->execute();
$stmt->bind_result($id);
while($stmt->fetch())
{
$cl = new Client($id, $dbCon);
$cl->doIt();
}
$stmt->close();
}
?>
client.php
<?php
Class Client
{
private $con;
public static $clientCount = 0;
public function __construct( $id, $con )
{
$this->con = $con;
$sql = "SELECT id FROM usr_clients WHERE id = $id";
$stmt = $this->con->prepare( $sql );
if ($stmt)
{
echo "it worked!";
}
else
{
echo "it failed";
}
}
}
?>
Now the index.php page successfully recognises the database connection declared in db.php, and returns a list of all clients. It then loops through each client, and creates a "client" object, passing it the database connection.
It is here that the problem seems to start. In the client class, the database connection is not recognised. I get multiple errors on the page saying "it failed". In the logs, there is a line about calling prepare() on a non object.
Can anyone explain why the connection works in index.php, but not in the client class?
Thanks
Your main problem is assumptions.
You are assuming that there is no connection passed, judging by indirect consequence.
But a programmer should be always logically correct in their reasoning.
Talking of connection? Verify the very connection. var_dump($con) in the constructor. var_dump($this->con) in the method. If it fails - only now you can blame connection and start for the solution.
If not - there is no reason in looking for another connection passing method. Yet it's time to find the real problem.
If your query fails, you have to ask mysql, what's going on, using $this->con->error, as this function will provide you with a lot more useful information than simple "it fails". The right usage I've explained here: https://stackoverflow.com/a/15447204/285587