PHP variable scope issue with mysqli - php

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.

Related

Warning: mysqli_query(): Couldn't fetch mysqli in my code

I know this question has been asked many times , I tried lot of other answers but it didn't work for me
Here is my class
<?php
class saveexceltodb
{
var $inputFileName;
var $tableName;
var $conn;
var $allDataInSheet;
var $arrayCount;
/**
* Create a new PHPExcel with one Worksheet
*/
public function __construct($table=0)
{
$this->initiatedb();
}
private function initiatedb(){
//var_dump($allDataInSheet);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "xyx";
// Create connection
$this->conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$this->conn) {
die("Connection failed: " . mysqli_connect_error());
}
}
public function updateIntermidiate(){
$allocationeventwise=array();
mysqli_query($this->conn,"DELETE FROM `allocationeventwise` WHERE 1");
$sql = "INSERT INTO `allocationeventwise` (`empid`, `event1`, `event2`, `event3`, `event4`, `event5` `event6`, `event7`) VALUES ";
$result = mysqli_query($this->conn, "SELECT usdeal.empid , usdeal.event1 , usdeal.event2, usdeal.event3, usdeal.event4, usdeal.event5, usdeal.event6, usdeal.event7 , salary.salary from usdeal INNER JOIN salary ON usdeal.empid = salary.empid where usdeal.allocated=0");
$i=0;
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$i++;
$totaleventDays = $row["event1"]+$row["event2"]+$row["event3"]+$row["event4"]+$row["event5"]+$row["event6"]+$row["event7"];
$allocationeventwise[$row["empid"]]['event1']=($row['salary']/$totaleventDays)*$row["event1"];
$allocationeventwise[$row["empid"]]['event2']=($row['salary']/$totaleventDays)*$row["event2"];
$allocationeventwise[$row["empid"]]['event3']=($row['salary']/$totaleventDays)*$row["event3"];
$allocationeventwise[$row["empid"]]['event4']=($row['salary']/$totaleventDays)*$row["event4"];
$allocationeventwise[$row["empid"]]['event5']=($row['salary']/$totaleventDays)*$row["event5"];
$allocationeventwise[$row["empid"]]['event6']=($row['salary']/$totaleventDays)*$row["event6"];
$allocationeventwise[$row["empid"]]['event7']=($row['salary']/$totaleventDays)*$row["event7"];
$sql .='("'.$row["empid"].'",
'.$allocationeventwise[$row["empid"]]["event1"].',
'.$allocationeventwise[$row["empid"]]["event2"].',
'.$allocationeventwise[$row["empid"]]["event3"].',
'.$allocationeventwise[$row["empid"]]["event4"].',
'.$allocationeventwise[$row["empid"]]["event5"].',
'.$allocationeventwise[$row["empid"]]["event6"].',
'.$allocationeventwise[$row["empid"]]["event7"].',)';
if($i<mysqli_num_rows($result))
$sql .=",";
else
$sql .=";";
}
echo $sql;
if (mysqli_query($this->conn, $sql)) {
echo "New record created successfully<br/>";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($this->conn);
}
} else {
echo "0 results";
}
}
}
When I use it like this
include('saveexceltodb.php');
$obj = new saveexceltodb(0);
$obj->updateIntermidiate();
I get following error .
Warning: mysqli_query(): Couldn't fetch mysqli in C:\xampp\htdocs\import-excel\saveexceltodb.php
You should follow below steps
Check database connection
Check query syntax
You have to pass connection object in mysqli_query function in you case it is ' $this->conn '
Hope, It may help you.

Change code to link mySQL into a function

I'm new to php. I have this piece of code:
<?php
if (!isset($_GET['id'])) {
die("missing query parameter");
}
$id = intval($_GET['id']);
if ($id === '') {
die("Invalid query parameter");
}
$db = mysql_connect("localhost", "root", "usbw");
$sdb = mysql_select_db("test", $db);
$sql = "SELECT * FROM config WHERE id=$id";
$mq = mysql_query($sql) or die("not working query");
$row = mysql_fetch_array($mq);
?>
And from this code, I want to make a function, but how?
What I'm trying to do is linking my MySQL database to my PHP code, and I also try to use the GET[id] to auto change my page if a change my id.
This piece of code does work, but I want to change it into a function. But I don't know how to start.
Here's an example of a function around your query, mind you it's just an example, as there are many improvements to make.
Such as not using the mysql_* api and moving towards PDO or mysqli_*
But it should be enough to get you started
<?php
// your if logic stays unchanged
$db=mysql_connect("localhost","root","usbw");
$sdb=mysql_select_db("test",$db);
function getConfig($id,$db){
$sql="SELECT * FROM config WHERE id=$id";
$mq=mysql_query($sql);
if ($mq) {
return mysql_fetch_array($mq);
}
else {
return false;
}
}
$results = getConfig($id,$db);
if ($results==false) {
print "the query failed";
}
else var_dump($results);
You can make a file named db.php including some common db functions so you will be able to use them easier:
<?php
function db_connection() {
//SERVER, USER, MY_PASSWORD, MY_DATABASE are constants
$connection = mysqli_connect(SERVER, USER, MY_PASSWORD, MY_DATABASE);
mysqli_set_charset($connection, 'utf8');
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
return $connection;
}
function db_selection() {
$db_select = mysqli_select_db(MY_DATABASE, db_connection());
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
return $db_select;
}
function confirm_query($connection, $result_set) {
if (!$result_set) {
die("Database error: " . mysqli_error($connection));
}
}
function q($connection, $query) {
$result = mysqli_query($connection, $query);
confirm_query($connection, $result);
return $result;
}
?>
Then, you can have your code in some other files:
<?php
require_once('db.php'); //This file is required
$id = $_GET['id']; //Shorthand the $_GET['id'] variable
if (!isset($id)) {
die("missing query parameter");
}
if ( filter_var($id, FILTER_VALIDATE_INT) === false) ) {
die("Invalid query parameter");
}
$sql = "SELECT * FROM config WHERE id = '$id'";
$result = q($connection, $sql);
while ($row = mysqli_fetch_array($result)) {
//Do something
}
?>
Try not to use mysql_* functions because they are deprecated. Use mysqli_* or even better try to learn about prepared statements or PDO.

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";
}

check record existing in mysql php

Please see I already checked old threads but did not help.
Here is my code, seems ok but gives error: Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given
code:
function getPnr()
{
$con = mysqli_connect('127.0.0.1', 'root', '', 'safari');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$pnr = mt_rand(1111111111, 99999999999);
$result = mysqli_query($con,"SELECT pnr from tbl_user where pnr = '".$pnr."'");
if(mysqli_num_rows($result)>0)
echo "emtpy";//getPnr();
else
echo $pnr;
}
what's wrong here?
UPDATED code:
function getPnr()
{
$con = mysqli_connect('127.0.0.1', 'root', '', 'safari');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$pnr = mt_rand(1111111111, 99999999999);
$result = mysqli_query($con,"SELECT user_pnr from tbl_user where user_pnr = '".$pnr."'") or die(mysqli_error($con);
if(mysqli_num_rows($result)>0)
echo "emtpy";//getPnr();
else
echo $pnr;
return;
}
new error:
Parse error: syntax error, unexpected ';' in F:\wamp\www\safari\REST_APIs_for_RedBus\main.php on line 104
This means your sql query failed to execute. Try to add error handling with your code then you will get clear error sql message
$result = mysqli_query($con,"SELECT pnr from tbl_user where pnr = '".$pnr."'") or die(mysqli_error($con));

php stored procedure error while in query

Here's the code:
<?php
$sql = mysql_query($db, "CALL selectproducts()");
if( $sql === FALSE ) {
die('Query failed returning error: '. mysql_error());
} else {
while($row=mysql_fetch_array($sql))
{
$id=$row['prodname'];
$name=$row['proddescription'];
$desc=$row['prodsupplier'];
$supp=$row['proddate'];
$date=$row['prodprice'];
$qtyleft=$row['prodquantity'];
Getting this Error:
Warning: mysql_query() expects parameter 2 to be resource, string given in C:\xampp\htdocs\inventory\tableedit.php on line 166
Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in C:\xampp\htdocs\inventory\tableedit.php on line 170
Why is it has errors when in fact i have no parameters in call procedure?
Should be:
mysql_query("CALL selectproducts()", $db);
Documentation
Note that the mysql_ functions are now depreciated.
Try this method:
<?php
$link = mysqli_init();
mysqli_options($link, MYSQLI_INIT_COMMAND, "SET AUTOCOMMIT=0");
mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5);
mysqli_real_connect($link, $hostname, $username, $password, $dbName);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "CALL simpleproc()";
if (mysqli_real_query($link,$query)) {
if ($result2 = mysqli_store_result($link)) {
while ($row = mysqli_fetch_assoc($result2)) {
$q = $row["login"];
echo $q;
}
}
}
mysqli_close($link);
?>
I do believe you're getting your mysql_query arguments getting mixed up, where was $db is the second parameter, and the first is the MySQL query to be executed.
Although furthermore, you're probably better off using mysqli instead for future proofing:
<?php
$mysqli = new mysqli('username', 'username', 'password', 'database' );
$result = $mysqli->query("CALL selectproducts()");
if( !$result ) {
die('Query failed returning error: '. $mysqli->connect_errno );
} else {
while( $row = $result->fetch_array(MYSQLI_ASSOC)) {
$id = $row['prodname'];
$name = $row['proddescription'];
$desc = $row['prodsupplier'];
$supp = $row['proddate'];
$date = $row['prodprice'];
$qtyleft = $row['prodquantity'];
}
}
?>
From checking the mysqli PHP Docs for calling stored procedure:
<?php
/**
* Prepare Stored Procedure
**/
if (!($result = $mysqli->prepare("CALL selectproducts()"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$result->execute()) {
echo "Execute failed: (" . $result->errno . ") " . $result->error;
}
/**
* Iterate through each result
**/
do {
if ($res = $result->get_result()) {
printf("---\n");
var_dump(mysqli_fetch_all($res));
mysqli_free_result($res);
} else {
if ($result->errno) {
echo "Store failed: (" . $result->errno . ") " . $result->error;
}
}
} while ($result->more_results() && $result->next_result());
?>

Categories