DB connection issues while converting mysql to mysqli - php

Ok so Im working to update my website to mysqli and I am having a difficulty with DB.php include for the db connection.
So my db.php looks like this.
<?php
$username="usern";
$server="server";
$password="pwd";
$database="db";
//MySQLi methods
$mysqli = new mysqli($server, $username, $password, $database) or trigger_error ( mysqli_connect_errno().mysqli_connect_error() );
?>
Note: the sql error output is for debugging Im aware that outputting sql and verbose errors is not good practice ;)
Anyways, so that works just fine.
After updating the db.php file to mysqli im having issues with all the pages that use that. Basically even with the include I get the following errors mysqli in \display_functions.php on line 21 Fatal error: Call to a member function query() on a non-object in r\includes\display_functions.php on line 21
The relevant portion of that file is:
function showConfig ($configID)
{
date_default_timezone_set('America/Denver');
require_once($_SERVER["DOCUMENT_ROOT"] . "/includes/DB.php");
$tbl_name="avr";
// Get information from DB for display
$configQuery="SELECT * FROM $tbl_name WHERE configID=$configID";
$configResult=$mysqli->query($configQuery);
<some more code>
}
When this was all mysql it worked and now it doesnt and Im not really sure why. I thought the include statement was supposed to bring in everything from the noted file but the only way to make this function (and others like it) work is by basically putting the contents of DB.php inside the function. Which is of course a terrible practice.
Also, still kind of learning all of this so forgive this ignorant question but it only became a problem with the time zone change this weekend, how would i setup the default timezone function so I dont have to put it in everything?

the $mysqli inside the function has local scope. it's not the same variable. you need to either pass $mysqli as a parameter
function showConfig ($configID, $mysqli)
or use a global declaration inside the function
function showConfig ($configID)
{
global $mysqli;

Related

Call to a member function prepare() on a non-object Error PHP mysql [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
Hello I have been finding issues in code that was working fine before
the $conn is giving error
It is a simple insert with pdo in Php
I have a connection class which works fine through i perform following operations in my file
// query
try{
$sql="INSERT INTO vup_file(filename,path,category,sub_category,user_id,comment,language,duration)
VALUES (:filename,:path,:category,:subcategory,:user_id,:comment,:language,:duration)";
global $conn;
$query=$conn->prepare($sql);
$query->execute
(array(':filename'=>$filename,':path'=>$path,':category'=>$category,':subcategory'=>$subcategory,':user_id'=>$user_id,':comment'=>$comment,':language'=>$language,':duration'=>$duration));
echo 'Success';
}catch(PDOException $e)
{
echo 'ERROR OCCURED : '.$e->getMessage();
}
}
I am getting a error of Call to a member function prepare() on a non-object in line 62
I tried to make $conn but that just didn't work
how to get rid of this error ?
As you have mentioned, you use mysql_query() in other file and it works fine.
It means you used mysql_connect().
It means you use procedure-style to connect to DB and create connection, but HERE you are trying to connect using OOP style and using connection created by mysql_connect().
It is impossible.
You need either to use OOP style to connect to DB:
$conn = new PDO('mysql:host=xxx;port=xxx;dbname=xxx', 'xxx', 'xxx', array( PDO::ATTR_PERSISTENT => false));
Or use procedure style to query DB instead of OOP-style:
mysql_query("INSERT INTO vup_file(filename,path,ca...
Procedure style is in past, now people mostly use OOP style, PDO objects.
PDO is the future, PDO is good.
And mysql_*() functions are in past, it is bad manner to write new code such way... Well it is explained here very well Why shouldn't I use mysql_* functions in PHP?
You global property $conn has not bee established correctly.
I would look back at your connection function and ensure that you have made a sucessful db connection.

Why isn't my mysqli_connect connecting? It says no hostname was specified when one is

I'm writing a simple blogging web app for my portfolio and I've come across this strange problem. I wrote a PHP script to connect to a database and read and write data to a database by RESTful calls.
I've done this before in other programs with no problems, but in this one I get an error. I wrote a simple test page to check that the RESTful calls would work before I started using them in my main app. Instead of working, I got an error back from my PHP script.
The error goes like this:
Warning: mysqli_connect() [function.mysqli-connect]: (HY000/2002): Can't connect to local MySQL server through socket '/No-MySQL-hostname-was-specified' (2) in /home/releesquirrel/storage.electricsquirrel.net/SimpleBlog/php/model_SimpleBlog.php on line 35
The code leading up to line 35 goes like this:
class model_SimpleBlog {
// Properties
// Database Info
private $serverName = "mysql.electricsquirrel.net";
private $userName = "esqrl_client";
private $userPassword = "fakepassword";
private $dbaseName = "esquirrel_simpleblog";
// Methods
public function model_SimpleBlog() {
//
}
// Load the ten latest entries after an offset
public function loadEntries($offset) {
$result = false;
// Connect to the Database Server
$connection = mysqli_connect($serverName, $userName, $userPassword, $dbaseName);
I've changed the password for privacy but that's the code that's throwing the error. I'm completely stumped. I've used code similar to this with no problems before, and I've tried googling the error code with no luck.
Does anybody know why I'm getting this error and what I can do to fix my code?
In PHP, you need to refer to object variables with $this->:
$connection = mysqli_connect($this->serverName, $this->userName, $this->userPassword, $this->dbaseName);
$serverName, for instance, looks for a variable with that name in the scope of the function. Obviously none exists.
See the manual for more information on PHP object properties.

How to access db config in a included PHP script?

I'm rewriting my application to make use of CodeIgniter. Currently I'm struggling with DB. I've configured databases in config/databases.php but have no idea how to access them in a scripts that are loaded in a traditional, non-MVC, way.
In a view login.php I have:
require_once("application/views/pages/include/membersite_config.php");
if(isset($_POST['submitted']))
{
if($fgmembersite->Login())
{
$fgmembersite->RedirectToURL("main");
}
}
in a required membersite_config.php :
require_once("fg_membersite.php");
in fg_membersite Login() leads to DBLogin() which is :
function DBLogin()
{
$this->connection = pg_connect("host=localhost port=5432 dbname=".$this->db->database." user=".$this->db->username." password=".$this->db->password."");
I receive errors:
Undefined property: FGMembersite::$db and Message: Trying to get property of non-object
Codeigniter is a MVC framework, so I'm afraid you have to folow that pattern.
Best way to do is rewrite your functions so that you can use it in a model.
Of course you can bypass it, but when you are rewriting your application, you better do it right.
By looking at your code, it seems likely that the variables you call in this piece of code have another name/location (correct me if I'm wrong):
function DBLogin()
{
$this->connection = pg_connect("host=localhost port=5432 dbname=".$this->db->database." user=".$this->db->username." password=".$this->db->password."");
Maybe instead of calling $this->db->database you need to call $this->db['database'] or something. If you supply the rest of the source code from that class we might be able to further help you.

Access denied error when using mysql_real_escape_string()

i am trying escape some data before it goes into my database, but i keep getting this error:
Warning: mysql_real_escape_string(): Access denied for user
Now this would usually suggest that i have not connected to the database (it also states (using password: NO)).
I was a little confused by this because when connecting to a database i have a 'die' clause so if it fails to connect i get told about it. So i tested this theory by running a simple query in the same function that im trying to escape the data and it works just fine.
So why on earth won't the escape method work or get a connection to the database. I did notice that the user the error states is not the user i use to access the database its something like 'www-data#localhost'. Could it be trying to log in with a different user, if so why and how? Because i another area of my website the escape function works just fine and i didn't do anything special to make it work, just added the code into my web page.
thanks for the help.
Are there any other ways of sanitizing my code?
Okay, so here we go, when the user submits the form, i use AJAX to collect the data and put it into an obj to post(JSON encoding) it to the first PHP script which is here:
http://codepad.org/kGPljN4I
This script checks all the data is there and then calls a function to add it to the database
this Mysql class is called to escape the data and then add a new record to the database, when and instance of the class is made it makes a connection to the database:
http://codepad.org/wwGNrTJm
The third file is for constants, it holds the information for the database like pass, user and so on:
http://codepad.org/dl0QQbi9
any better?
thanks again for the help.
The problem is that you have established your connection using MySQLi, but are then calling mysql_real_escape_string(). You intend to be calling mysqli_real_escape_string() either in procedural context, or object oriented contex.
class Mysql
{
private $conn;
function __construct()
{
$this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
die('No Connection to database!');
}
function add_non_member($data)
{
$email = $data->email;
// Procedural call
$san_email = mysqli_real_escape_string($this->conn, $email);
// Or OO call (recommended)
$san_email = $this->conn->real_escape_string($email);
// etc...
}
// etc...;
}
You're mixing ext/mysqli
$this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME
with ext/mysql functions:
$san_email = mysql_real_escape_string($email);
that last line should be
$san_email = $this->conn->real_escape_string($email);
I also got this access denied warning and I was able to find the solution. The problem is that I have not setup mysql db connection before calling mysql_real_escape_string function.
Solution:
Call mysql_connect($host, $user, $password) first (Or you can call your database connect function)
Then use mysql_real_escape_string($var)

Pass adodb connection to new php object

I'm trying to pass through an adodb connection to a class constructor but in doing so get this error:
mysql_error(): supplied argument is not a valid MySQL-Link resource
So to put it into context, I have instantiated a new adodb connection like this:
// establish database connection
$db = ADONewConnection($dsn);
if (!$db) die(mysql_error());
Then created my new user access object and passed in the adodb connection like this:
$user = new UserAccess($db);
This is the constructor from the user access class:
function UserAccess($oDbLink) {
// check we have a valid connection
}
Any ideas what I'm doing wrong?
Thanks,
Gaz
I can't see any obvious error in the part of code you supplied, so I'd suggest you:
leave aside the object for the time being
set your error_reporting() to E_ALL
double-check the parameters in $dsn - you may want to try to connect from the command line...
check your access privileges and run FLUSH PRIVILEGES
turn on ADODb debugging with $db->debug = TRUE;
test the thing from outside the object with a $db->Execute("SELECT * FROM tablename") or die($db->ErrorMsg());
When you get a message your connection resource is not a valid link - well, that's usually true. Don't forget to check the database is actually there and running.
The problem is most likely that you're attempting to use PHP's mysql_* functions with the $db object you get from ADONewConnection. It's not a mysql handle, so it won't work with those functions - you need to use adodb's own stuff.
Nothing wrong with your code, from what you've supplied. If you supply something more full then may be able to help.
Is there a real reason for passing a ADODB connection around? It'll just need to be passed everywhere and more work and without a real reason... I'd hesitate to do that. Even a standard global may be better (yes globals are evil) or perhaps a Singleton class?
Your code should be like this:
// establish database connection
$db = ADONewConnection($dsn);
if ( ! $db )
{
// just display error message
// you cannot use mysql_error, since you haven't connected to any database
die ("Cannot connect, check the parameter and make sure db is running!");
}
User reference, to avoid copying object
function UserAccess(&$oDbLink) {
// check we have a valid connection
}
Hope it help.
Thanks for your answers, I've managed to get this working by removing the $dsn variable and just passing in $_GLOBAL variables

Categories