Undefined Variable on mysqli_query - php

I have similar code that works with no errors but when I try and query my database I'm getting the several errors. Can anyone help ?
errors:
Notice: Undefined variable: link in C:\wamp64\www\twitter clone\functions.php on line 22
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\wamp64\www\twitter clone\functions.php on line 22
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\wamp64\www\twitter clone\functions.php on line 24
Code;
<?php
session_start();
$link = mysqli_connect("localhost", "root", "pass", "twitter");
if (mysqli_connect_errno()) {
print_r(mysqli_connect_error());
exit();
}
if (isset($_GET['function']) == "logout"){
session_unset();
}
function displayTweets($type) {
if ($type == 'public'){
$whereClause = "";
}
$query = "SELECT * FROM tweets ".$whereClause." ORDER BY 'datetime' DESC LIMIT 10";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) == 0) {
echo "No Tweets";
}
}
?>

The problem is that your $link variable is not in the function's local scope.
A way to fix this is by defining the variable in the function's local scope by adding the following line to the function:
global $link
Please have a look at this page to read more about the variable scope in PHP.
Edit:
An even better way would be to inject your connection by adding it as an argument to your function, which would have your code look something like this:
function displayTweets($type, $connection) {
if ($type == 'public'){
$whereClause = "";
}
$query = "SELECT * FROM tweets ".$whereClause." ORDER BY 'datetime' DESC LIMIT 10";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) == 0) {
echo "No Tweets";
}
}
After this, you would call your function using displayTweets('public',$link), with 'public' being the type, and $link being your defined connection
Also, in your current function, $whereClause could be undefined. I'm guessing your aware of this, just wanted to state it in case you get errors on that.

You have to use $link variable as global variable ($GLOBALS['link']) in displayTweets function or you have to pass $link as parameter.
$result = mysqli_query($GLOBALS['link'], $query);
or
displayTweets('public',$link);

Related

Problems when converting mysql to mysqli

I'm trying to convert mysql to mysqli, but I get some errors
first error:
mysqli_query() expects at least 2 parameters, 1 given in /home/.........../class/class.mysql.php on line 55
public function query($res, $pass_no = 1) {
$q1 = mysqli_query($res, $this->db_link);
if (!$q1) {
$this->sql_error();
if ($pass_no == 1) {
if ($this->output_error == 1) {
echo 'Attempting to reconnect to MySQL...' . "\n";
}
$this->db_close();
$this->db_connect();
$this->query($res, 2);
} else {
if ($this->output_error == 1) {
echo 'Reconnection failed; please check your MySQL server settings!' . "\n";
}
}
} else {
return $q1;
}
}
second error:
mysqli_real_escape_string() expects exactly 2 parameters, 1 given in /home/..../index.php on line 14
global $db ;
$username = mysqli_real_escape_string($_POST['username_login']);
$q ="select * from ".DB_PREFIX."admins where username='".$username."' ".
"and password='".md5( $_POST['password_login'])."'";
// echo $q;
$res =$db->query($q);
if($db->num_rows($res)==1)
{
return true ;
}
return false ;
I don't understand the 2 errors
When you get errors: Please help yourself by reading the manual .
1)
first error : mysqli_query() expects at least 2 parameters, 1 given in /home/.........../class/class.mysql.php on line 55
Your code:
$q1 = mysqli_query($res, $this->db_link);
Should be:
$q1 = mysqli_query($this->db_link, $res);
With the Database connection variable FIRST. This variable is required for almost all mysqli_ functions.
2)
second error : mysqli_real_escape_string() expects exactly 2 parameters, 1 given in /home/..../index.php on line 14
See point 1, above:
mysqli_real_escape_string($connectionVariable, $_POST['username_login']);
3)
$q ="select * from ".DB_PREFIX."admins where username='".$username."' ".
"and password='".md5( $_POST['password_login'])."'";
NO
Do not do this!!! Passwords should be stored using PHPs specialist password_hash function. Please read how to use it, why you should use it, why it should be used, and the benefits of using it and here if you need to use it on older versions of PHP.

Error : Array to string conversion in PHP

I'm getting this error while trying to execute my function.
The columns of my database are 100% correct and i tested every request and it worked!
Error :
[26-May-2018 05:21:49 UTC] PHP Notice: Array to string conversion in C:\wamp64\www\gcm\database.php on line 82
[26-May-2018 05:21:49 UTC] PHP Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in C:\wamp64\www\gcm\database.php on line 88
My function:
function getHistoriqueNotification($user,$mdp){
$com = new DbConnect();
$message=array();
$sql="select UTLR_UID from adm_utilisateurs where UTLR_LOGIN='$user' and UTLR_MDP='$mdp'";
$result=mysqli_query($com->getDb(),$sql);
$getID = mysqli_fetch_assoc($result);
$userID = $getID['UTLR_UID'];
$sqli = "SELECT alr_alertes.ALRT_DES_LN1,alr_alertes.ALRT_PHOTO,alr_historiques.AHIS_DES_LN1,alr_historiques.AHIS_DATEHEURE from alr_alertes,alr_historiques WHERE alr_alertes.ALRT_UID=alr_historiques.ALRT_UID AND alr_historiques.UTLR_UID=$userID";
$resulti = mysqli_query($com->getDb(),$sqli);
while($row=mysqli_fetch_assoc($resulti)){
$message = array('photo' =>$row['ALRT_PHOTO'] , 'titre' => $row['ALRT_DES_LN1'] , 'dateHeure' =>$row['AHIS_DATEHEURE'] , 'detail' => $row['AHIS_DES_LN1']);
}
return $message;
}
When using mysqli you need to free up the results per each query. Since you made a query with the $sql and then a second query using the $sqli without freeing up the results in between the two queries it caused you the problem.
Please read on these mysqli functions:
http://php.net/manual/en/mysqli-result.free.php
Notice I closed your first connection and then made a second one. I think you can do this by keeping the same connection but calling mysqli_free_result() prior to your next query. I am not all that familiar with mysqli but I think that's right.
function getHistoriqueNotification($user, $mdp){
$com = new DbConnect();
$message=array();
$sql = "select UTLR_UID from adm_utilisateurs where UTLR_LOGIN='$user' and UTLR_MDP='$mdp'";
$result = mysqli_query($com->getDb(),$sql);
$getID = mysqli_fetch_assoc($result);
$userID = $getID['UTLR_UID'];
mysqli_close($com);
unset($com);
$com1 = new DbConnect(); //This is really just a test.
$sqli = "SELECT alr_alertes.ALRT_DES_LN1,alr_alertes.ALRT_PHOTO,alr_historiques.AHIS_DES_LN1,alr_historiques.AHIS_DATEHEURE from alr_alertes,alr_historiques WHERE alr_alertes.ALRT_UID=alr_historiques.ALRT_UID AND alr_historiques.UTLR_UID=$userID";
if ($resulti = mysqli_query($com1->getDb(), $sqli)){
while($row = mysqli_fetch_assoc($resulti)){
//Added the [] after message.
$message[] = array(
'photo' =>$row['ALRT_PHOTO'],
'titre' =>$row['ALRT_DES_LN1'],
'dateHeure' =>$row['AHIS_DATEHEURE'],
'detail' =>$row['AHIS_DES_LN1']
);
}
}else{
echo("Error description: " . mysqli_error($com1->getDb()));
}
print_r($message); //<---This will show you if you have a result.
return $message;
}

How do I fix mysqli_store_result() expects parameter 1 to be mysqli, object given

I have looked at the manual for the function and cannot figure out what parameter would satisfy. I know several other questions have this problem but none of those solutions have helped.
Here is my code:
$id = $_GET['id'];
$_SESSION['id'] = $id;
$link = mysqli_connect("localhost", "root", "", "first_db");
mysqli_select_db($link, "first_db");
$query = mysqli_query($link, "Select * from list WHERE id ='$id'");
$count = mysqli_stmt_num_rows($query);
Since you are calling mysqli_query you don't actually need to call mysqli_store_result as that is part of what that does (see the manual). Also since you're not actually using a prepared statement you need to change the num_rows routine you are calling; replace
$count = mysqli_stmt_num_rows($query);
with
$count = mysqli_num_rows($query);

Warning: mysqli_query() expects parameter 1 to be mysqli, null given on line 26

I'm getting this error on my site after I tried to convert to mysqli on line 26 ($rs = mysqli_query($link,MySQLi) or die(mysqli_connect_error());)
My code is like this
//Get configuration control record from database
$MySQLi = "SELECT configValLong
FROM storeadmin
WHERE configVar = 'controlRec'
AND adminType = 'C' ";
$rs = mysqli_query($link,MySQLi) or die(mysqli_connect_error());
$totalRows = mysqli_num_rows($rs);
if ($totalRows!=0){
$rows = mysqli_fetch_array($rs);
$configArr = trim($rows["configValLong"]);
if (strlen($configArr) > 0 ){
$configArr = explode("*|*",$configArr);
}
If you have defined, $link=mysqli_connect() outside the function, you need to pass it as a parameter to the function or declare it global inside the function.
1. Passing as parameter
yourFunction($link); //function call, passing the variable to the function
function yourFunction($link) //you can use any name for parameter
{ //now it can be accessed here
}
2. Declaring as Global inside the function
function yourFunction()
{
global $link;
//now it can be accessed here
}
By using the keyword global, you are specifying that you want to use the $link which you have defined in global scope.
You may have to do the same with $MySQLi and other variables if you
have defined them outside the function.
On this line: $rs = mysqli_query($link,MySQLi) or die(mysqli_connect_error());, your variable MySQLi needs the variable sign $.
So change that to this:
$rs = mysqli_query($link,$MySQLi) or die(mysqli_connect_error());

Query empty if included

I have been performing a query inside my page -- say, page.php -- where I run a simple query.
Pseudo-code:
$request_unavailble = mysqli_query($mysqli, "SELECT * FROM my_table WHERE availble='0'");
When this is performed from within page.php, I get all results where availble is set to 0. However, if I run this from within a seperate included file, the data returns empty. In fact, mysqli_num_rows returns 0 when included.
What's going wrong, here?
Edit
The following function was added as an include (both as a function and alone)
function compte_messagerie()
{
$requetes_messagerie = mysqli_query($mysqli, "SELECT * FROM ".DB_PREFIX."messagerie WHERE lu='0'");
if(mysqli_num_rows($requetes_messagerie) == 0)
{
echo '<a id="messagerie" href="messagerie">'.AUCUN_NOUVEAU."</a>";
}
else if(mysqli_num_rows($requetes_messagerie) == 1)
{
echo '<a id="messagerie" href="messagerie">';
echo '<span>'.mysqli_num_rows($requetes_messagerie)."</span> ";
echo MESSAGES_SINGULIER."</a>";
}
else
{
echo '<a id="messagerie" href="messagerie">';
echo '<span>'.mysqli_num_rows($requetes_messagerie)."</span> ";
echo MESSAGES_PLURIEL."</a>";
}
}
When porting your query into a function, the MySQLi connection object in $mysqli went out of scope, and was therefore invalid inside the function. With display_errors enabled, I would expect you to see errors like:
Notice: undefined variable $mysqli
Warning: mysqli_query() expects parameter 1 to be resource, null given
The cleanest solution is to pass $mysqli into your function as a parameter, making it available to the function's scope
// Expect the MySQLi resource as a parameter...
function compte_messagerie($mysqli)
{
$requetes_messagerie = mysqli_query($mysqli, "SELECT * FROM ".DB_PREFIX."messagerie WHERE lu='0'");
if(mysqli_num_rows($requetes_messagerie) == 0)
{
echo '<a id="messagerie" href="messagerie">'.AUCUN_NOUVEAU."</a>";
}
// etc.....
}
Try this. Please check if the available table is require string value or integer.
$request_unavailble = mysqli_query("SELECT * FROM my_table WHERE availble= 0 ");
while($rows = mysqli_fetch_assoc($request_unavailble)){ // <- this will check if there some data fetch
// You put some code here
}

Categories