Could not connect to database using PHP and Mysql - php

I have an issue.i need to connect my database and fetch the table value.But it is not happening like that.I am explaining my code below.
index.php:
<?php
session_start();
include_once 'dbcon/DBConnection.php';
$dbobj = new DBConnection();
$dbobj->connect();
if (isset($_REQUEST['msg'])){
$msg = urlencode($_REQUEST['msg']);
}
if(isset($_POST["login"])){
//echo 'hii';exit;
$loginid=htmlspecialchars(trim($_POST['txtname']));
$password =sha1(htmlspecialchars(trim($_POST['pwd'])));
//echo $password;exit;
$admin = $dbobj->adminLogin($loginid,$password);
//echo ($admin->result);exit;
if($admin->result == 2){
$msg ='2';
}
if($admin->result ==1){
$_SESSION["admin_id"] = $admin->adminid;
$_SESSION["admin_name"] = $admin->adminname;
$_SESSION["admin_loginid"] = $admin->adminloginid;
header("location:dashboard.php");
}
}
?>
<script>
function valid()
{
var obj = document.frmlogin;
if(obj.txtname.value == "")
{
alert("Please Enter Username");
obj.txtname.focus();
return false;
}
if(obj.pwd.value == "")
{
alert("Please Enter Password");
obj.pwd.focus();
return false;
}
else
{
return true;
}
}
</script>
<form method="post" name="frmlogin" id="frmlogin" action="" autocomplete="off" class="mt">
<label for="" class="text-uppercase text-sm">Username</label>
<input type="text" placeholder="Username" name="txtname" class="form-control mb">
<label for="" class="text-uppercase text-sm">Password</label>
<input type="password" placeholder="Password" name="pwd" class="form-control mb">
<div class="checkbox checkbox-circle checkbox-info">
<input id="checkbox7" type="checkbox" checked>
<label for="checkbox7">
Keep me signed in
</label>
</div>
<button class="btn btn-primary btn-block" name="login" id="login" type="submit" onClick="return valid();">LOGIN</button>
</form>
DBConnection.php:
<?php
class DBConnection{
function __construct() {
}
// destructor
function __destruct() {
// $this->close();
}
public function connect() {
require_once 'dbcon/config.php';
$con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
if ($con->connect_error)die("Connection failed: ");
// return database handler
return $con;
}
public function adminLogin($loginid,$password){
$admin = new AdminUser();
if(ctype_alnum($loginid)){
$sqllogin=sprintf("select * from ".PREFIX."admin where username='%s' and trim(password)='%s' and status=1",mysqli_real_escape_string($con,$loginid),mysqli_real_escape_string($con,$password));
$dbsql=mysqli_query($con,$sqllogin);
$Num = mysqli_num_rows($dbsql);
echo $Num;exit;
if($Num >0){
if($row=mysqli_fetch_array($dbsql)){
$admin->adminid =htmlspecialchars($row['id']);
$admin->adminname =htmlspecialchars($row['name']);
$admin->adminloginid =htmlspecialchars($row['username']);
$admin->result=1;
}
}else{
$admin->result=2;
}
}else{
$admin->result=2;
}
return $admin;
}
}
?>
Here i am trying to echo the number of rows present but its displaying nothing.Please help me to resolve this issue.

As a base of reflection, if you use OOP, use it as OOP and not as function libs.
I started something for you, you just have to use it like this :
$db = new DBConnection('host', 'user', 'pass', 'database_name');
$db->connect();
$data = $db->adminLogin('login', 'password');
-
class DBConnection
{
protected $_host = null;
protected $_user = null;
protected $_pass = null;
protected $_database = null;
protected $_con = null;
public function __construct($host, $user, $pass, $db)
{
$this->_host = $host;
$this->_user = $user;
$this->_pass = $pass;
$this->_database = $db;
}
function __destruct()
{
//$this->close();
}
public function connect()
{
$con = new mysqli($this->_host, $this->_user, $this->_pass, $this->_database);
if ($con->connect_error)
{
die("Connection failed: ");
}
$this->_con = $con;
return $con;
}
public function adminLogin($login, $password)
{
$admin = new AdminUser();
if( ctype_alnum($login) )
{
$sqllogin = sprintf(
"select * from ".PREFIX."admin where username='%s' and trim(password)='%s' and status=1",
mysqli_real_escape_string($this->_con, $login),
mysqli_real_escape_string($this->_con, $password));
$dbsql=mysqli_query($this->_con,$sqllogin);
$Num = mysqli_num_rows($dbsql);
echo $Num;exit;
if($Num >0){
if($row=mysqli_fetch_array($dbsql)){
$admin->adminid =htmlspecialchars($row['id']);
$admin->adminname =htmlspecialchars($row['name']);
$admin->adminloginid =htmlspecialchars($row['username']);
$admin->result=1;
}
}else{
$admin->result=2;
}
}else{
$admin->result=2;
}
return $admin;
}
}
Btw please see about prepare & bindParam & execute & get_result

Related

Registration form in php using oop

I just want to make a registration page but I'm stuck in this error -
Warning: Creating default object from empty value in
C:\wamp\www\2209login\register.php on line 25*
and this one ->
Fatal error: Call to undefined method stdClass::create() in
C:\wamp\www\2209login\register.php on line 30
database.php
<?php
// used to get mysql database connection
class Database{
// specify your own database credentials
private $host = "localhost";
private $db_name = "ooplogin";
private $username = "root";
private $password = "";
public $conn;
// get the database connection
public function getConnection(){
$this->conn = null;
try{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
echo "connected";
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
?>
user.php
<?php
// 'user' object
class User{
// database connection and table name
private $conn;
private $table_name = "users";
// object properties
public $id;
public $firstname;
public $lastname;
public $email;
// constructor
public function __construct($db){
$this->conn = $db;
// create new user record
function create(){
$query = "INSERT INTO
" . $this->table_name . "
SET
firstname = :firstname,
lastname = :lastname,
email = :email";
// prepare the query
$stmt = $this->conn->prepare($query);
// sanitize
$this->firstname=htmlspecialchars(strip_tags($this->firstname));
$this->lastname=htmlspecialchars(strip_tags($this->lastname));
$this->email=htmlspecialchars(strip_tags($this->email));
// bind the values
$stmt->bindParam(':firstname', $this->firstname);
$stmt->bindParam(':lastname', $this->lastname);
$stmt->bindParam(':email', $this->email);
// execute the query, also check if query was successful
if($stmt->execute()){
return true;
}else{
$this->showError($stmt);
return false;
}
}
}
}
register.php
<?php
// core configuration
//include_once "config/core.php";
// set page title
$page_title = "Register";
// include login checker
//include_once "login_checker.php";
// include classes
include_once 'config/database.php';
include_once 'objects/user.php';
//include_once "libs/php/utils.php";
// include page header HTML
//include_once "layout_head.php";
if($_POST){
// get database connection
$database = new Database();
$db = $database->getConnection();
$user->firstname=$_POST['firstname'];
$user->lastname=$_POST['lastname'];
$user->email=$_POST['email'];
// create the user
if($user->create()){
echo "<div class='alert alert-info'>";
echo "Successfully registered. <a href='{$home_url}login'>Please login</a>.";
echo "</div>";
}else{
echo "<div class='alert alert-danger' role='alert'>Unable to register. Please try again.</div>";
}
}
?>
<form action='register.php' method='post' id='register'>
<table class='table table-responsive'>
<tr>
<td class='width-30-percent'>Firstname</td>
<td><input type='text' name='firstname' class='form-control' required value="<?php echo isset($_POST['firstname']) ? htmlspecialchars($_POST['firstname'], ENT_QUOTES) : ""; ?>" /></td>
</tr>
<tr>
<td>Lastname</td>
<td><input type='text' name='lastname' class='form-control' required value="<?php echo isset($_POST['lastname']) ? htmlspecialchars($_POST['lastname'], ENT_QUOTES) : ""; ?>" /></td>
</tr>
<tr>
<td>Email</td>
<td><input type='email' name='email' class='form-control' required value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email'], ENT_QUOTES) : ""; ?>" /></td>
</tr>
<td></td>
<td>
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-plus"></span> Register
</button>
</td>
</tr>
</table>
</form>
Neither data are inserting in database.
Thanks in advance.
You need to separate __construct and create method. In your current code create method is inside constructor, change your user class to:
// 'user' object
class User{
// database connection and table name
private $conn;
private $table_name = "users";
// object properties
public $id;
public $firstname;
public $lastname;
public $email;
// constructor
public function __construct($db){
$this->conn = $db;
}
// create new user record
public function create(){
$query = "INSERT INTO
" . $this->table_name . "
SET
firstname = :firstname,
lastname = :lastname,
email = :email";
// prepare the query
$stmt = $this->conn->prepare($query);
// sanitize
$this->firstname=htmlspecialchars(strip_tags($this->firstname));
$this->lastname=htmlspecialchars(strip_tags($this->lastname));
$this->email=htmlspecialchars(strip_tags($this->email));
// bind the values
$stmt->bindParam(':firstname', $this->firstname);
$stmt->bindParam(':lastname', $this->lastname);
$stmt->bindParam(':email', $this->email);
// execute the query, also check if query was successful
if($stmt->execute()){
return true;
}else{
$this->showError($stmt);
return false;
}
}
}
<?php
include 'db5.php';
//user data insertion in database
class B
{
public function register()
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$username = mysqli_real_escape_string($obj->conn,$_POST['username']);
$email= mysqli_real_escape_string($obj->conn,$_POST['email']);
$password = mysqli_real_escape_string($obj->conn,$_POST['password']);
$repassword = mysqli_real_escape_string($obj->conn,$_POST['repassword']);
$password = md5($password);
$sql2 = "INSERT INTO opps(username, email, password, repassword) values('$username', '$email', '$password', '$repassword')";
$result = mysqli_query($obj->conn, $sql2) or die(mysqli_error($sql2));
echo "Registration Successfull!";
print_r($sql2);
//}
//else
//{
//echo "Registration Failed.";
//}
}
}
public function login()
{
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$emailusername = mysqli_real_escape_string($obj->conn,$_POST['email']);
$password = mysqli_real_escape_string($obj->conn,$_POST['password']);
$password = md5($password);
$sql="SELECT * FROM opps WHERE email = '$emailusername' and password='$password'";
$result=mysqli_query($obj->conn,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
//$active=$row['active'];
//$count=mysqli_num_rows($result);
if ($row['username']==$emailusername && $row['password']==$password)
{
echo "login successfully" .$row['username'];
}
else
{
echo "login failed";
}
}
}
$obj2 = new B();
$obj2->register();
$obj2->login();
?>

I have a MySQL code and I am facing a crisis in 'mysqli_num_rows() expects parameter 1 to be mysqli_result, string given'

This is my code. The connection code and the login page.
<?php
ini_set("display_errors",1);
class connection //create a class for make connection
{
var $host = "localhost";
var $username = "root";
var $password = "";
var $database = "myDb";
var $myconn;
var $select;
var $query;
function database() //create a function for connect to database
{
$conn = mysqli_connect($this->host,$this->username,$this->password);
if(!$conn) // testing the connection
{
die ("Cannot connect to the database");
}
else
{
$this->myconn = $conn;
}
mysqli_select_db($this->myconn,$this->database); //use php inbuil function for select database
if(mysqli_error($this->myconn)) //if error occured display the error message\\
{
echo "Cannot find the database " . $this->database;
}
return $this->myconn;
}
function query($select)
{
$this->query= mysqli_query($this->myconn,$select)or die(mysqli_error($this->myconn));
}
function fetchQuery()
{
return mysqli_fetch_array($this->query);
}
function closeConnection() //close the connection
{
mysqli_close($this->myconn);
}
}
?>
And a page where I am handling it.
<?php
$connection = new connection();
$connection->database();
if(isset($_POST['submit']))
{
$user = $_POST['name'];
$pass = $_POST['password'];
$select = "SELECT * From tab_user where txt_uname ='$user' and txt_pass ='$pass' ";
$result = $connection->query($select);
$count = mysqli_num_rows($result);
if($count>0)
{
$row = $connection->fetchQuery();
$name = $row['txt_full_name'];
echo $name;
$connection->closeConnection();
}
else
{
echo 'Wrong Inputs.';
}
}
?>
<form method="post">
<input type="text" name="name">
<input type="password" name="password">
<input type="submit" name="submit" value="submit">
</form>
I am facing a problem
mysqli_num_rows() expects parameter 1 to be mysqli_result, string given
How can I solve it?
Your query() function does not return anything, but you are trying to work with the return value:
// In code:
$result = $connection->query($select);
$count = mysqli_num_rows($result);
// In class:
function query($select)
{
$this->query= mysqli_query($this->myconn,$select)or die(mysqli_error($this->myconn));
}
You could do the following:
mysqli_num_rows($connection->query);
Or return the result as well as storing it:
function query($select)
{
return $this->query= mysqli_query($this->myconn,$select)or die(mysqli_error($this->myconn));
}
Try this
'.$user.' and '.$pass.'
instead of
'$user' and '$pass'

Login Function [PHP][PDO]

I've been having trouble trying to get my login function to work. Whenever I try to login it always gives me this Syntax error:
Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\cereal_mod\includes\Cereal.php on line 53
I'm not sure if the Database connection is part of the problem but i'm not totally sure what's the big ideal of it not operating correctly.
Here is Database.php
<?php
namespace Cereal;
ini_set('error_reporting', E_ALL);
class Database Extends \PDO
{
public function __construct($dbHost,$dbName,$dbUser,$dbPass)
{
parent::__construct($dbHost,$dbName,$dbUser,$dbPass);
try
{
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
die($e->getMessage());
}
}
#get the number of rows in a result
public function num_rows($query)
{
# create a prepared statement
$stmt = parent::prepare($query);
if($stmt)
{
# execute query
$stmt->execute();
return $stmt->rowCount();
}
else
{
return self::get_error();
}
}
#display error
public function get_error()
{
$this->connection->errorInfo();
}
# closes the database connection when object is destroyed.
public function __destruct()
{
$this->connection = null;
}
}
?>
Here is the login.php
<?php
ini_set('error_reporting', E_ALL);
include "includes/Cereal.php";
$manager = new Cereal;
session_start();
if(isset($_POST['username'], $_POST['password'], $_POST['submit'])){
$login = $manager->login($_POST['username'], $_POST['password']);
}
?>
<form action="" method="POST">
<div id="login">
<input type="username" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" />
</form>
</div>
and lastly Cereal.php
<?php
#namespace Cereal;
ini_set('error_reporting', E_ALL);
class Cereal {
private $configObj;
private $databaseObj;
public $playerData;
public function __construct(){
$this->loadConfig();
if($this->configObj){
try {
$dbHost = $this->configObj['Database']['Host'];
$dbName = $this->configObj['Database']['Database'];
$dbUser = $this->configObj['Database']['User'];
$dbPass = $this->configObj['Database']['Pass'];
$this->databaseObj = new Database('mysql:host=' . $dbHost . ';dbname=' . $dbName, $dbUser, $dbPass);
} catch(\PDOException $ex){
$this->__return($ex->getMessage, true);
}
}
}
private function loadConfig(){
$configPath = getcwd() . '/includes/config/Configuration.json';
$configData = file_get_contents($configPath);
$configObj = json_decode($configData, true);
if(!$configObj){
$this->configObj = $configObj;
} else {
}
}
public function __return($message, $die = false){
$successCheck = $die ? 'false' : 'true';
$messageArr = Array('success' => $successCheck, 'message' => $message);
echo json_encode($messageArr);
if($die) die();
}
public function login($username, $password){
try {
$login = $this->databaseObj->prepare("SELECT * FROM users WHERE username=:username AND password=:password");
$login->bindParam(':username', $username);
$login->bindParam(':password', md5($password));
$login->execute();
$row = $login->fetch(PDO::FETCH_ASSOC);
if($row) {
$_SESSION['auth'] = 1;
$_SESSION['username'] = $username;
die(json_encode(array("error"=>false, "message"=>"")));
} else {
die(json_encode(array("error"=>true, "message"=>"Incorrect credentials")));
}
} catch(PDOException $e) {
error_log('PDOException: ' . $e->getMessage());
die(json_encode(array("error"=>true, "message"=>"Database error, this has been logged.")));
}
}
}
?>
If someone could point out what i'm doing wrong I would really appreciate that because I haven't played with PDO in a while and i'm not sure if I am doing this correctly.
In Database.php you need to change
public function __construct($dbHost,$dbName,$dbUser,$dbPass)
{
parent::__construct($dbHost,$dbName,$dbUser,$dbPass);
}
to
public function __construct($dsn, $dbUser, $dbPass)
{
parent::__construct($dsn, $dbUser, $dbPass);
}
You also have to add use Cereal\Database; in top of Cereal.php
and use PDO; in top of Database.php
Try following:
if(!$configObj){
$this->configObj = $configObj;
} else {
}
should it not be if($configObj) ?

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..

PHP script won't run

I'm currently coding a CMS in PHP in order to get back into PHP (I use to use it all the time). However, for some odd reason, when "including" or "requiring" my classes file, it simply stops the php script, my login form (login.php's html) does not show up (whether I am logged in or not). Any help? Here are two of my scripts:
login.php:
<?php
session_start();
include "classes.php";
if(isset($_GET['logout'])) {
setupSession(2);
}
if($_SESSION['status'] == "online") header("location: admin.php");
if($_POST && isset($_POST['username']) && isset($_POST['password'])) {
$un = $_POST['username'];
$pwd = $_POST['password'];
$mysql = new mySql();
$mysql->validateUser($un, $pwd);
} else $attempt = 2;
?>
<html>
<head>
<title>Log In</title>
</head>
<body>
<form method="post" action="">
<label for="username">username: </label>
<input type="text" name="username" />
<label for="password">password: </label>
<input type="password" name="password" />
<input type="submit" value="Log In" name="submit" />
</form>
</body>
</html>
and classes.php
<?php
class mySql {
protected $dbname;
protected $dbuser;
protected $dbpass;
protected $db;
private $conn;
function __construct() {
$conn = new mysqli($dbname, $dbuser, $dbpass, $db);
}
public function validateUser($username, $password) {
$query = "SELECT * FROM users WHERE username = ? AND password = ? LIMIT 1";
if($stmt = $this->conn->prepare($query)) {
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
if($stmt->fetch()) {
$stmt->close();
setupSession(1);
} else $attempt = 1;
}
}
}
function setupSession($status) {
switch($status) {
case 1:
$_SESSION['status'] = "online";
//other user variables
header("location: admin.php");
break;
case 2:
unset($_SESSION['status']);
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 1000);
}
session_destroy();
break;
default:
session_start();
if($_SESSION['status'] != "online") header("location: login.php");
break;
}
}
?>
You have a scope problem.
$conn = mysqli(....)
should be $this->conn = mysqli(....)
There are not lots of reasons for a required script to break the parent : the required file does not exist, it has an error or it calls exit() or die().
Are you sure that the file classes.php is in the same folder as your script, or in the include path ?
Is this the exact code you are using ?
With a constructor like this :
function __construct() {
$conn = new mysqli($dbname, $dbuser, $dbpass, $db);
}
How the hell do you connect to your database ?
$mysql = new mySql();
function __construct() {
$conn = new mysqli($dbname, $dbuser, $dbpass, $db);
}
Should Be
function __construct($dbname, $dbuser, $dbpass, $db) {
$this->dbname = $dbname;
$this->dbuser = $dbuser;
$this->dbpass = $dbpass;
$this->db = $db;
$this->connect();
}
function connect()
{
$this->conn = new mysqli($this->dbname, $this->dbuser, $this->dbpass, $this->db);
}
Something of that nature.
error_reporting (1);

Categories