mysqli/mysql query inside function not working [duplicate] - php

This question already has answers here:
Executing mysqli_query inside a function
(2 answers)
Closed 1 year ago.
I'm tryin to build some functions for a website of mine and some of them consist in
fetching data from the mysql database. When I test the code outside of the function
it seems to work properly. So here it is, The first page:
require('db.php');
require('functions.php');
$email = 'sample#gmail.com';
if (user_exists($email) == true){
echo "Good news, this exists";
}
Now db.php :
$db = new MySQLi("localhost","test","test","test");
if ($db->connect_errno){
echo "$db->connect_errno";
}
And the functions.php file:
function sanitize ($data){
$db->mysqli_real_escape_string($data);
}
function user_exists($usermail){
$usermail = sanitize($usermail);
$query = $db->query("SELECT COUNT(userId) FROM users WHERE userEmail= '$usermail' ");
$check = $query->num_rows;
return ($check == 1) ? true : false;
}
And the error I'm getting when accessing the first file is:
Notice: Undefined variable: db in C:\xampp\htdocs\auctior\inc\functions.php on line 6
Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\auctior\inc\functions.php on line 6
SO I've required/included the db.php where $db is the mysqli connect. And within the same file(first file) I call the functions located at functions.php
Thank you in advance,
I'd appreciate your help as this is pissing me off......

You probably need to use the global keyword, otherwise $db is considered a var in local scope.
function sanitize ($data){
global $db;
$db->mysqli_real_escape_string($data);
}
function user_exists($usermail){
global $db;
$usermail = sanitize($usermail);
$query = $db->query("SELECT COUNT(userId) FROM users WHERE userEmail= '$usermail' ");
$check = $query->num_rows;
return ($check == 1) ? true : false;
}

Try to connect inside the function, and connection needs to be included before you include functions.
Something like this:
function user_exists($usermail){
$db = new MySQLi("localhost","test","test","test");
$usermail = sanitize($usermail);
$query = $db->query("SELECT COUNT(userId) FROM users WHERE userEmail= '$usermail' ");
$check = $query->num_rows;
return ($check == 1) ? true : false;
}

Related

PHP function returns wrong values

I have this function
function getNick($uid)
{
$sqli = "SELECT nick FROM users WHERE userid='".$uid."'";
mysqli_real_escape_string($con,$sqli);
$resulti = mysqli_query($con,$sqli);
$rowi = mysqli_fetch_assoc($resulti);
if($resulti->num_rows > 0) return $rowi["nick"];
else return "(none)";
}
Basically it should return me nick based on user's id. Problem is that I only keep getting '(none)'. What is interesting I printed actual $sqli and copied it into phpMyAdmin and it worked as expected. I even tried to just print nick without IFs but I ended up with empty string. What might be the issue? Am I overlooking something? Thanks
<?php
$con = mysqli_connect("localhost","root","","test");
function getNick($uid,$con)
{
$sqli = "SELECT nick FROM users WHERE userid='".$uid."'";
mysqli_real_escape_string($con,$sqli);
$resulti = mysqli_query($con,$sqli);
$rowi = mysqli_fetch_assoc($resulti);
if($resulti->num_rows > 0) return $rowi["nick"];
else return "(none)";
}
echo getNick(1,$con);
?>
it works
variable scope problem
use above method to pass connection in method or
use $GLOBALS['con'] to access connection in method getNick

Variable $connection is undefined. Impossible, what is happening there?

Objective: I am in the process of creating a php login script.
Problem: I can't seem to be able to make my includes recognize the $connection variable even though it should be clearly defined in connection.php. As a result the value of my variable is nothing / NULL.
What I tried: I started with mysql but quickly noticed that it was the wrong approach and converted my code to mysqli. I checked for typos in all the $connection variables I have. I made sure the paths are correct. As a last resort I did a Google search but didn't find an answer or any useful hint to my scenario.
Problem: What is the reason for my variable not being defined?
Error Messages:
All those messages are related to this single variable no being defined for some reason:
Php Notice: Undefined variable: connection in C:\xampp\htdocs\aspie\Php\Core\Common.php on line 4
Php Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\aspie\Php\Core\Common.php on line 4
Php Notice: Undefined variable: connection in C:\xampp\htdocs\aspie\Php\Core\Functions\Members.php on line 4
Php Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\aspie\Php\Core\Functions\Members.php on line 4
Php Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\aspie\Php\Core\Functions\Members.php on line 5
// INITIALIZER
<?php
session_start();
// error_reporting(NULL);
include 'Connection.php';
include 'Common.php';
include 'Functions/Members.php';
?>
**// ERROR MESSAGES **
<?php
$connection_error = 'Our website is experiencing technical issues, please come back later.';
$wrong_login = 'Password and name are wrong.';
$member_registered = 'Access has been denied. You do not seem to be a registered user.';
?>
**// CONNECTION **
<?php
include 'Errors.php';
$connection = mysqli_connect('localhost', 'root', '', 'project') or exit ($connection_error);
?>
**// COMMON **
<?php
error_reporting();
function sanitize($connection, $data) {
global $connection;
global $data;
return mysqli_real_escape_string($connection, $data);
}
?>
**// MEMBERS **
<?php
function member_registered($connection, $name) {
$name = sanitize($connection, $name);
$query = mysqli_query($connection, "SELECT COUNT(`id`) FROM `members` WHERE `name` = '$name'");
return (mysqli_num_rows($query) == 1) ? true : false;
}
?>
**// LOGIN **
<?php
include 'Php/Core/Initializer.php';
if (member_registered($connection, 'ee')) {
echo "exists";
}
die("eee");
echo error_reporting();
if (empty($_POST) == false) {
$name = $_POST['name'];
$password = $_POST['name'];
if (empty($name) OR empty($password)) {
echo $wrong_login;
}
else if (member_registered($connection, $name) == false) {
echo $member_registered;
}
}
?>
UPDATE:
Now what I get: existseee;
The conditional doesnt work now even though its all set up right. Username doesnt exist so it should'nt echo "exists:
if (member_registered($connection, 'ee')) {
echo "exists";
}
die("eee");
In your case, the $connection variable inside your sanitize function isn't reachable.
Try to pass the $connection variable into your function, like this:
function sanitize($data, $connection) {
return mysqli_real_escape_string($connection, $data);
}
Read more about it here: http://php.net/manual/en/language.variables.scope.php
UPDATE
In **// MEMBERS ** you need to include the new parameter as well:
function member_registered($name, $connection) {
$name = sanitize($name, $connection);
$query = mysqli_query($connection, "SELECT COUNT(`id`) FROM `members` WHERE `name` = '$name'");
return (mysqli_num_rows($query) == 1) ? true : false;
}
and because of that your **// LOGIN ** should be updated as well:
include 'Php/Core/Initializer.php';
if (member_registered('ee', $connection)) {
echo "exists";
}
die("eee");
echo error_reporting();
if (empty($_POST) == false) {
$name = $_POST['name'];
$password = $_POST['name'];
if (empty($name) OR empty($password)) {
echo $wrong_login;
}
else if (member_registered($name, $connection) == false) {
echo $member_registered;
}
}
And make sure that the $connection variable is reachable everywhere where you need it.
UPDATE #2
Answer to your update:
it should be like this:
if (member_registered('ee', $connection)) {
echo "exists";
}
and not like this:
if (member_registered($connection, 'ee')) {
echo "exists";
}
the $connection is the second parameter.

MySQL COUNT not returning False or True in PHP

So I'm trying to check if a user already liked a post.
Code:
function previously_liked($id) {
if (isset($_SESSION['user_login'])) {
$user = $_SESSION["user_login"];
}
else {
$user = "";
}
$connection = new mysqli($host, $username, $password, $database);
$id = $connection->real_escape_string($id);
$query = $connection->query("SELECT COUNT(`id`) AS `count` FROM `likes` WHERE `id` = '$id' AND `user_id` = '".$connection->escape_string($user)."'");
while ( $row = $query->fetch_object()->count ) {
if ( $row->count == 0 ) return false;
else return true;
}
}
The thing is, it's not returning false or true. On my other PHP page I'm trying to run this function like this:
if (previously_liked(70) === true) {
$aliked = "You've already liked this!";
}
echo $aliked;
The only error I'm seeing is Notice: Undefined variable: aliked in profile.php on line 391
Any help is welcome! Thanks!
You can do this things to finds error in your code:
echo $user; //before MySQL query
Query your MySQL statement in MySQL console or app like PHPmyAdmin after replacing ".$connection->escape_string($user)." to your user_id. If it fetch row than your MySQL statement is correct and there is something wrong with $_SESSION["user_login"] value.
Optionally, you can also echo the returning rows to check the output data.
Otherwise check your query statement as column names, table name, database etc.
Hope, it helps you...
Your query is fine, your problem is something else: You're defining $aliked inside the scope of the if-statement, so you can't use it outside. You need to change your code, one possibility is this:
if (previously_liked(70) === true) {
echo "You've already liked this!";
}
or this:
$aliked = "";
if (previously_liked(70) === true) {
$aliked = "You've already liked this!";
}
echo $aliked;

How to create Holiday Function in PHP?

I'm trying to make a function to generate holiday in PHP.
I've stored the holiday date in Oracle Table:
HOLIDAY
01-JAN-15
03-JAN-15
04-JAN-15
etc
My question is, how to make a function to get holiday date?
I mean, I need to find out that is_holiday('01-JAN-15') holiday is TRUE.
Here's my source code:
<?php
include "config/connect.php";
function is_holiday($thedate)
{
$sql = OCIParse($connect, "SELECT * FROM UF2T_HOLIDAY WHERE HOLIDAY = '".$thedate."'");
ociexecute($sql);
$result = oci_fetch_array($sql);
if(!empty($result[0]))
{
$holiday = "TRUE";
}
else
{
$holiday = "FALSE";
}
return $holiday;
}
echo is_holiday("08-JAN-15");
?>
This code doesn't work and always return FALSE.
What I'm supposed to do to make this code work?
Additional information:
I try to run it outside of a function, something like this :
<?php
include "config/connect.php";
$thedate = '01-JAN-15';
$sql = OCIParse($connect, "SELECT HOLIDAY FROM UF2T_HOLIDAY WHERE HOLIDAY = '".$thedate."'");
ociexecute($sql);
$result = oci_fetch_array($sql);
if(!empty($result[0]))
{
$holiday = "TRUE";
}
else
{
$holiday = "FALSE";
}
echo $holiday;
?>
This code is work. So I think the problem is around the function. Any suggestion? Please help. Thanks in advance.
Sorry for my bad English. :D
I think, that problem is, that variable $connect is not available in your function. Try this:
function is_holiday($thedate, $connect)
and then call the function:
echo is_holiday("08-JAN-15", $connect);
That's becuase in PHP global variables by default are not visible in the functions. In your case the connection inside your function is a local variable which value is undefined. Change your function like this:
function is_holiday($thedate)
{
global $connect;
$sql = OCIParse($connect, "SELECT * FROM UF2T_HOLIDAY WHERE HOLIDAY = '".$thedate."'");
ociexecute($sql);
...

mysqli connection not working inside function? [duplicate]

This question already has answers here:
Executing mysqli_query inside a function
(2 answers)
Closed 7 years ago.
I'm having some problems performing a mysql query inside a php function. The error I am getting is
Notice: Undefined variable: link in C:\path\api\inc\restFunctions.php on line 16
There are several files calling each other so I will attempt to outline the necessary information.
URL Accessed:
localhost/serverList/api/rest.php?action=allServers
serverList/api/rest.php
<?php
include 'inc/restFunctions.php';
$possibleCalls = array('allServers','allEnvs','allTypes','false');
if(isset($_GET['action'])){
$action = $_GET['action'];
}
else{
$action = 'false';
}
if(in_array($action,$possibleCalls)){
switch ($action){
case 'allServers':
$return = allServers();
break;
case 'allEnvs':
$return = allEnvs();
break;
case 'allTypes':
$return = allTypes();
break;
case 'false':
$return = falseReturn();
break;
}
}
serverList/api/inc/restFunctions.php
<?php
include ('inc/config.php');
function allServers(){
$serverInfoQuery = "SELECT * FROM servers"
$allServerResults = $link->query($serverInfoQuery);
$json = array();
while($row = $allServerResults->fetch_assoc()){
$json[]['serverID'] = $row['serverID'];
$json[]['environment'] = $row['environment'];
$json[]['type'] = $row['type'];
$json[]['serverIP'] = $row['serverIP'];
$json[]['serverDescription'] = $row['serverDescription'];
$json[]['serverCreatedBy'] = $row['serverCreatedBy'];
$json[]['serverCreatedDtTm'] = $row['serverCreatedDtTm'];
$json[]['serverUpdatedBy'] = $row['serverUpdatedBy'];
$json[]['serverUpdatedDtTm'] = $row['serverUpdatedDtTm'];
}
$jsonResults = json_encode($json);
return $jsonResults;
}
?>
serverList/api/inc/config.php
<?php
$host = 'localhost';
$user = 'userName';
$password = 'password';
$database = 'database';
$link = new mysqli($host, $user, $password, $database);
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
?>
I have verified that the query being called works. I also verified that the connection info (masked above) works by using a different page of this software that queries the db.
I'm assuming I must have missed a quote or paren somewhere, but I'm baffled as to where it might be.
The problem is with PHP variable scoping. Add this line inside of allServers() function before you refer to the $link variable for the first time:
global $link;
See more here:
http://php.net/manual/en/language.variables.scope.php
In my opinion using global variables is not a good solution. You might override $link ($link is rather usual name for a variable you may be using for another purposes) variable in some scope by accident, resulting in lot's of confusion and difficult debugging.
Just pass it as a function parameter - much cleaner and easier to read:
function AllServers($link) {
$serverInfoQuery = "SELECT * FROM servers";
$allServerResults = $link->query($serverInfoQuery);
//More PHP code
}
if(in_array($action,$possibleCalls)){
switch ($action){
case 'allServers':
$return = allServers($link);
break;
}
}
To be honest, even better solution would be using some generic classes/functions to establish your mysql connection like so:
class DB {
private static $link = null;
public static function getConnectionResource() {
//In that way we "cache" our $link variable so that creating new connection
//for each function call won't be necessary
if (self::$link === null) {
//Define your connection parameter here
self::$link = new mysqli($host, $user, $password, $database);
}
return self::$link;
}
}
function getAllServers() {
$link = DB::getConnectionResource();
//Preform your query and return results
}
Use global variable
function allServers(){
global $link
...
...
...
... your code follows

Categories