switch from mysql to mysqli Undefined variable: connect - php

I would like to switch from mysql_* to mysqli_* because I've read, that soon mysql_* won't be supported anymore.
Now I have a problem, that the functions which I wrote dont work anymore.
At the index.php file I have
global $connect;
$connect = mysqli_connect('localhost', "username", "password");
and at the functions.php file I have
function count_total_messages(){
$result = "SELECT COUNT(id) AS total FROM database.messages WHERE uidto='".$_SESSION['userid']."' OR unameto='".$_SESSION['username']."'";
$qry = mysqli_query($connect,$result);
return $qry['total'];
}
But I get the following error:
Undefined variable: connect
What should I do? Everywhere the mysqli_query works except those from the functions.php file.

function count_total_messages(){
global $connect; //You need a locally defined connect variable
$result = "SELECT COUNT(id) AS total FROM database.messages WHERE uidto='".$_SESSION['userid']."' OR unameto='".$_SESSION['username']."'";
$qry = mysqli_query($connect,$result);
return $qry['total'];
}

You are doing the global the wrong way around. In your index you just need
$connect = mysqli_connect('localhost', "username", "password");
And in your functions you use this:
function count_total_messages(){
global $connect;
$result = "SELECT COUNT(id) AS total FROM database.messages WHERE uidto='".$_SESSION['userid']."' OR unameto='".$_SESSION['username']."'";
$qry = mysqli_query($connect,$result);
return $qry['total'];
}

Related

Can not execute the MySQL query using PHP and MySQL

I have an issue when executing the sql query.I am explaining my code below.
complain.php:
require_once("./include/dbconfig.php");
if($_REQUEST['typeOfApp']=="WEB"){
$sent_form="Web";
$ticket_id=generateTicketId('W1');
}
function generateTicketId($code){
$sql="select * from db_ticket order by id desc ";
$qrylast=mysqli_query($con,$sql);
echo mysqli_num_rows($qrylast);exit;
}
Here i am trying to check the number of rows.But I am not getting anything.I am giving my dbconfig.php below.
dbconfig.php
$con = new mysqli("localhost", "root", "****", "************");
if ($con->connect_error)die("Connection failed: ");
Here i need to check the no of rows present inside the table.Please help me.
You need to define your connection variable global so you have to access in inside your function OR you need to pass it in function parameter
require_once("./include/dbconfig.php");
//global $con;
if($_REQUEST['typeOfApp']=="WEB"){
$sent_form="Web";
$ticket_id=generateTicketId('W1',$con);// pass connection variable
}
Pass your $con variable as parameter and function need return value
function generateTicketId($code, $con) {
$sql = "select * from db_ticket order by id desc ";
$qrylast = mysqli_query($con, $sql);
$rows = mysqli_num_rows($qrylast);
if($rows>0){
return $rows;
}else{
return FALSE
}
}
http://php.net/manual/en/language.variables.scope.php

Changing mysql_connect to mysqli causes function to fail

To begin with, I am a novice when it comes to PHP and MySQL.
I have a MySQL table called levels that contains two columns: level_id and mapData. Some time ago, I wrote a piece of code using mysql_connect that takes user inputted level_id and fetches the corresponding mapData from the table, and the code works as intended. See below:
<?php
$mysql_host = 'localhost';
$mysql_user = 'username';
$mysql_password = "password";
$mysql_database = 'database';
if (!mysql_connect($mysql_host,$mysql_user,$mysql_password)||!mysql_select_db($mysql_database)){
die('Connection failed');
}
function get_map_data($level_id,$field){
$query = "SELECT $field FROM levels WHERE level_id='$level_id'";
if($query_run = mysql_query($query)){
if($query_result = mysql_result($query_run,0,$field)){
return $query_result;
}
}
}
$user_input = mysql_real_escape_string(base64_decode($_GET["level_id"]));
$sql = "SELECT level_id FROM levels WHERE level_id='$user_input'";
$result = mysql_query($sql);
if(mysql_num_rows($result) >0){
$mapData = get_map_data($user_input,'mapData');
print $mapData;
}else{
echo "0";
}
?>
In the case that the user inputs a level_id that does not exist in the database, instead of mapData, he will receive 0. Everything works! I, however, read that mysql_connect is deprecated as of PHP 5.5 and decided to switch from using it in my file to using mysqli:
$conn = new mysqli($mysql_host, $mysql_user, $mysql_password, $mysql_database);
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
After changing to mysqli, my get_map_data function has stopped working. I have made certain that the mysqli connection works, but I am simply hitting my head against the wall in making my function work using it. How do I fix my get_map_data function so that it functions again using mysqli?
You can't mix mysqli and mysql_ functions. Furthermore, your mysqli initialization is creating an object, not a resource. Lastly, there is no mysqli_result() function, so therefore we need to emulate what you're trying to do. You wanted the first row 0 and then wanted a specific $field. Below should be what you want.
function get_map_data($level_id,$field){
$query = "SELECT $field FROM levels WHERE level_id='$level_id'";
if($query_run = $mysqli->query($query)){
//no mysqli->result() function, so we need to seek to the row.
$query_run->data_seek(0);
if($query_result = $query_run->fetch_assoc()){
return $query_result[$field];
}
}
}
your get_map_data function currently has query running using mysql_query you have to change that to mysqli_query in order to execute:
function get_map_data($level_id,$field){
$query = "SELECT $field FROM levels WHERE level_id='$level_id'";
if($query_run = mysqli_query($conn,$query)){
if($query_result = mysqli_result($query_run,0,$field)){
return $query_result;
}
}
}

PHP MySQL call Store Procedure with parameters

In my php application i need to call a stored procedure from MySQL
the procedure i have created is this.
DROP PROCEDURE IF EXISTS _proc.usp_hotel_rooms_mLoadByPrimaryKey;
CREATE PROCEDURE _proc.`usp_hotel_rooms_mLoadByPrimaryKey`(
_HTR_ID INT(11),
_HTR_TYPE_ID INT(11)
)
BEGIN
SELECT
HTR_ID,
HTR_NAME,
HTR_TYPE_ID
FROM hotel_rooms_m
WHERE
(HTR_ID = _HTR_ID AND HTR_TYPE_ID=_HTR_TYPE_ID)
;
END;
I need to pass the parameters _HTR_ID and _HTR_TYPE_ID,so i tried it like this
<?php
$con = mysql_connect("localhost","user","user")or die(mysql_error());
$db = mysql_select_db("_proc") or die(mysql_error());
$par1 = "1";
$par2 = "2";
$dbh->query("CAST usp_hotel_rooms_mLoadByPrimaryKey($par1, $par2, #OutPut)");
$dbh->query("SELECT #OutPut");
echo $dbh;
?>
this is the error i am getting Call to a member function query() on a non-object in D:\xampp\htdocs\_proc\index.php on line
You have to use
your connection string like this using mysqli
$mysqli = new mysqli( "HOST", "USR", "PWD", "DBNAME" );
Here is the link for tutors Mysql stored procedures with php
You seem to be mixing up some styles: Nor mysql_connect nor mysql_select_db return an object and all mysql_* functions are deprecated. Your $dbh->query statments seem to suggest a database connection using mysqli or PDO.
You probably want to open a connection using mysqli or PDO to start with and assign that to your $dbh variable.
Here your code goes
<?php
$dbh = new PDO('mysql:host=localhost;dbname=_proc', "user", "user");
$par1 = "1";
$par2 = "2";
$dbh->query("CAST usp_hotel_rooms_mLoadByPrimaryKey($par1, $par2, #OutPut)");
$dbh->query("SELECT #OutPut");
echo $dbh;
?>

Fatal error: Call to a member function prepare() on a non-object PDO

I am trying to move the my sql working to PDO but it showing the following
Fatal error: Call to a member function prepare() on a non-object in /home/content/58/9508458/html/pa/test. php on line 12
orginal code
<?php
$pdfreq=$_GET['dadi'];
include('config.php');
require('fpdf.php');
$link =mysql_connect($db_host,$username,$password);
mysql_select_db($db_name);
$update = "UPDATE mastertable SET pdfstatus =1 WHERE id_pk = $pdfreq";
mysql_query($update, $link);
Replaced with
<?php
$pdfreq=$_GET['dadi'];
include('config.php');
require('fpdf.php');
$link =mysql_connect($db_host,$username,$password);
mysql_select_db($db_name);
$sql = "UPDATE mastertable SET pdfstatus=?, WHERE id_pk=?";
$q = $link->prepare($sql);
$q->execute(array(1,$pdfreq));
Your $link variable is not a PDO object. You should replace:
$link = mysql_connect($db_host,$username,$password);
mysql_select_db($db_name);
With:
$link = new PDO("mysql:dbname=$db_name;host=$db_host",$username,$password);
You are using MySQL helper functions, not PDO or MySQLi.
Prepare will not work with what you are doing
You need to change your syntax to, note the trailing i in MySQLi
<?php
$pdfreq=$_GET['dadi'];
$id = 1;
include('config.php');
require('fpdf.php');
$link = new mysqli($db_host,$username,$password, $db_name);
$sql = "UPDATE mastertable SET pdfstatus=? WHERE id_pk=?";
$q = $link->prepare($sql);
$q->bind_param("is", $id, $pdfreq);
$q->execute();
Since MySQL does not have a prepare method, your value will never get set to 1, and you will fail with Fatal error: Call to a member function prepare() on a non-object
If you wish to use PDO see the PDO Documentation on PHP.Net

Scope of PHP function [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 2 years ago.
I have a file that corrals my re-usable functions into one file (functions.php). It's include_once()'d on every page that needs it. I'm getting an error when my custom functions are trying to access a MySQL connection outside their own scope. The source is a bit like this:
<?php
// functions.php
$connect = mysql_connect("localhost", "user", "pass") or die("MySQL said: ".mysql_error());
mysql_select_db("database", $connect) or die("MySQL said: ".mysql_error()); // no error
/* ... */
function getmotd($user) {
$query = "SELECT cid FROM `users`
WHERE id = ".$user;
$query = mysql_query($query, $connect); // error occurs here, $connect is not a valid MySQL link-resource
/* ... */
}
?>
Why can't my function access variables declared above it's scope? I can get a successful connection by reproducing $connect's declaration within the function.
Any insight into how I can work around this or what I'm doing wrong here?
You can't access $connect because it is outside the scope of the function; that is, PHP can only see the variables within the function when it's inside it. You could use the global keyword to let PHP know the variable is outside the function's scope as Kemal suggests, but I think a better course of action is to pass the connection into the function. This will give you better encapsulation. If you learn to write your functions (and later classes) with passing in the resources and data you need (a practice known as "dependency injection"), you'll find you have cleaner and more maintainable code. Here's the example:
function getmotd($db, $user) {
$query = "SELECT cid FROM users WHERE id = " . (int)$user;
$result = mysql_query($query, $db);
/.../
}
$connect = mysql_connect(...);
mysql_select_db(...);
$motd = getmotd($connect, $user);
Hope this helps.
Use the global keyword.
Example
function getmotd($user) {
global $connect;
$query = "SELECT cid FROM `users`
WHERE id = ".$user;
$query = mysql_query($query, $connect); // error occurs here, $connect is not a valid MySQL link-resource
/* ... */
}
You can also do it like this
function getmotd($user) {
$query = "SELECT cid FROM `users`
WHERE id = ".$user;
$query = mysql_query($query, $GLOBALS['connect']); // error occurs here, $connect is not a valid MySQL link-resource
/* ... */
}
If you want to make re-usable codes, you'd probably be better off with OOP. Create a class for the database, and add some properties for the database info, and access them from the functions by using the this keyword.

Categories