how to use a variable outside a function - php

i have this initialization file called init.php which I have declared a variable called $db for a mysqli connection. Below is my code.
<?php
ob_start();
session_start();
define('DBHOST', '127.0.0.1');
define('DBUSER', 'root');
define('DBPASSWORD', '');
define('DBNAME', 'mydb');
$db = new mysqli(DBHOST, DBUSER, DBPASSWORD, DBNAME);
if ($db->connect_error) {
header('Location: 404.php');
}
require_once 'functions/User.php';
require_once 'functions/Sanitize.php';
As you can see I required User.php inside the function folder, and on the User.php file i have this code
<?php
function login($idnumber, $username, $password) {
$idnumber = sanitize($idnumber);
$username = sanitize($username);
$password = sanitize($password);
$hashed_password = get_hashed_password($username);
}
function get_hashed_password($username) {
$username = sanitize($username);
$sql = "SELECT `password` FROM `users` WHERE `username` = ?";
$stmt = $db->prepare($sql);
if(!$stmt) {
echo 'invalid sql statement';
}
die();
}
On the get_hashed_password() function i used the variable $db but i got an error message saying
Notice: Undefined variable: db in D:\xampp\htdocs\sample\functions\User.php on line 15
Fatal error: Call to a member function prepare() on a non-object in D:\xampp\htdocs\sample\functions\User.php on line 15
Can someone help me how can I used the variable $db in any of my functions? Thanks in advance!

Call $db as global
function get_hashed_password($username) {
global $db;
//...
}

you can use $GLOBALS inside the function like this
$your_var = "something";
function abc()
{
$your_var = $GLOBALS['your_var'];
}
UPDATE 2 :
function get_hashed_password($username) {
$username = sanitize($username);
$sql = "SELECT `password` FROM `users` WHERE `username` = ?";
$db = $GLOBALS['db'];
$stmt = $db->prepare($sql);
if(!$stmt) {
echo 'invalid sql statement';
}
die();
}

Related

Php Class inside included file not found

I was trying to follow this tutorial to make a simple login and registration for Android application with MySql. The Android app runs fine until it hit an error when accessing the database (account register).
When I tried to access the php application to make sure that the error is in the Android app, I got this error:
Fatal error: Class 'DbConnect' not found in C:\xampp\htdocs\AndroidLogin\include\user.php on line 12
I'm sure that db.php is already included in user.php. These are the codes I used from the tutorial: The first one is index.php
//index.php
<?php
require_once 'include/user.php';
$username = "";
$password = "";
$email = "";
if(isset($_POST['username'])){
$username = $_POST['username'];
}
if(isset($_POST['password'])){
$password = $_POST['password'];
}
if(isset($_POST['email'])){
$email = $_POST['email'];
}
// Instance of a User class
$userObject = new User();
// Registration of new user
if(!empty($username) && !empty($password) && !empty($email)){
$hashed_password = md5($password);
$json_registration = $userObject->createNewRegisterUser($username, $hashed_password, $email);
echo json_encode($json_registration);
}
// User Login
if(!empty($username) && !empty($password) && empty($email)){
$hashed_password = md5($password);
$json_array = $userObject->loginUsers($username, $hashed_password);
echo json_encode($json_array);
}
?>
Next, config.php
//config.php
<?php
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("DB_NAME", "androidlogin");
?>
This one is db.php
// db.php
<?php
include_once 'config.php';
class DbConnect{
private $connect;
public function __construct(){
$this->connect = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno($this->connect)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
public function getDb(){
return $this->connect;
}
}
?>
And the last one is user.php
// user.php
<?php
include_once 'db.php';
class User{
private $db;
private $db_table = "users";
public function __construct(){
$this->db = new DbConnect();
}
public function isLoginExist($username, $password){
$query = "select * from " . $this->db_table . " where username = '$username' AND password = '$password' Limit 1";
$result = mysqli_query($this->db->getDb(), $query);
if(mysqli_num_rows($result) > 0){
mysqli_close($this->db->getDb());
return true;
}
mysqli_close($this->db->getDb());
return false;
}
public function createNewRegisterUser($username, $password, $email){
$query = "insert into users (username, password, email, created_at, updated_at) values ('$username', '$password', '$email', NOW(), NOW())";
$inserted = mysqli_query($this->db->getDb(), $query);
if($inserted == 1){
$json['success'] = 1;
}else{
$json['success'] = 0;
}
mysqli_close($this->db->getDb());
return $json;
}
public function loginUsers($username, $password){
$json = array();
$canUserLogin = $this->isLoginExist($username, $password);
if($canUserLogin){
$json['success'] = 1;
}else{
$json['success'] = 0;
}
return $json;
}
}
?>
My directory looks like this:
AndroidLogin
|index.php
|include
|config.php
|db.php
|user.php
Do I miss something?
Usually, call the file like the class that you declare in it. In WAMP usually it gives some issues, i suggest to you to rename db.php in DbConnect.php
Make a default (empty) constructor in DbConnect, and make a simple method that would echo something. Try to make new DbConnect instance call that method from User class?

I can't count results in my database with PDO

I have this error has shown:
Notice: Undefined variable: conn in D:\xampp\htdocs\website\core\functions\users.php on line 4
Fatal error: Call to a member function query() on null in D:\xampp\htdocs\website\core\functions\users.php on line 4
this is connect database
connect.php
<?php
$servername = "localhost";
$user = "root";
$passwd = "";
$dbname = "userdata";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $user, $passwd);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $exc) {
die($exc->getMessage());
}
?>
and in this part I have the problem
users.php
<?php
function user_exists($username){
$sql ="SELECT COUNT('id') FROM users where username = '$username'";
$query = $conn->query($sql);
$result = $query->fetchAll(PDO::FETCH_ASSOC);
if(count($result)){
$res = 0;
}else {
$res = 1;
}
return $res;
}
?>
and this where I connected users.php with connect.php
init.php
<?php
session_start();
require 'database/connect.php';
require 'functions/users.php';
require 'functions/general.php';
$errors = array();
?>
This is a variable scope problem.
Because $conn is set / declared outside of your function, you do not have access to it inside of your function.
Modify your function as follows:
function user_exists($username){
// This gets you access to the $conn variable inside the function.
global $conn;
$sql ="SELECT COUNT('id') FROM users where username = '$username'";
$query = $conn->query($sql);
$result = $query->fetchAll(PDO::FETCH_ASSOC);
if(count($result)){
$res = 0;
}else {
$res = 1;
}
return $res;
}

Fatal error call to undefined function mysqli_stat_bind_param()

I have the below php script
<?php
$con = mysqli_connect("localhost", "root", "");
if (!$con) {
die('Could not connect'.mysqli_error());
}
mysqli_select_db($con, "mysql");
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "Select * from bbau_login where username=? and password=?");
mysqli_stat_bind_param($statement, $username, $pasword);
mysqli_stat_execute($statement);
mysqli_stat_store_result($statement);
mysqli_stat_bind_result($statement, $id, $name, $username, $password);
$user = array();
while (mysqli_stat_fetch($statement)) {
$user[name] = $name;
$user[username] = $username;
$user[password] = $password;
}
echo json_encode($user);
mysqli_stat_close($statement);
mysqli_close($con);
But every time I call this script I get the error as
Fatal error call to undefined function mysqli_stat_bind_param()
You have to change your mysqli_stat_* calls to mysqli_stmt_* calls.
You also should use quotes when using associative arrays:
$user['name'] = $name;
$user['username'] = $username;
$user['password'] = $password;
instead of
$user[name]=$name;
$user[username]=$username;
$user[password]=$password;

Fatal error: Call to a member function query() on a non object

I've got this error:
Fatal error: Call to a member function query() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/login.php on line 8
The line is this:
$res = $mysqli->query("SELECT * FROM user WHERE user='$user' and password='$pw'");
This is login.php:
$user = $_POST['user'];
$pass = $_POST['pass'];
$pw = md5($pass);
include_once('connect.php');
function check_login($user,$pw,&$result){
$res = $mysqli->query("SELECT * FROM user WHERE user='$user' and password='$pw'");
$cont = 0;
while($row = $res->fetch_object()){
$cont++;
$result = $row;
}
if($cont == 1){
return 1;
}
else{
return 0;
}
}
if(!isset($_SESSION['userid'])){
if(isset($_POST['login'])){
if(check_login($user,$pw,$result) == 1){
session_start();
$_SESSION['userid'] = $result->id_user;
header("location:index.php?var=ok");
}
else{
header('location:index.php?var=log');
}
}
}
And the code of connect.php :
$mysqli = new mysqli('localhost', 'root', 'pass', 'cms' );
if ($mysqli->connect_error) {
die('Error de Conexión (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
What could be the problem? Problems connecting the database?
This is most likely a scoping issue. This means that the variable $mysqli that you define in your included file is outside of the check_login function's scope (i.e. is not known inside this function).
You could try to get the $mysqli variable from global scope with
function check_login($user,$pw,&$result){
global $mysqli;
$res = $mysqli->query("SELECT * FROM user WHERE user='$user' and password='$pw'");
// ...
Edit: Oh, and you should also mind the SQL injection vulnerabiliy in your code. Use prepared statements to prevent this issue (or at least escape your input variables with a function like mysqli::real_escape_string).
function check_login($user,$pw,&$result){
global $mysqli;
$res = $mysqli->query("SELECT * FROM user WHERE user='$user' and password='$pw'");
$cont = 0;
while($row = $re[...]
Mind the "global". This puts the var in the scope of your method.
This is a quick and dirty solution, but will work in this case.
It looks like your $mysqli variable is not being set properly within the scope of your code thats executing the query. Can you confirm that $mysqli is indeed a mysqli object and not, say, set to null?
You can check this by doing: echo print_r($mysqli); right before you call the ->query method in your code.
If it is not set properly, track the variable backward in your code until you see why
variable $mysqli in function check_login is out of scope (it is declare outside the function) so it is null.
public function connectDB($DBServer, $DBUser, $DBPass, $DBName) {
global $con;
$con = new mysqli($DBServer, $DBUser, $DBPass, $DBName) or die ("Error occured");
return $con;
and then pass $con in all the functions that you define or run wherever.

"Undefined Variable" notice

Im new to php so im sure this is an easy one. Im getting this error
Notice: Undefined variable: conn in C:\Dev\Webserver\Apache2.2\htdocs\EclipsePHP\thecock\php\db.php on line 23
for this code
<?php
$host = "localhost"; $database = "dbname"; $username = "user"; $password = "pass";
$conn = new mysqli($host, $username, $password, $database);
if (! $conn) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}else{
echo("all ok!");
}
function getContent($id) {
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) { # line 23
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}
?>
How do I fix the notice?
Change your function to:
function getContent($id, $conn) {
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) {
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}
You don't declare the "original" $conn in the scope of the function. Inside the function you only have access to variables declared inside the function or provided via parameters.
Another way would be to declare the variable as global in your function:
function getContent($id) {
global $conn;
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) {
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}
But you should only do this, if there is no other way. Globals make it hard to debug and maintain the code.
See also Variable scope and why global variables are bad.
Edit:
Yes e.g. you can have a DB class:
class DB {
private static $conn = null;
public static function getConnection() {
if (is_null(DB::$conn)) {
$host = "localhost"; $database = "dbname"; $username = "user"; $password = "pass";
DB::$conn = new mysqli($host, $username, $password, $database);
}
return DB::$conn;
}
}
Of course this is not the best implementation ;) But it should give you the right idea. Then you can get the the connection:
DB::getConnection()
conn is a global variable. To access it within a function:
function getContent($id) {
global $conn;
...
}
Otherwise the function can't see it.

Categories