A Join using MySQLi shows error - php

I have a script that is supposed to read from the database and return an array which is used by another function to display a table. However the function is throwing an error.
Fatal error: Call to a member function fetch_array() on a non-object in C:\xampp\htdocs\nu\userClass.php on line 205
I don't know what could be the error because I have already created an object for the MySQLi class. Here is my code
function getUser($user_id)
{
require("config.php");
//TODO Clean variables
$dbc = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query2 = "SELECT family.Position, food.Meal "."FROM family, food "."WHERE family.Position = food.Position";
$result = $dbc->query($query2);
$row = $result->fetch_array();
/* close connection */
$dbc->close();
return $row;
}

This error message seems to say that you have an error in your SQL query.
Try replacing the call to $dbc->query() by the following lines :
$result = $dbc->query($query2);
if ($result === false) {
echo 'MySQL error: ' . $dbc->error;
}
This will show you a more detailed error message.

Related

Error passing mysql connection as parameter

I'm trying to build a basic API with PHP and mysql and depending on the url path, different database tables are used and therefore the connection needs to be made. But I keep getting this error:
Fatal error: Call to a member function prepare() on a non-object
in....line 6
dashboard.class.php:
class dashboard {
public function getData($conn) {
// Get latest status
$stmt = $conn->prepare("SELECT status FROM status_archive ORDER BY datetime DESC LIMIT 1 ");
$stmt->execute(); //line 6
$stmt->bind_result($status);
$stmt->fetch();
($status == '1' ? $status = 'up' : $status = 'down');
$stmt->close();
return $status;
}
}
Function that creates the database connection:
function db_connection($type) {
$db = $type.'_db';
syslog(LOG_INFO, 'DB: '.$db);
// Check to see if a development or production server is being used
if (strpos(getenv('SERVER_SOFTWARE'), 'Development') === false) {
$conn = mysqli_connect(null,
getenv('PRODUCTION_DB_USERNAME'),
getenv('PRODUCTION_DB_PASSWORD'),
$db,
null,
getenv('PRODUCTION_CLOUD_SQL_INSTANCE'));
} else {
$conn = mysqli_connect(getenv('DEVELOPMENT_DB_HOST'),
getenv('DEVELOPMENT_DB_USERNAME'),
getenv('DEVELOPMENT_DB_PASSWORD'),
$db);
}
// Check if successful connection to database
if ($conn->connect_error) {
die("Could not connect to database: $conn->connect_error " .
"[$conn->connect_errno]");
}
return $conn;
}
This is the code at the end of the file that initiates everything:
$path_array = explode("/", parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH));
$conn = db_connection($path_array[3]);
include 'classes/dashboard.class.php';
$dashboard = new dashboard;
$results = $dashboard->getData($conn);
echo json_encode($results, JSON_PRETTY_PRINT);
mysqli_connect can to return falsy value.
You should use OOP style (new mysqli) or check $conn:
$conn = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
if (!$conn) {
die('Connection error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
php.net - See "Procedural style" example.
It turned out it was due to variable scope.
I ended up using PHP $GLOBALS to get it to work.

mysqli connection and query

I am new to mysqli and was going through a tutorial from: http://www.binpress.com/tutorial/using-php-with-mysql-the-right-way/17#comment1
I was able to connect to my database using this:
$config = parse_ini_file('../config.ini');
$connection = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if($connection === false) {
die('Connection failed [' . $db->connect_error . ']');
}
echo("hello"); //this worked!
But then I tried wrapping it in a function (as discussed in the tutorial)... I saw that you call the connection function from another function... in the tutorial each function keeps getting called from another and another... and I never quite found where the initial call started from to get the domino effect of functions calling eachother.. so anyway, I tried to stop it at two just to test and teach myself.. but it's not working and I don't know why:
function db_connect() {
static $connection;
if(!isset($connection)) {
$config = parse_ini_file('../config.ini');
$connection = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
echo("hello2");
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
echo("hello1");
}
db_query("SELECT `Q1_Q`,`Q1_AnsA` FROM `Game1_RollarCoaster`"); //this didn't work :(
Well I ended up taking it out of the functions and made the code super simple (sticking with procedural instead of OOP even though a lot of tutorials use OOP - thought it was better to start this way):
<?php
$config = parse_ini_file('../config.ini');
$link = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
$query = "SELECT * FROM Game1_RollarCoaster";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)) {
echo $row[Q1_Q] . '<-- Here is your question! ' . $row[Q1_AnsA] . '<-- Here is your answer! ';
echo '<br />';
}
mysqli_free_result($result);
mysqli_close($link);
?>
Here's a simple mysqli solution for you:
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
$row = $resource->fetch_assoc();
echo "{$row['field']}";
$resource->free();
$db->close();
If you're grabbing more than one row, I do it like this:
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
With Error Handling: If there is a fatal error the script will terminate with an error message.
// ini_set('display_errors',1); // Uncomment to show errors to the end user.
if ( $db->connect_errno ) die("Database Connection Failed: ".$db->connect_error);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
if ( !$resource ) die('Database Error: '.$db->error);
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
With try/catch exception handling: This lets you deal with any errors all in one place and possibly continue execution when something fails, if that's desired.
try {
if ( $db->connect_errno ) throw new Exception("Connection Failed: ".$db->connect_error);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
if ( !$resource ) throw new Exception($db->error);
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
} catch (Exception $e) {
echo "DB Exception: ",$e->getMessage(),"\n";
}

PHP variable scope issue with mysqli

I am still learning PHP and I'm trying to get around this error I'm getting.
As per this link my code is correct, but this is my code and this is the error i'm receiving:
$con = mysqli_connect("IP","username","passowrd","dbname");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function get_demos(){
$result = mysqli_query($con,"SELECT * FROM demos");
if(!$result)
{
die("Invalid query ".mysqli_error($con));
}
return $result;
}
get_demos();
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /home/content/83/11483383/html/php/db.php on line 10
Warning: mysqli_error() expects parameter 1 to be mysqli, null given
in /home/content/83/11483383/html/php/db.php on line 13 Invalid query
What am I doing wrong?
Thanks.
You should try like,
$con = mysqli_connect("IP","username","passowrd","dbname");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function get_demos($con){
$result = mysqli_query($con,"SELECT * FROM demos");
if(!$result)
{
die("Invalid query ".mysqli_error($con));
}
return $result;
}
get_demos($con);
You are not declaring that a variable $con is already set.
Try this one
$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con, 'databse_name_here') or die ('Failed to connect to MySQL: ' . mysqli_connect_error());
function get_demos($con){
$result = mysqli_query($con,"SELECT * FROM users");
if(!$result)
{
die("Invalid query ".mysqli_error($con));
}
return $result;
}
get_demos($con);
You have to pass your connection to your function. if you don't want to do it every time you can use singleton pattern to always have it in scope.
class DBCon {
private static $_instance = null;
private function __construct() {
$_instance = mysqli_connect("IP","username","passowrd","dbname");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
public static function get() {
if(is_null(self::$_instance)) {
self::$_instance = new DBCon();
}
return self::$_instance;
}
}
and use it in your code :
function get_demos(){
$result = mysqli_query(DBCon::get(),"SELECT * FROM demos");
if(!$result)
{
die("Invalid query ".mysqli_error(DBCon::get()));
}
return $result;
}
I figured out the solution after putting the question:
$con = mysqli_connect("IP","username","passowrd","dbname");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function get_demos(){
global $con;
$result = mysqli_query($con,"SELECT * FROM demos");
if(!$result)
{
die("Invalid query ".mysqli_error($con));
}
return $result;
}
get_demos();
By adding global $con.

Using MYSQLI in seperate / distinct PHP functions

I'm transitioning from MYSQL to MYSQLI and I am in need of assistance with putting MYSQLI into separate / distinct functions.
From all the "tutorials" i have located on the web, they all have everyrything in one big long code, and not distinct / separate functions that my main scripts can call.
Eg :-
Connect to MYSQLI
Do SELECT
Exit MYSQLI
what i'm after is :-
MYSQLI.PHP
<?
function connect_mysqli()
{
$con=mysqli_connect("localhost","wrong_user","my_password","my_db");
// Check connection
if (!$con)
{
die("Connection error: " . mysqli_connect_errno();
}
// Return the connection back to where i called it ??
}
function do_query ($sql)
{
$row = $con->query("$sql")->fetch_array();
return $row;
}
function close_mysqli()
{
$mysqli->close();
}
?>
in my script i want to call :-
another.php
<?
include_once("MYSQLI.PHP");
connect_mysqli();
....
do some SELECT
do some UPDATE
close_mysqli();
?>
So far, from the error codes I am receiving, the "connection" to mysqli is not being passed to/from my other script(s)
Has anyone got a working / tested example of mysqli using functions (not just half the code) - but a working example of simple SELECT
Once i get that far, i can do the rest.
fix your include file to
/**
* #return mysqli
*/
function connect_mysqli()
{
$con = mysqli_connect("localhost","wrong_user","my_password","my_db");
// Check connection
if (!$con)
{
die("Connection error: " . mysqli_connect_errno());
}
return $con;
}
function do_query ($con, $sql)
{
$row = $con->query("$sql");
if($row) {
return $row->fetch_array();
}
return null;
}
function close_mysqli($con)
{
$con->close();
}
now you can run a script like this
include_once("MYSQLI.PHP");
$connection = connect_mysqli();
if(null !== $connection) {
print_r(do_query($connection, "SELECT * FROM yourTable"));
close_mysqli($connection);
}
but for correct handling create a connection interface and a implementation for mysqli like this
interface myConnectionClass {
function connect();
....
}
and a mysqli implementation
class myMysqlIConnection implements myConnectionClass {
function connect() {
//do more... save connection etc...
return true; //sucess
}
}
Example Demos
Scroll down there are a lot of exmaples...
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
printf("Table myCity successfully created.\n");
}
/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", $result->num_rows);
/* free result set */
$result->close();
}
/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {
/* Note, that we can't execute any functions which interact with the
server until result set was closed. All calls will return an
'out of sync' error */
if (!$mysqli->query("SET #a:='this will not work'")) {
printf("Error: %s\n", $mysqli->error);
}
$result->close();
}
$mysqli->close();
?>

mysqli fetch_object() throwing an error

Os i'm starting to use mysqli, i'm getting a little confused with how it works.
So i have a function:
function verify_payment_date()
{
$today = date("Y-m-d");
$email = $_SESSION['email'];
$result = $this->conn->query("SELECT * FROM user WHERE email=$email");
while ($row = $result->fetch_object())
{
$next_payment_date = $row['next_payment_date'];
}
}
To set up my connect i do this in the same class:
private $conn;
function __construct()
{
$this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
die('There was a problem connecting to the database.');
}
can anyone give me a helping hand here because i'm totally lost. I was basing some of the code on this website:
http://www.willfitch.com/mysqli-tutorial.html
Also the error i'm getting is:
Fatal error: Call to a member function fetch() on a non-object in /home/vhosts/tradingeliteclub.com/subdomains/test/httpdocs/FES/members/classes/Mysql.php on line 52
I'm not sure where to go from here.
Thanks for your time and help.
$result is not mysql result, your query failed. Try
$result = $this->conn->query("SELECT * FROM user WHERE email='$email'");
// apostrophes
instead.
$this->conn->query returns resource on success, false on fail. You can avoid the error this way
if($result) while ($row = $result->fetch_object())
{
$next_payment_date = $row['next_payment_date'];
}

Categories