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

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';

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'];

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?

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!

How to connect to MySQLi server

I have a login-script, but when i proceed it there com a error:
Undefined property: Users::$host in C:\wamp\www\userlogin\classes\class.database.php on line 8
There is 4 files:
<?php
session_start();
include "classes/class.users.php";
if(isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$users->login($username, $password);
}
?>
<!DOCTYPE html>
<head>
<title>Basic Login Script</title>
</head>
<body>
<form method="POST" action="" name="login">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="login" value="Login">
</form>
</body>
</html>
<?php
class Database
{
public function __construct()
{
$host = 'localhost';
$user = 'root';
$pass = 'password';
$name = 'usersystem';
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name);
if ($mysqli->connect_errno)
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
echo $mysqli->host_info . "\n";
}
} ?>
<?php
include "class.database.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(); ?>
//dashboard
<?php echo "error"; ?>
I use localhost/index.php to run and the 3 files class.database.php and class.users.php dahsboard.php is in the directory: classes
Mybe it is a syntax-error, but i can not locate it.
I have created a database in phpmyadmin and inserted the data.
Can anybody help me?
You can't use $this for local variable, they will need to be property of the class, and you need a public one for the connection, like this:
<?php
class Database {
public $mysqli;
private $host = 'localhost';
private $user = 'root';
private $pass = 'password';
private $name = 'usersystem';
public function __construct() {
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name);
if ($this->mysqli->connect_errno) {
echo "Failed to connect to MySQL: (". $this->mysqli->connect_errno . ") ";
}else{
echo $this->mysqli->host_info . "\n";
}
}
}
?>
Other thing I notice is you don't start a session before setting it.
You should also exit after redirecting
if($stmt->fetch()) {
session_start();
$_SESSION['username'] == $username;
header("Location: dashboard.php");
exit;
}
Try changing your database connection to this:
class Database
{
// Since you are calling this variable in other methods
// you need to make it available.
public $mysqli;
public function __construct()
{
$host = 'localhost';
$user = 'root';
$pass = 'password';
$name = 'usersystem';
$this->mysqli = new mysqli($host, $user, $pass, $name);
// You are mixing local with class-wide variables. Should all conform.
if ($this->mysqli->connect_errno)
echo "Failed to connect to MySQL: (".$this->mysqli->connect_errno.")".$this->mysqli->connect_error;
echo $this->mysqli->host_info."\n";
}
}
in the __construct method for Database change $user to $this->user, $host to $this->host etc..

Check user credentials PHP MySQL

Im trying to create a user management section on my website that allows users to login.
So far I have the following PDO Conenction class...
<?php
class connection{
private $host = 'localhost';
private $dbname = 'dbname';
private $username = 'liam#';
private $password ='Password';
public $con = '';
function __construct(){
$this->connect();
}
function connect(){
try{
$this->con = new PDO("mysql:host=$this->host;dbname=$this->dbname",$this->username, $this->password);
$this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo 'We\'re sorry but there was an error while trying to connect to the database';
file_put_contents('connection.errors.txt', $e->getMessage().PHP_EOL,FILE_APPEND);
}
}
}
?>
My check-login.php looks like...
<?php
include 'assets/connection.class.php';
$username=$_POST['username'];
$password=$_POST['password'];
function login(PDO $db, $username, $password) {
$user_id = user_id_from_username($db, $username);
$password = md5($password);
$stmt = $db->prepare('SELECT COUNT(`user_id`) FROM `users` WHERE `username` = ? AND `password` = ?');
$stmt->bindParam(1, $username);
$stmt->bindParam(2, $password);
$stmt->execute();
if($stmt->fetchColumn() > 0) {
return $user_id;
} else {
return false;
echo 'failed';
}
}
?>
my problem is that im not given any result from check-login.php? Im not a php programmer so apologies if this seems vague, any help will be appreciated
It could be a problem with
$user_id = user_id_from_username($db, $username);
Since we don't know what that function (user_id_from_username) is doing, it might be that the
return $user_id;
is just returning NULL or an empty string.

Categories