SQL Login System - php

I coded this login system, but whenever I try to log in with the only username and password included in my database table, I get redirected to index.php?error=sqlerror. I checked the code for spelling mistakes but there are none. Could this be a problem with the database connection? I use MAMP. I have checked the database and it displays the Success message so it seems to be working. Do you know what I am doing wrong? Thank you!
DATABASE CONNECTION (file name: dbh.inc.php)
$servername = "127.0.0.1";
$dBUsername = "root";
$dBPassword = "";
$dBName = "gallerydatabase";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
if (!$conn) {
echo "Error: Unable to connect to MySQL.";
}
echo "Success";
mysqli_close($conn);
?>
LOG-IN PHP CODE (file name: login.inc.php)
if (isset($_POST['login-submit'])) {
require 'dbh.inc.php';
$mailuid = $_POST['mailuid'];
$password = $_POST['pwd'];
if (empty($mailuid) || empty($password)) {
header ("Location: ../index.php?error=emptyfields");
exit();
}
else {
$sql = "SELECT * FROM users WHERE uidUsers=?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header ("Location: ../index.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $mailuid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$pwdCheck = password_verify($password, $row['pwdUsers']);
if ($pwdCheck == false) {
header ("Location: ../index.php?error=wrongpwd");
exit();
}
else if ($pwdCheck == true) {
session_start();
$_SESSION['userId'] = $row['idUsers'];
$_SESSION['userUid'] = $row['uidUsers'];
header ("Location: ../index.php?login=sucess");
exit();
}
else {
header ("Location: ../index.php?error=wrongpwd");
exit();
}
}
else {
header ("Location: ../index.php?error=nouser");
exit();
}
}
}
}
else {
header ("Location: ../index.php");
exit();
}

I think the problem is in your file dbh.inc.php, you create the connection $conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName); and later you close it as well mysqli_close($conn);.
So by the time you come to use $conn in login.inc.php your connection is closed. What you need to do is write a function in dbh.inc.php that returns a live connection (don't call close), use that to do your DB queries / insert and after that close the connection.
A reusable database class can be written (functional style) as follows
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
trait DBInfo {
protected $servername = "127.0.0.1";
protected $username = "root";
protected $password = "";
protected $dbname = "gallerydatabase";
}
class Database{
use DBInfo;
function __construct() {}
function connection(){
$conn = new mysqli($this->servername, $this->username,
$this->password, $this->dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else{
$conn->autocommit(FALSE);
return $conn;
}
}
function select($sql, $fn2bind_takestmt, $fn2process_row_return_result){
try{
$result = array();
$conn = $this->connection();
$stmt = $conn->prepare($sql);
$fn2bind_takestmt($stmt);
$stmt->execute();
$rowset = $stmt->get_result();
while ($row = $rowset->fetch_assoc()) {
$obj = $fn2process_row_return_result($row);
array_push($result, $obj);
}
}catch(Exception $e) {
$result = NULL;
throw $e;
}finally{
if(isset($rowset))$rowset->close();
if(isset($stmt))$stmt->close();
if(isset($conn))$conn->close();
}
return $result;
}
// You can introduce functions for insert, update and delete as well
}
?>
and then for database selects for example login check
<?php
function allow_login($user, $pwd){
$sql = "SELECT count(*) rec_count FROM users WHERE uidUsers=? and pwdUsers=?"
$db = new Database();
$result = $db->select($sql,
function($stmt) use($user, $pwd){
$stmt->bind_param("ss", $user, $pwd);
},
function($row){
if($row['rec_count'] > 0){// or whatever
return TRUE;
}
return FALSE;
}
);
if(isset($result)){
return $result[0];
}
return $result;
}
?>

Related

Cant connect mysql and php

I tried to connect my MySQL database kuvarskir with my PHP code. Then inputted this into html:
<?php
include "mysql.php";
$recepti = execute_sql("SELECT * FROM recepti");
foreach($recepti as $recept)
{
?>
<article>
<h2><?=$recept["naziv"]?></h2>
<i><?=$recept["sastojci"]?></i>
<p><?=$recept["uputstvo"]?></p>
</article>
<?php
}
?>
but its not working.
i think there is error with mysql.php file, here's the code:
<?php
function init_sql()
{
global $conn;
$host = "localhost";
$db = "kuvarskir";
$username = "root";
$password = "root";
try
{
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$conn = new PDO("mysql:host=$host;dbname=$db", $username, $password, $pdo_options);
}
catch(PDOException $e)
{
die("Database connection failed!");
}
}
function execute_sql($sql, $params=[])
{
global $conn;
if ($conn == null)
init_sql();
try
{
$stmt = $conn->prepare($sql);
$stmt->execute($params);
$data = array();
if ($stmt->columnCount() == 0) //INSERT / UPDATE
return $stmt->rowCount();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
$data[] = $row;
return $data;
}
catch(Exception $e)
{
die("somting glitched. error is: $e");
}
}
?>
maybe, there is problem with my localhost, which is localhost:8080/phpmyadmin
also here is picture of database

External file with PDO connection not working

I realize this question has been asked in some form or another multiple times, but none of the solutions on the other versions of this question work for me.
These two files have no issues:
/blog/login.php
<?php
include('core/init.php');
if (empty($_POST) === false){
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) || empty($password)) {
$errors[] = 'Missing username and/or password.';
} else if (user_exists($username) === false) {
$errors[] = 'User doesn\'t exist.';
}else if (user_active($username) === false) {
$errors[] = 'User account not activated.';
}else {
//
}
print_r($errors);
}
?>
/blog/core/init.php
<?php
require('database/connect.php');
require('functions/users.php');
require('functions/general.php');
session_start();
$errors = array();
?>
I'm just including them to show you how connect.php is require()'d (indirectly) in users.php.
/blog/core/database/connect.php
<?php
$dbname = "xxx_forms";
$servername = "mysql.xxx.com";
$usr= "xxx_xxx";
$pass = "xxxxxxxx";
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $usr, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
This connection itself doesn't trigger any errors...
/blog/core/functions/users.php
<?php
function user_exists($username) {
$ret = '';
try {
$sql = "SELECT COUNT(id) FROM registration WHERE user = '$username';";
$q = $pdo->query($sql);
$f = $q->fetch();
$ret = $f[0];
} catch (PDOException $e) {
die("Could not connect to the database $dbname :" . $e->getMessage());
}
return ($ret == 1) ? true : false;
}
However, when we get to users.php, I always get an error at the $q = $pdo->query($sql); line, apparently because PHP doesn't know what $pdo is. On the other hand, when I include the code from connect.php, so that it is not in an external file (exactly like below, but not commented out):
function user_exists($username) {
//$dbname = "xxx_forms";
//$servername = "mysql.xxx.com";
//$usr= "xxx_xxx";
//$pass = "xxxxxxxx";
$ret = '';
try {
//$pdo = new PDO("mysql:host=$host;dbname=$dbname", $usr, $pass);
$sql = "SELECT COUNT(id) FROM registration WHERE user = '$username';";
$q = $pdo->query($sql);
$f = $q->fetch();
$ret = $f[0];
} catch (PDOException $e) {
die("Could not connect to the database $dbname :" . $e->getMessage());
}
return ($ret == 1) ? true : false;
}
...everything works the way it is supposed to.
How do I make it work when the PDO connection is done in the external file connect.php?
Further to my comment, you need to do something like this:
/config.php
<?php
define('DS',DIRECTORY_SEPARATOR);
define('DB_HOST','localhost');
define('DB_NAME','database');
define('DB_USER','root');
define('DB_PASS','');
define('ROOT_DIR',__DIR__);
define('FUNCTIONS',ROOT_DIR.DS.'functions');
# Add the connection function
require_once(FUNCTIONS.DS.'connect.php');
# Start session
session_start();
# Get the connection
$pdo = connect();
/functions/connect.php
function connect()
{
$pdo = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
/functions/user_exists.php
<?php
function user_exists($pdo,$username)
{
$ret = 0;
try {
$sql = "SELECT COUNT(id) as count FROM registration WHERE user = :username";
$q = $pdo->prepare($sql);
$q->execute(array(":username"=>$username));
$f = $q->fetch(PDO::FETCH_ASSOC);
$ret = $f['count'];
}
catch (PDOException $e) {
die("Could not connect to the database ".DB_NAME.":" . $e->getMessage());
}
return ($ret == 1);
}
Here is an example of use:
/index.php
<?php
# Add the basic stuff
require(__DIR__.DIRECTORY_SEPARATOR.'config.php');
# Add our functions
require(FUNCTIONS.DS.'user_exists.php');
require(FUNCTIONS.DS.'general.php');
# Example of use
print_r(user_exists($pdo,'username#email.com'));

I can't run my PHP program and I received several errors

This is the image of the warning I got
I am new and I really want to learn PHP.
<?php
include 'mysql.conf.php';
if(isset($_POST['submit']))
{
if(!empty($_POST['user']) && !empty($_POST['password']))
{
$user = $_POST['user'];
$password = $_POST['password'];
$select = "SELECT * FROM admin where user=$user && password=$password";
$sql=mysql_query($select) or die(mysql_error());
if($sql)
{
echo "Login";
}
else
{
echo "Cannot Login";
}
}
}
?>
Below is my code for the mysql.conf.php
<?php
$name = "localhost";
$user = "root";
$pass = "gasamul";
$connect = mysql_connect($name, $user, $pass) or die(mysql_error());
$db = "portfolio";
if($connect)
{
$db = mysql_select_db($db) or die(mysql_error());
if($db)
{
//echo 'Database Connect';
}
}
else
{
echo 'Database can\'t connect';
}
?>
The name of my database is portfolio. I also named my table admin.
Since the error is stating clear that mysql_* extension is already deprecated and it is suggesting that you use mysqli_* or PDO extension.
Lets try the first option - mysqli_*. We establish first the connection to your database in mysql.conf.php:
$connect = new mysqli("localhost", "root", "gasamul", "portfolio");
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
Then, we can proceed with logintest.php:
include 'mysql.conf.php';
if(isset($_POST['submit']) && !empty($_POST['user']) && !empty($_POST['password']))
{
if($stmt = $con->prepare("SELECT * FROM admin WHERE user = ? AND password = ?")){ /* PREPARE YOUR QUERY */
$stmt->bind_param("ss", $_POST['user'], $_POST['password']); /* BIND THESE TWO VARIABLES TO THE QUERY ABOVE RESPECTIVELY; s STANDS FOR strings */
$stmt->execute(); /* EXECUTE THE QUERY */
$stmt->store_result(); /* STORE THE RESULT */
$noofrows = $stmt->num_rows; /* GET THE NUMBER OF RESULT */
if($noofrows > 0){ /* CHECK IF RESULT IS MORE THAN 0 */
echo "Login";
} else {
echo "Cannot Login";
}
$stmt->close(); /* CLOSE THE PREPARED STATEMENT */
}
}
You can also check out password_hash() for securing your password in your database.

Not checking for User if existing

I want to check if a user exists or not.
It keeps registering users even though I added a check inside. The echo does not give me a accurate feedback on how to fix this issue.
Edit:
Code edited due to comments. It does not exit or check for the existing user.
Here is my code:
if($_POST['username']) {
if ( $password == $c_password ) {
$db_name = '*';
$db_user = '*';
$db_password = '*';
$server_url = '*';
$mysqli = new mysqli($server_url , $db_user, $db_password, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
} else {
$check="SELECT * FROM USER WHERE 'Name'='". $username."'";
$rs = mysqli_query($mysqli,$check) or die(mysqli_error($mysqli));
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
if($data[0] > 1) {
echo "User Already in Exists<br/>";
exit;
}
else
{
$stmt = $mysqli->prepare("INSERT INTO USER (Name, Password) VALUES (?, ?)");
$password = md5($password);
$stmt->bind_param('ss', $username, $password);
/* execute prepared statement */
$stmt->execute();
if ($stmt->error) {error_log("Error: " . $stmt->error); }
$success = $stmt->affected_rows;
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
error_log("Success: $success");
if ($success > 0) {
error_log("User '$username' created.");
echo '{"success":1}';
} else {
echo '{"success":0,"error_message":"Username Exist."}';
}}
}
} else {
echo '{"success":0,"error_message":"Passwords does not match."}';
}
} else {
echo '{"success":0,"error_message":"Invalid Username."}';
}

PHP to mySQL check if user exists

I have a script that updates/creates user from an iOS device. Now i want to have the script also check if the user already exists in the database. I am going to restrict this to username for now, so no more than ONE unique username may exist. I have an if-statement in my PHP but i cannot get it to work - help please :).
<?php
header('Content-type: application/json');
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
$db_name = 'dbname';
$db_user = 'dbuser';
$db_password = 'dbpass';
$server_url = 'localhost';
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
$userexists = mysql_query("SELECT * FROM users WHERE username='$username'");
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
}
if(mysql_num_rows($userexists) != 0) {
echo '{"success":0,"error_message":"Username Exist."}';
}
else {
$stmt = $mysqli->prepare("INSERT INTO users (username, password, email) VALUES (?, ?, ?)");
$password = md5($password);
$stmt->bind_param('sss', $username, $password, $email);
/* execute prepared statement */
$stmt->execute();
if ($stmt->error) {error_log("Error: " . $stmt->error); }
$success = $stmt->affected_rows;
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
error_log("Success: $success");
if ($success > 0) {
error_log("User '$username' created.");
echo '{"success":1}';
}
else {
echo '{"success":0,"error_message":"Username Exist."}';
}
}
}
else {
echo '{"success":0,"error_message":"Passwords does not match."}';
}
}
else {
echo '{"success":0,"error_message":"Invalid Username."}';
}
}
else {
echo '{"success":0,"error_message":"Invalid Data."}';
}
?>
You could SELECTthe table before trying to insert username. If it already exists (= you have a result) you dont simply insert.
Better yet, use ON DUPLICATE IGNORE or something like that.

Categories