Fatal Error Call To a member Function query() - php

I've seen some of the previous posts on here but they really don't explain what it is I'm looking for. maybe someone can point me in the right direction.
All I'm doing is a simple select statement that works on some other pages but not this one.
at the top of my page, I have the connection to my db: include 'myDBconnection.php'; just like any other page that uses it.
I'm using these to tell me what errors I have:
ini_set('display_errors', 'On');
error_reporting(E_ALL);
and they are returning this:
"Fatal error: Call to a member function query() on a non-object in /var/www/vhosts/mydomainname.com/httpdocs/somedirectory/index.php on line 16"
So, this is my simple select statement that I'm trying to just display on the page:
<?php
//just a simple select statement
if($row = $con->query("SELECT * FROM ErrorCodeTable WHERE ErrorCodeID = 100"))//this is line 16 in my code
{
$eCodeId = $row['ErrorCodeID'];
$eCode = $row['ErrorCode'];
echo $eCodeId." = ".$eCode;
}
?>
So, I'm stumped. Why is it telling me that?
Just for clarity's sake, this is my DB connection and I'm reading from an INI file.
function getConnected()
{
$file = "../myConnection.ini";
if (!$settings = parse_ini_file($file, TRUE)) throw new exception('Unable to open ' . $file . '.');
$host = $settings['connection']['default_host'];
$user = $settings['connection']['default_user'];
$paass = $settings['connection']['default_pw'];
$dbName = $settings['connection']['default_db'];
$con = 'mysqli_connect("'.$host.'", "'.$user.'", "'.$paass.'", "'.$dbName.'")';
return $con;
}
//MYSQLI CONNECTION
$con = getConnected();
//CONNECTION CHECK
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
So, why do I get the "Fatal Error" message? Did I overlook or forget something in my query?
Be gentle. :-)

Remove the single quotes around the below statement
$con = 'mysqli_connect("'.$host.'", "'.$user.'", "'.$paass.'", "'.$dbName.'")';
^ ^
By enclosing it in single quotes , your $con behaves like a string instead of a connection resource. The mysqli_connect function will never be executed.
Simply rewrite it like..
$con = mysqli_connect($host,$user,$paass,$dbName);

Related

Trouble using a reusable database connector

I'm new to php. I've been having trouble connecting to and using a data with PHP. I don't really have much information on the issue, maybe I'm using some out of date method, or I did something wrong. I've double checked and looked on this website for information, but I didn't find much. Here's the code below.
The error reads :
Fatal error: Call to a member function query() on boolean in C:\xampp\htdocs\website\Practice\mysqli\pdo.php on line 6
That would mean that there is a problem located near the
$result = $conn->query($sql)or die(mysqli_error());
I entered my username and password correctly. I even created a new username and password just to make sure. I have no other ideas why $conn isn't working, and I would love any thoughts or ideas on the issue!
connection.ini.php
function dbConnect($usertype, $connectiontype = 'pdo') {
$host = 'localhost';
$db = 'student';
if ($usertype == 'read') {
$user = 'user';
$pwd = 'pass';
}
elseif ($usertype == 'write') {
$user = 'root';
$pwd = 'password';
}
else {
exit('Unrecognized connection type');
}
//Connection Code
if ($connectionType ='mysqli') {
return new mysqli($host, $user, $pwd, $db) or die ('Cannot open database');
}
else {
try {
return new PDO('mysql:host=$host;dbname=$db, $user, $pwd');
}
catch(PDOExecption $e) {
echo 'Cannot connect to database';
exit;
}
}
}
?>
mysqli.php
?php
require_once('connection.inc.php');
$conn = dbConnect('read', 'pdo');
$sql = 'SELECT * FROM guestbook';
$result = $conn->query($sql)or die(mysqli_error());
$numRows = $result->num_rows;
?>
<!DOCTYPE html>
<html>
<p> A total of <?php
echo $numRows;
?>
records were found.</p>
</html>
Any time you get the...
"Fatal error: Call to a member function bind_param() on boolean"
...it is likely because there is an issue with your query. The prepare() might return FALSE (a Boolean), but this generic failure message doesn't leave you much in the way of clues. How do you find out what is wrong with your query? You ask!
First of all, make sure error reporting is turned on and visible: add these two lines to the top of your file(s) right after your opening <?php tag:
error_reporting(E_ALL);
ini_set('display_errors', 1);
If your error reporting has been set in the php.ini you won't have to worry about this. Just make sure you handle errors gracefully and never reveal the true cause of any issues to your users. Revealing the true cause to the public can be a gold engraved invitation for those wanting to harm your sites and servers. If you do not want to send errors to the browser you can always monitor your web server error logs. Log locations will vary from server to server e.g., on Ubuntu the error log is typically located at /var/log/apache2/error.log. If you're examining error logs in a Linux environment you can use tail -f /path/to/log in a console window to see errors as they occur in real-time....or as you make them.
Once you're squared away on standard error reporting adding error checking on your database connection and queries will give you much more detail about the problems going on. Have a look at this example where the column name is incorrect. First, the code which returns the generic fatal error message:
$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
$query = $mysqli->prepare($sql)); // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();
The error is generic and not very helpful to you in solving what is going on.
With a couple of more lines of code you can get very detailed information which you can use to solve the issue immediately. Check the prepare() statement for truthiness and if it is good you can proceed on to binding and executing.
$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
if($query = $mysqli->prepare($sql)) { // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();
// any additional code you need would go here.
} else {
$error = $mysqli->errno . ' ' . $mysqli->error;
echo $error; // 1054 Unknown column 'foo' in 'field list'
}
If something is wrong you can spit out an error message which takes you directly to the issue. In this case there is no foo column in the table, solving the problem is trivial.
If you choose, you can include this checking in a function or class and extend it by handling the errors gracefully as mentioned previously.

PHP and MySQL Nested database connection

This is a general example.
The application has 3 files.
conn.inc.php -- setting up the database connection
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "hmt";
$conn = new mysqli($db_host, $db_username, $db_pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
func.inc.php -- file including functions
<?php
function load_module($module_name){
$sqlCmd = "SELECT content FROM modules WHERE name='$module_name' LIMIT 1";
$result = $conn->query($sqlCmd);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$module_footer = $row["content"];
}
}else {
echo 'Error while loading module '.$module_name;
}
return $result;
$result->free_result();
}
?>
index.php -- the main page to display content
<?php
include 'conn.inc.php';
include 'func.inc.php';
if (!isset($_GET['page_name'])) { // if page_name is not set then reset it to the homepage
$page_name = 'module_footer';
}else{
$page_name = $_GET['module_footer'];
}
$module_content = load_module($page_name);
echo $module_content;
?>
Now my goal was to include functions inside the func.inc.php file and database into conn.inc.php, so as to keep separate and easier to read in the future.
My problem now is that the $conn variable declared in conn.inc.php cannot be used inside the function and it can't get my head around how to use it. I even tried using GLOBALS with no success.
The error for the files is this:
Notice: Undefined variable: conn in ./func.inc.php on line 4
Fatal error: Call to a member function query() on a non-object in ./func.inc.php on line 4
Which (I assume) is because the $conn variable is not in a global scope.
Now my question is. How can I keep the nested files but have the functions working? Is there a mistake in my approach or is it not possible to use a nested call to a mysql object?
Eventually you'll want to get into object-oriented coding but for now lets make what you have a little prettier.
When including files, you'll want to avoid things like global variables. They sound great, but end up being a pain when handling scope. So instead include a set of functions to call.
conn.inc.php
function getConnection(){
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "hmt";
$conn = new mysqli($db_host, $db_username, $db_pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
Then function.inc.php
<?php
function load_module($module_name){
$sqlCmd = "SELECT content FROM modules WHERE name='$module_name' LIMIT 1";
//Here is where we get our database connection.
$conn = getConnection();
$result = $conn->query($sqlCmd);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$module_footer = $row["content"];
}
}else {
echo 'Error while loading module '.$module_name;
}
return $result;
$result->free_result();
}
And finally finish up with your index page the way it is. So now, any page that wants a database connection will need to include the conn.inc.php and simply call getConnection() to get a mysqli connection object.
Think of your program as being a series of individual functions working together. And eventually you'll get to it being a series of objects working together. Nothing should be just floating off in global space. Try to encapsulate everything in some sort of function or object to be called over and over with consistent results.
You'd have to do something like this:
$conn = '';
function connect() {
global $conn;
... do db stuff
}
But this is usually bad practice. A more common method is to use a singleton object to "carry" your db handle, and you new that singleton everywhere you need to do DB operations.
function do_something() {
$conn = new DBSingleton();
... do db stuff
}

Database Connectivity in PHP - unexpected error

Following is my piece of code in which I am trying to create database connectivity. Please see the comments below in the code in which I mentioned where exactly the problem is occurring. Moreover, I also mentioned one connectivity code that is working fine.
Please let me know how I can call my dbconfig.php so it'll behave like that piece of code that results to successful connection.
Thanks
<?php
//Including Header file for the connectivity to the database
require_once('Connections/dbconfig.php');
mysql_select_db($database_dbconfig, $dbconfig);
// If I use the following line of code for connectivity then it works perfectly fine:
//$dbh = new PDO('mysql:host=localhost;dbname=rare','root','');
$dbh= $dbconfig;
$q = 'select resident_id,u_first,u_last from z_events group by resident_id';
/*
The following error will occur when I try to make a connection from the header file:
Fatal error: Call to a member function prepare() on a non-object in C:\Users\QAD\Downloads\CAR\index12 - Copy.php on line 200
*/
$user = $dbh->prepare($q);
$user->execute();
?>
dbconfig.php
<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_dbconfig = "localhost";
$database_dbconfig = "rare";
$username_dbconfig = "root";
$password_dbconfig = "";
$dbconfig = mysql_pconnect($hostname_dbconfig, $username_dbconfig, $password_dbconfig) or trigger_error(mysql_error(),E_USER_ERROR);
?>
You are mixing mysql_* functions with PDO functions - first connecting to your database using mysql_connect and then using prepare() to query your database.
You should move to PDO completely, replace this line:
$dbconfig = mysql_pconnect($hostname_dbconfig, $username_dbconfig, $password_dbconfig) or trigger_error(mysql_error(),E_USER_ERROR);
With this one:
$dbconfig = new PDO('mysql:dbname=' . $database_dbconfig . ';host=127.0.0.1', $username_dbconfig, $password_dbconfig);
And put this in your other file:
<?php
//Including Header file for the conectivity to the database
require_once('Connections/dbconfig.php');
$dbh = $dbconfig;
$q = 'select resident_id,u_first,u_last from z_events group by resident_id';
$user = $dbh->prepare($q);
$user->execute();
?>
Try This
$connection = mysql_connect("localhost","root","") or die(mysql_error());
$db = mysql_select_db("database_name") or die(mysql_error());
change your database selection into this
mysql_select_db($database_dbconfig);

PHP Windows require_once ignored

My problem is,
This is the file that is being included ,
<?php
$dbhost = "localhost";
$dbuser = "****";
$dbpass = "***";
$dbname = "****";
$MYSQL_ERRNO = "";
$MYSQL_ERROR = "";
// Connect To Database
function db_connect() {
global $dbhost, $dbuser, $dbpass, $dbname;
global $MYSQL_ERRNO, $MYSQL_ERROR;
$link_id = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$link_id) {
$MYSQL_ERRNO = 0;
$MYSQL_ERROR = "Connection failed to $dbhost.";
return 0;
}
else if(!mysql_select_db($dbname)) {
$MYSQL_ERRNO = mysql_errno();
$MYSQL_ERROR = mysql_error();
return 0;
}
else return $link_id;
}
?>
The main file has the following code to make db connection ,
<?php
require_once 'file.php';
$link_id = db_connect($dbname);
......
?>
But i got function undefined error.
Using Apache in Windows with PHP 5.3
1) Check relative paths for your includes.
2) Just because the PHP documentation says you can use require_once without parenthesis doesn't mean you should. Stay consistent, use require_once("file.php");.
3) Be consistent with curly braces in your function. You're missing one or two up there. I'd like to know if you rewrite your function the following way if it works:
function db_connect() {
global $dbhost, $dbuser, $dbpass, $dbname, $MYSQL_ERRNO, $MYSQL_ERROR;
$link_id = mysql_connect($dbhost, $dbuser, $dbpass);
if ($link_id === false) {
$MYSQL_ERRNO = 0;
$MYSQL_ERROR = "Connection failed to $dbhost.";
return 0;
} elseif (mysql_select_db($dbname) === false) {
$MYSQL_ERRNO = mysql_errno();
$MYSQL_ERROR = mysql_error();
return 0;
} else {
return $link_id;
}
}
And remember, checking your web server error logs usually helps.
Edit:
According to the comments for this answer, you're not including the file you think you are. Use an absolute path for the include so you're 100% sure of the file being included.
A logic.
Sometimes we need it.
Let's sort out your case.
you can see whatever "function undefined error." (Although I'd prefer literal and exact PHP error messages as they contain A LOT of useful information, let's assume it's regular PHP error thrown right in this place).
We can conclude from the (1) that you can see alll errors occurred.
So, from (2) we can tell the if there was a file not found error, you'd be notified of it.
So, we can assume from (3) that there is no error and file being included correctly.
What's next?
The most possible reason for you getting this error is the wrong code you posted here.
For example, if you include your file not as file.php but as http://example.com/file.php the result will be exactly as described.
Or there can be 2 files named 'file.php', one contains the function definition and another without it.
Or there can be a typo in the function's name as well.
So, you just have to double check your names and print some debugging info to be sure you are including the right file and calling the right function.

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result [duplicate]

This question already has answers here:
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
(31 answers)
Closed 11 months ago.
I get the error when trying to run this:
<?php
require_once('includes/DbConnector.php');
$connector = new DbConnector();
$result = $connector->query('SELECT title,content FROM staff_vacancies ORDER BY ordering LIMIT 0,100');
// Get an array containing the results.
// Loop for each item in that array
while ($row = $connector->fetchArray($result)){
echo $row['title'].'</h3>';
echo $row['content'];
}
?>
I have a linked file: DbConnector.php:
<?php
////////////////////////////////////////////////////////////////////////////////////////
// Class: DbConnector
// Purpose: Connect to a database, MySQL version
///////////////////////////////////////////////////////////////////////////////////////
require_once 'SystemComponent.php';
class DbConnector extends SystemComponent {
var $theQuery;
var $link;
//*** Function: DbConnector, Purpose: Connect to the database ***
function DbConnector(){
// Load settings from parent class
$settings = SystemComponent::getSettings();
// Get the main settings from the array we just loaded
$host = $settings['dbhost'];
$db = $settings['dbname'];
$user = $settings['dbusername'];
$pass = $settings['dbpassword'];
//the settings
$host = 'localhost';
$db = 'xxx';
$user = 'xxx';
$pass = 'xxx';
// Connect to the database
$this->link = mysql_connect($host, $user, $pass);
mysql_select_db($db);
register_shutdown_function(array(&$this, 'close'));
}
//*** Function: query, Purpose: Execute a database query ***
function query($query) {
$this->theQuery = $query;
return mysql_query($query, $this->link);
}
//*** Function: getQuery, Purpose: Returns the last database query, for debugging ***
function getQuery() {
return $this->theQuery;
}
//*** Function: getNumRows, Purpose: Return row count, MySQL version ***
function getNumRows($result) {
return mysql_num_rows($result);
}
//*** Function: fetchArray, Purpose: Get array of query results ***
function fetchArray($result) {
return mysql_fetch_array($result);
}
//*** Function: close, Purpose: Close the connection ***
function close() {
mysql_close($this->link);
}
}
?>
Does anyone know what the problem is?
Your query must have a problem which is causing $result to be an invalid resource.
Try checking for mysql_error() after the line on which you run your query.
Edit:
In fact, I would alter your DBConnector class function query() to something like the following, so that an identifiable error is thrown when you have a bad query:
function query($query) {
$this->theQuery = $query;
$queryId = mysql_query($query,$this->link);
if (! $queryId) {
throw new Exception(mysql_error().". Query was:\n\n".$query."\n\nError number: ".mysql_errno();
}
return $queryId;
}
I find this in a post, to me solved my problem.
Slds.
Yeah, Answer is simple, the query used is not a true result as it's a query inside of a getrow so to speak..
Here is the fix:
Find all lines that look like this:
mysql_fetch_array(mysql_query("...snip...";-) );
And just add a "#" in front of it so it looks like this:
#mysql_fetch_array(mysql_query("...snip...";-) );
Then do the same thing for the following lines..
Code:
mysql_num_rows(mysql_query("...snip...";-) );
Perform the same steps as above by adding the "#" to it so it looks like this:
#mysql_num_rows(mysql_query("...snip...";-) );
All this does it say "While doing xxx within yyy" Otherwise, it's dead due to missing result value. It's a PHP thing..
Works like a charm, took me 5 mins to rip the whole code apart and slap it all into Modernbill, Shares the same database and works perfectly for me.
This error means your query failed. mysql_query() returns false if an error occurred, you are then passing false to mysql_fetch_array() which is triggering the error message.
Your query could be failing due to a missing/wrong table or field. To see the detailed error, print out the result of mysql_error().
The mysql_* library is deprecated. It is recommended to upgrade to MySQLi or PDO.
// Load settings from parent class
$settings = SystemComponent::getSettings();
// Get the main settings from the array we just loaded
$host = $settings['dbhost'];
$db = $settings['dbname'];
$user = $settings['dbusername'];
$pass = $settings['dbpassword'];
//the settings
$host = 'localhost';
$db = 'xxx';
$user = 'xxx';
$pass = 'xxx';
Did you mean to reassign the connection vars? OR was that a few lines of stub code you forgot to take out? Or just an example to show what $settings contains?
Please provide the error from mysql_error(). Without that I can only guess... try escaping your field names?
$result = $connector->query('SELECT `title`,`content` FROM `staff_vacancies` ORDER BY `ordering` LIMIT 0,100');
Your query must have a problem which is causing $result to be an invalid resource.
Use this
<?php
require_once('includes/DbConnector.php');
$connector = new DbConnector();
$result = $connector->query('SELECT title,content FROM staff_vacancies ORDER BY ordering LIMIT 0,100');
// Get an array containing the results.
// Loop for each item in that array
if($result){
while ($row = $connector->fetchArray($result)){
echo $row['title'].'</h3>';
echo $row['content'];
}
}
?>

Categories