Warning: mysql_close(): 4 is not a valid MySQL-Link resourc - php

Friends please help me out here
My Config File config.php
**<?php
define('DB_SERVER', 'localhost'); // Mysql hostname, usually localhost
define('DB_USERNAME', 'gani'); // Mysql username
define('DB_PASSWORD', 'gani'); // Mysql password
define('DB_DATABASE', 'gani'); // Mysql database name
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());
?>
My php file
**function instcount($updateid,$position)
{
include "config.php";
global $connection;
$sel=mysql_query("select * from register where regid='$updateid'");
$getcount=mysql_num_rows($sel);
$rowss=mysql_fetch_array($sel);
//print_r($rowss);
if($getcount==0)
{
$insert=mysql_query("insert into register (regid,dtentered) values ('$updateid',CURDATE())");
}
else
{
$update=mysql_query("update dailycount set net=100 where regid='$updateid'");
}
$selw=mysql_query("select sid,position from register where regid='$updateid'");
$rowd=mysql_fetch_array($selw);
if($rowd['sid']!='admin' && $rowd['sid']!="")
{
instcount($rowd['sid'],$rowd['position']);
}
//return 0;
mysql_close($connection);
}
$updated="10000";
$upfun=instcount($updated,$position);**
When i run above script I am getting below error
Warning: mysql_close(): 4 is not a valid MySQL-Link resource
Any one please help me out....

The problem is the
global $connection;
line of the code. You include the file within the function and according to php manual on include:
When a file is included, the code it contains inherits the variable
scope of the line on which the include occurs.
This means, that the $connection variable becomes a local variable, since the include is within the function.
Either move the include out of the function or delete the global $connection; line from your code.

Related

Trying to connect from iOS to MySQL Database using php ( HTTP POST )

Below is my sample code for my PHP program, and my database has already been created.
createteam.php:
<?php
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//getting values
$teamName = $_POST['name'];
$memberCount = $_POST['member'];
//including the db operation file
require_once '../includes/DbOperation.php';
$db = new DbOperation();
//inserting values
if($db->createTeam($teamName,$memberCount)){
$response['error']=false;
$response['message']='Team added successfully';
}else{
$response['error']=true;
$response['message']='Could not add team';
}
}else{
$response['error']=true;
$response['message']='You are not authorized';
}
echo json_encode($response);
config.php:
<?php
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('DB_NAME', 'iphone');
DbConnect.php:
<?php
class DbConnect
{
private $conn;
function __construct()
{
}
/**
* Establishing database connection
* #return database connection handler
*/
function connect()
{
require_once 'Config.php';
// Connecting to mysql database
$this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check for database connection error
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// returing connection resource
return $this->conn;
}
}
DbOperation.php:
<?php
class DbOperation
{
private $conn;
function __construct()
{
require_once dirname(__FILE__) . '/Config.php';
require_once dirname(__FILE__) . '/DbConnect.php';
// opening db connection
$db = new DbConnect();
$this->conn = $db->connect();
}
//Function to create a new user
public function createTeam($name, $memberCount)
{
$stmt = $this->conn->prepare("INSERT INTO team(name, member) values(?, ?)");
$stmt->bind_param("si", $name, $memberCount);
$result = $stmt->execute();
$stmt->close();
if ($result) {
return true;
} else {
return false;
}
}
}
However when I use HTTP POST method using Postman in Chrome, it states this
Notice: Undefined index: name in D:\xampp\htdocs\TestServ\api\createteam.php on line 9
Notice: Undefined index: member in D:\xampp\htdocs\TestServ\api\createteam.php on line 10
Warning: mysqli::__construct(): (HY000/1049): Unknown database 'iphone' in D:\xampp\htdocs\TestServ\includes\DbConnect.php on line 20
Failed to connect to MySQL: Unknown database 'iphone'
Warning: mysqli::prepare(): Couldn't fetch mysqli in D:\xampp\htdocs\TestServ\includes\DbOperation.php on line 20
Fatal error: Uncaught Error: Call to a member function bind_param() on null in D:\xampp\htdocs\TestServ\includes\DbOperation.php:21 Stack trace: #0 D:\xampp\htdocs\TestServ\api\createteam.php(18): DbOperation->createTeam(NULL, NULL) #1 {main} thrown in D:\xampp\htdocs\TestServ\includes\DbOperation.php on line 21
What does this mean, and what should I change?
Your first two errors are caused because of these two lines:
$teamName = $_POST['name'];
$memberCount = $_POST['member'];
The error (Undefined index) tells you that you have some non-existing variables, in this case name and member from your $_POST[] variable. Make sure your POST request is correctly made, see undefined variable for more information.
Your third error (Warning: mysqli::__construct(): (HY000/1049)) is caused because there isn't a database called iphone in your database system. Check if you have typed it correctly or if you haven't yet created an actual database with the name iphone.
The last error is caused because of the first two errors, since name and member aren't (correctly) defined in your POST request they have been set to NULL and the mysqli library doesn't like that.

Warning: mysqli_query(): Couldn't fetch mysqli in <file> on line <number>

The view file
<?php
require('OrderModel.php');
session_start();
if(!isset($_SESSION['orderModel'])){
$newModel = new OrderModel();
$_SESSION['orderModel'] = $newModel;
} else{
$newModel = $_SESSION['orderModel'];
}
$newModel->addToBasket(1, 30);
echo $newModel->getItemName($newModel->basket[0][0]);
?>
The OrderModel file (simplified)
class OrderModel{
public $basket;
public $orderDate;
public $orderTime;
public $sent;
public $dbc;
public $customerOrderID;
public function __construct()
{
$this->dbc = require_once('../../db/config.php');
$this->basket = [];
}
public function addToBasket($itemNumber, $itemQuantity){
array_push($this->basket, [$itemNumber, $itemQuantity]);
}
public function getItemName($itemNum){
$query = "SELECT ItemName FROM item WHERE ItemID = $itemNum;";
$r = mysqli_query($this->dbc, $query); //Line 31
if($r){
return mysqli_fetch_row($r)[0];
}else{
echo mysqli_error($this->dbc); //Line 35
}
}
I can confirm that the config.php file is definitely configured correctly and is talking to the DB. In any rate, the code is:
<?php
define ('username', 'root');
define ('password', 'root');
define ('server', '127.0.0.1');
define ('database', 'alberto');
$dbc = mysqli_connect(server, username, password, database) OR DIE ('Could not connect to MySQL: ' . mysqli_connect_error());
mysqli_set_charset($dbc, 'utf8');
return $dbc;
?>
I am getting the following error messages from the view file:
Warning: mysqli_query(): Couldn't fetch mysqli in D:\UniServerZ\www\alberto\app\models\OrderModel.php on line 31
Warning: mysqli_error(): Couldn't fetch mysqli in D:\UniServerZ\www\alberto\app\models\OrderModel.php on line 35
I suspect the error is to do with the session, but I can't seem to find any answers from the threads posted so far.
Please kindly advise. Thank you.
Barmar is correct that $this->dbc is not a valid mysqli object. You are using the require_once with the file like a function. Make the config.php a class, and make the db connection from there. See here for an example of what I'm referring to. https://gist.github.com/jonashansen229/4534794

Getting error while trying to call a function located in included file with mysqli from a file? [duplicate]

This question already has answers here:
error in calling same function twice in php
(2 answers)
Closed 2 years ago.
I have been trying to assign a function for to call site title from database so the function while called at it's assigning page as functions.php gives the exact data what I need i.e it outputs the data from database but now getting error while trying to call the same function in index.php and I included the function file already but it gives me a common error message as so (please need help) :
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in D:\xampp\htdocs\php-login-new\config\functions.php on line 15
while my functions.php file is as :
<?php
error_reporting(E_ALL ^ E_NOTICE);
require_once('config.php');
function site_title() {
global $mysqli;
$query = "SELECT * FROM settings";
$fetch = mysqli_query($mysqli,$query) or die(mysql_error());
$row = mysqli_fetch_array($fetch);
$site_name=$row['site_name'];
echo $site_name;
}
?>
while my config.php file for mysqli connection is as :
<?php
/* Database config */
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_database = 'login';
/* End config */
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
and here goes the index.php file :
<?php
include('config/functions.php');
site_title();
?>
Really what I was doing wrong is that I was calling the mysqli connection file as require_once('config/config.php');
it worked fine when changed the
require_once
function to
include('config/config.php');
Thanks to #Fred And #user3791372 for pointing out too.

undefined constant DB_SERVER - assumed 'DB_SERVER'

I have installed WAMP server on my local machine and I have written php script to insert record into the database, but I'm getting the following error-
Notice: Use of undefined constant DB_SERVER - assumed 'DB_SERVER' in C:\wamp\www\test_services\db_connect.php on line 32
following is my db_config code
<?php 
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password
define('DB_DATABASE', "test_db"); // database name
define('DB_SERVER', "localhost"); // db server
?>
Here is my **db_connect.php code**
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT
{
// constructor
function __construct()
{
// connecting to database
$this->connect();
}
// destructor
function __destruct()
{
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect()
{
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
// Selecing database
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close()
{
// closing db connection
mysql_close();
}
}
?>
Please help.. Thank you..!
I don't think you are showing the correct file. The problem is in db_connect.php. It is very likely that that file does not include db_config.php, i.e:
require_once 'path/to/db_config.php';
Edit: Does db_config.php actually live in the same directory as db_connect.php? Your code suggests that it does, which may be incorrect?
Edit: What happens if you put $var = 'hello' in db_config.php, and then print $var in db_connect.php after you include it, do you see 'hello'? Just to clarify you are connecting with the file..

Android app connect with MySql not working

I just created an android app in which app is connected with MySql through PHP files.. I did according to this tutorial this
But I am able to connect when igave localhost address when i gave my server address it is not working .. The following is db_connect .. i didnt make any change
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
// Selecing database
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}
}
?>
db_config.php
<?php
/*
* All database connection variables
*/
define('DB_USER', "root");
// db user
define('DB_PASSWORD', "");
// db password (mention your db password here)
define('DB_DATABASE', "androidhive");
// database name
define('DB_SERVER', "localhost"); // db server
?>
this is the link i uploaded my file...
Warning: mysql_connect() [function.mysql-connect]: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) in /home/content/96/11645896/html/app/db_connect.php on line 28
Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
Warning: mysql_close(): no MySQL-Link resource supplied in /home/content/96/11645896/html/app/db_connect.php on line 42
but message came like this... what I have to do...
You need to give a server address of your own.. Instead of androidhive's and give the username and password of that particular server.. and edit the db_config.php file according to that.. then try to connect..
Check your db credentials and make sure mysqld is running. Try this /etc/init.d/mysql status or http://www.cyberciti.biz/faq/how-to-find-out-if-mysql-is-running-on-linux/ to know if MySQL is up.

Categories