Php Class inside included file not found - php

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?

Related

Why does my script not return a record from mySQL?

I am building a login portal with mySQL and PHP
I have this file (dbc.php):
<?php
class db_connect {
protected $DB_SERVER = "localhost";
protected $DB_USERNAME = "root";
protected $DB_PASSWORD = "";
protected $DB_DATABASE = "mydb";
public function connect() {
$conn = new mysqli($this->DB_SERVER, $this->DB_USERNAME, $this->DB_PASSWORD, $this->DB_DATABASE);
if(mysqli_connect_errno()) {
die("Connection failed: ". mysqli_connect_errno());
}
return $conn;
}
}
?>
Then my actual PHP script (login.php) takes a POST from the login page:
<?php
//include database connection
include("dbc.php");
session_start();
//put post values into variables
$username = $_POST['username'];
$password = $_POST['password'];
//create db connector object
$db = new db_connect();
$conn = $db->connect();
//select correct db
mysqli_select_db($conn,”mydb”);
$username = mysqli_real_escape_string($conn,$username);
$query = "SELECT password FROM mydb.users WHERE username = '$username'";
$result = mysqli_query($conn,$query);
if(mysqli_num_rows($result) == 0)
{
header('Location: sorry.html');
}
$pwhash = $result;
if (password_verify($password, $pwhash)) {
header('Location: welcome.php');
} else {
header('Location: sorry.html');
}
?>
This never returns a value which is odd.
Any help appreciated!
$result holds a MySQLi response resource, not a string or array.
You need to change this line:
$pwhash = $result;
To this:
$pwhash = mysqli_fetch_assoc($result)['password'];

Sql Statement from PHP isnt inserting into Database but doesnt give an error

Thanks to this site i could manage to solve my problems, but my statement isnt going through on my database, but when i copy it and paste it directly to my database, it inserts without any problem. Here my code:
<?php
$ip = "***"; //MySQL Server IP
$user = "***"; //MySQL user
$pw = "***"; //MySQL password
$db = "***"; //Database
$sql_filter = "";
$con = mysqli_connect($ip, $user, $pw, $db);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
function register()
{
$username = $_POST[username];
$vorname = $_POST[vorname];
$nachname = $_POST[nachname];
$geschlecht = $_POST[geschlecht];
$geburtsdate = $_POST[geburtsdatum];
$password = $_POST[password];
$email = $_POST[email];
if($email!="" and $password!="" and $username!="" and $password==$_POST["password_confirm"])
{
$sql_filter = "INSERT INTO `tblUser`(`UserID`, `UserName`, `Vorname`, `Nachname`, `EMail`, `Geschlecht`,`Password`) VALUES ('','$username','$vorname','$nachname','$email','$geschlecht','$password')";
$_SESSION['filter'] = $sql_filter;
$page_query = mysqli_query($con, $_SESSION['filter']);
$page_nums = mysqli_num_rows($page_query);
//header('Location: index.php');
echo $sql_filter;
echo $_SESSION['filter'];
}
else
{
header('Location: 404.html');
}
}
if(isset($_POST['submit']))
{
register();
}
mysqli_close($con);
?>
I think the problem is your $con is undefined in the function register(). So add this in the beginning of your function :
function register()
{
global $con;
... // the rest of your function
}

Login System with a DB Connection Class don't login. Return with else error for invalid login

I'm new with DB classes and working on it. I'm trying to make my old login system work with this DB class but it returns with my else for invalid login error, like there is no such e-mail and password in the DB. But there is.
Connection Class:
class Conexao
{
private $link;
public function __construct($host = null, $username = null, $password = null, $dbName = null)
{
$this->link = mysqli_init();
$this->link->real_connect($host, $username, $password, $dbName) or die("Failed to connect");
}
public function __destruct()
{
$this->link->close();
}
public function Query($sql)
{
return $this->link->query($sql);
}
Login Page:
<?php
include('dbConnect.php');
session_start();
$conexao = new Conexao("localhost", "root", "XXXXX", "festas");
if(isset($_POST['submit'])) {
$email = mysqli_real_escape_string($conexao,$_POST['email']);
$pass = mysqli_real_escape_string($conexao,$_POST['senha']);
$sel_user = $conexao->Query("SELECT * from contas where email='$email' AND senha='$pass'");
$check_user = mysqli_num_rows($sel_user);
$row = mysqli_fetch_assoc($sel_user);
if($check_user>0){
$_SESSION['user_email']=$email;
header('Location: ../adminpage.php');
mysqli_free_result($result);
} else {
header('Location: ../admin.php?erroLogin=1');
}
}
?>
Always it returns with the "else" header('Location: ../admin.php?erroLogin=1'). I think it could be because of "$check_user = mysqli_num_rows($sel_user);" but I tried to fix and can't. Tried also "$conexao->num_rows($sel_user).
I solved it. Here's what I did:
In DB class php:
public function Escape($sql)
{
return $this->link->real_escape_string($sql);
}
then in login php:
$email = $conexao->Escape($_POST['email']);
Thanks!

Fatal error: Using $this when not in object context in C:\xampp\htdocs\BaseballTuts\include\class.user.php [duplicate]

This question already has answers here:
PHP $this when not in object context for set public variable from out of class
(3 answers)
Closed 8 years ago.
I'd got a problem when i'm checking if username is available in the table.
In my class.user.php I've got this error:
* Fatal error: Using $this when not in object context in C:\xampp\htdocs\BaseballTuts\include\class.user.php on line 47 *
this how my class.user.php was written:
<?php
include "db_config.php";
class User{
public $db;
public function __construct(){
$this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
}
/*** for registration process ***/
public function reg_user($name,$nickname,$gender,$birthdate,$address,$email,$short_info,$username,$password){
$password = md5($password);
$sql="SELECT * FROM `user` WHERE `username`='$username' OR `email`='$email'";
//checking if the username or email is available in db
$check = $this->db->query($sql) ;
$count_row = $check->num_rows;
//if the username is not in db then insert to the table
if ($count_row == 0){
$sql1="INSERT INTO `user` SET `name`='$name', `nickname`='$nickname', `gender`='$gender', `birthdate`= '$birthdate', `address`='$address', `email` = '$email', `short_info`= '$short_info', `username` = '$username', `password` = '$password'";
$result = mysqli_query($this->db,$sql1) or die(mysqli_connect_errno()."Data cannot inserted");
return $result;
}
else { return false;}
}
/*** for login process ***/
public function check_login($emailusername, $password){
$password = md5($password);
$sql2="SELECT `user_id` from `user` WHERE `email`='$emailusername' or `username`='$emailusername' and `password`='$password'";
//checking if the username is available in the table
*** $result = mysqli_query($this->db,$sql2);***
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1) {
// this login var will use for the session thing
$_SESSION['login'] = true;
$_SESSION['id'] = $user_data['user_id'];
return true;
}
else{
return false;
}
}
/*** for showing the username or fullname ***/
public function get_fullname($uid){
$sql3="SELECT fullname FROM users WHERE uid = $uid";
$result = mysqli_query($this->db,$sql3);
$user_data = mysqli_fetch_array($result);
echo $user_data['fullname'];
}
/*** starting the session ***/
public function get_session(){
return $_SESSION['login'];
}
public function user_logout() {
$_SESSION['login'] = FALSE;
session_destroy();
}
}
?>
and this how i call check_login:
session_start();
include_once 'include/class.user.php';
$user = new User();
if (isset($_REQUEST['submit'])) {
extract($_REQUEST);
$login = $user->check_login($emailusername, $password);
if ($login) {
// Registration Success
header("location:home.php");
} else {
// Registration Failed
echo 'Wrong username or password';
}
}
Call the function like the code below:
$emailusername = '';
$password = '';
$userObj = new User();
$result = $userObj->check_login($emailusername, $password);
If you still have a problem, I would suggest that you modify your code like the one below:
<?php
include "db_config.php";
class User{
private $db;
public function __construct(){
$this->connect();
}
private function connect($db_connect=true){
if($db_connect){
$this->db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(mysqli_connect_errno()){
printf("DB Connect failed: %s\n", mysqli_connect_error());
exit();
}
}
}
/*** for registration process ***/
public function reg_user($name,$nickname,$gender,$birthdate,$address,$email,$short_info,$username,$password){
// Get the MySQLi object
$db = $this->db;
if(empty($db)){
$this->connect();
$db = $this->db;
}
$password = md5($password);
$sql="SELECT * FROM `user` WHERE `username`='$username' OR `email`='$email'";
//checking if the username or email is available in db
$check = $this->db->query($sql) ;
$count_row = $check->num_rows;
//if the username is not in db then insert to the table
if ($count_row == 0){
$sql1="INSERT INTO `user` SET `name`='$name', `nickname`='$nickname', `gender`='$gender', `birthdate`= '$birthdate', `address`='$address', `email` = '$email', `short_info`= '$short_info', `username` = '$username', `password` = '$password'";
$result = mysqli_query($this->db,$sql1) or die(mysqli_connect_errno()."Data cannot inserted");
return $result;
}
else { return false;}
mysqli_close($db);
$this->db = null;
}
/*** for login process ***/
public function check_login($emailusername, $password){
// Get the MySQLi object
$db = $this->db;
if(empty($db)){
$this->connect();
$db = $this->db;
}
$password = md5($password);
$sql2="SELECT `user_id` from `user` WHERE `email`='$emailusername' or `username`='$emailusername' and `password`='$password'";
//checking if the username is available in the table
*** $result = mysqli_query($this->db,$sql2);***
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1) {
// this login var will use for the session thing
$_SESSION['login'] = true;
$_SESSION['id'] = $user_data['user_id'];
return true;
}
else{
return false;
}
mysqli_close($db);
$this->db = null;
}
/*** for showing the username or fullname ***/
public function get_fullname($uid){
// Get the MySQLi object
$db = $this->db;
if(empty($db)){
$this->connect();
$db = $this->db;
}
$sql3="SELECT fullname FROM users WHERE uid = $uid";
$result = mysqli_query($this->db,$sql3);
$user_data = mysqli_fetch_array($result);
echo $user_data['fullname'];
mysqli_close($db);
$this->db = null;
}
/*** starting the session ***/
public function get_session(){
if(session_id() == '') session_start();
return $_SESSION['login'];
}
public function user_logout() {
if(session_id() == '') session_start();
$_SESSION['login'] = FALSE;
session_destroy();
}
}
?>
First of all, it's better to have private $db, because you're only using this property inside the PHP Class.
Second of all, to avoid having an empty object, you need to check if this object is empty and if it is, you need to connect to the DB and fill that object. Also, you need to close the MySQL connection when you're done and you need to empty the variable.
EDIT 2:
I fixed a small issue in the PHP Session code, because it might throw an error if the Session isn't started.
I also added a flag in the __construct function so that you can call the object without connection to the DB, because the last 2 functions don't need a db call.

Fatal error: Cannot redeclare class Database. How to fix?

I've seen the question asked but the answer wasn't very clear to me.
My code is.
index.php
<?php include 'header.php'; ?>
<?php
include "class.users.php";
if(isset($_POST['login'])) {
$username = $_POST['username1'];
$password = $_POST['password1'];
$users->login($username, $password);
}
?>
class.users.php
<?php
include "connect.php";
class Users extends Database {
public function login($username, $password) {
$stmt = $this->mysqli->prepare("SELECT username, password FROM users WHERE username = ? AND password = ? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1) {
while($stmt->fetch()) {
$_SESSION['username'] == $username;
header("Location: dashboard.php");
}
} else {
return false;
}
$stmt->close();
$stmt->free_result();
}
}
$users = new users();
?>
connect.php
<?php
class Database {
public function __construct() {
$host = 'localhost';
$user = 'root';
$pass = '';
$name = 'meeboo3';
$this->mysqli = new mysqli($host, $user, $pass, $name);
}
}
?>
The class Database isn't called twice? so how is it a error? can anyone explain why in the comments.
you could test to see if its already declared before doing so:
if (!isset($database) && !is_a($database, 'Database')){
$database = new Database();
}
Or
if you're declaring it inside connect.php you could:
include_once 'connect.php';
instead of
include 'connect.php';

Categories