How to connect to MySQLi server - php

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

Related

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) ?

Insert into database in OOP doesn't work

I'm trying to make object oriented login and insert into database, following tutorial but this doesn't work. It won't make connection to database, error: No database selected. Can you help me?
This is code:
form in index.php
<form action="insert.php" method="post">
Firstname: <input type="text" name="fname" /><br><br>
Lastname: <input type="text" name="lname" /><br><br>
<input type="submit" />
Class in insert_class.php:
<?php
class Insert_class {
public $servername;
public $username;
public $password;
public $dbname;
public function __construct(){
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// insert into database
$sql = "INSERT INTO nametable (firstname, lastname)
VALUES ('$_POST[fname]','$_POST[lname]')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
}
Object for login and insert in database in insert.php:
require 'insert_class.php';
$insert = new Insert_class();
$insert->servername ='localhost';
$insert->username ='root';
$insert->password ='';
$insert->dbname ='newdatabase';
Try this
<?php
class Insert_class {
private $servername;
private $username;
private $password;
private $dbname;
private $con
public function __construct($servername,$username,$password,$dbname)
{
$this->servername = $servername;
$this->username = $username;
$this->password = $password;
$this->dbname = $dbname;
// Create connection
$this->conn = mysqli_connect($this->servername, $this->username,
$this->password, $this->dbname);
if ($this->con->connect_error) {
die('Connect Error (' . $this->con->connect_errno . ') '. $this->con->connect_error);
}
// etc
}
Then you can do
require 'insert_class.php';
$insert = new Insert_class('localhost','root','','newdatabase');
Notice I also captured the $con as a property. Your code would have lots it as it would only have been visible in __construct but none of the other methods you may want to write in this class.
Also Notice I changed the test for a successful connection. This is the correct way to check if a connection was successful. a simple if( ! $con ) is not good enough.
Rather than defining the connection details explicitly ,you can use DEFINE ..
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("DB_NAME", "newdatabase");
insert_class.php ...
public function __construct(){
$conn = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die(mysql_error());
mysql_select_db(DB_NAME, $conn) or die(mysql_error());
}

Mysqli connection in function PHP

I'm facing a PHP problem. I've searched the web but couldn't find the answer. This is my code so far:
<?php
$db_host = 'db_host';
$db_user = 'db_user';
$db_password = 'db_password';
$db_name = 'db_name';
//not showing you the real db login ofcourse
$conn = mysqli_connect($db_host, $db_user, $db_password, $db_name);
if($conn) {
echo 'We are connected!';
}
Up to here, everyting goes well. The connection is established and 'We are connected!' appears on the screen.
function login($username, $password, $conn) {
$result = $conn->query("SELECT * FROM users");
echo mysqli_errno($conn) . mysqli_error($conn);
}
When I run this function however, the mysqli error 'No database selected pops up. So I added the following piece of code the the file before and in the function, so the total code becomes:
<?php
$db_host = 'db_host';
$db_user = 'db_user';
$db_password = 'db_password';
$db_name = 'db_name';
//not showing you the real db login ofcourse
$conn = mysqli_connect($db_host, $db_user, $db_password, $db_name);
if($conn) {
echo 'We are connected!';
}
if (!mysqli_select_db($conn, $db_name)) {
die("1st time failed");
}
function login($username, $password, $conn, $db_name) {
if (!mysqli_select_db($conn, $db_name)) {
die("2nd time failed");
}
$result = $conn->query("SELECT * FROM users");
echo mysqli_errno($conn) . mysqli_error($conn);
}
$username = 'test';
$password = 'test';
login($username, $password, $conn, $db_name);
?>
The first time adding the database name works fine, however, in the function it doesn't work. I've also tried using global $conn inside the function but that didn't work either. Changing mysqli_connect() to new mysqli() also doesn't have any effect.
Thanks in advance!
Please be aware, this code is refactored based on your code, and the login logic is NOT RECOMMENDED. Please try this code and make the changes that you think you need.
Make sure that your Database information is also updated as needed.
MyDB Class
Class MyDB {
protected $_DB_HOST = 'localhost';
protected $_DB_USER = 'user';
protected $_DB_PASS = 'password';
protected $_DB_NAME = 'table_name';
protected $_conn;
public function __construct() {
$this->_conn = mysqli_connect($this->_DB_HOST, $this->_DB_USER, $this->_DB_PASS);
if($this->_conn) {
echo 'We are connected!<br>';
}
}
public function connect() {
if(!mysqli_select_db($this->_conn, $this->_DB_NAME)) {
die("1st time failed<br>");
}
return $this->_conn;
}
}
Login Class
Class Login {
protected $_conn;
public function __construct() {
$db = new MyDB();
$this->_conn = $db->connect();
}
//This is a HORRIBLE way to check your login. Please change your logic here. I am just kind of re-using what you got
public function login($username, $password) {
$result = $this->_conn->query("SELECT * FROM user WHERE username ='$username' AND password='$password'");
if(!$result) {
echo mysqli_errno($this->_conn) . mysqli_error($this->_conn);
return false;
}
return $result->fetch_row() > 0;
}
}
Usage
$login = new Login();
$logged = $login->login('username', 'password');
if ($logged) {
echo "yeah!! you are IN";
} else {
echo "boo!! . Wrong username and password";
}

MySQL connect on PHP

what is the best way to connect PHP application on MySQL.
So far I had the below connection classes.
class Connection{
private static $server = "127.0.0.1";
private static $catalog = "schemadb";
private static $username = "rootuser";
private static $password = "password";
public static $current = null;
public static function Open(){
self::$current = mysqli_init();
if(!self::$current){
die("Failed to initialize connection");
}
if(!self::$current->real_connect(self::$server,self::$username,self::$password,self::$catalog)){
die("Cannot connect to server");
}
return self::$current;
}
public static function Close(){
self::$current->close();
}
}
and also I have
abstract class abstractDAO
{
protected function getConnection()
{
$mysqli = new mysqli("127.0.0.1","rootuser","password","schemadb");
return $mysqli;
}
}
or if there's any other best approach to connect PHP application on MySQL. Please advise thanks..
You can try using the PDO object:
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Have a look at PHP PDO documentation page
Try to use php frameworks like codeigniter, Yii, cake php. If you implement in any one of this framework no need to write php mysql query It will automatically generate.
You just need to enter your database configuration like give in below
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'sample';
You can connect through data using PDO, here is an example
<?php
$servername = "localhost";
$username = "root";
$password = "nopass";
try {
$conn = new PDO("mysql:host=$servername;dbname=wireframe", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
$stmt = $conn->prepare("SELECT * FROM todolist");
$stmt->execute();
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<table border="1" align="center">
<tr>
<th>name</th>
<th>type</th>
<th>status</th>
</tr>
<?php
foreach($stmt->fetchAll() as $k=>$v){
echo
"<tr>
<td>{$v['name']}</td>
<td>{$v['type']}</td>
<td>{$v['status']}</td>
</tr>\n";
}
?>
</table>
</body>
</html>
try this
<?php
$user = $_POST["username"];//if this doesnt work try the next line
$user = (isset($_POST["username"]) ? $_POST["username"] : "");
$host = "localhost";//mysql password
$username = "";//mysql username
$password = "";//mysql password
$db_name = "database";//database name
$tbl_name ="test";//table name
//make the connection
$con = mysql_connect("$host","username","password")or die("Could not connect.");
$conn = mysql_select_db("$db_name")or die("Could not select database.");
$sql = "SELECT * FROM $tbl_name WHERE username='$username'";
//query mysql
$result = mysql_query($sql);
if($result){
//if it works show this
}else{
//if it doesnt work show this
}
?>
ive tryed a lot of times to make a connection to a database and i finaly found one.

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