Cannot add to mySQL database using XAMPP for mac - php

I hello I am currently trying to add data to my user login database however for some reason my database it not being updated when I register a new user.
here is my code from user.inc.php:
<?php
//checks if username already exists in database
function user_exists($user)
{
$user = mysqli_real_escape_string($user);
$total = mysqli_query("SELECT user_id FROM user_system WHERE user_name= ('$user')");
return (mysql_result($total, 0) == '1') ? true : false;
}
//checks if username and password combo is valid
function valid_credent($user, $pass)
{
$user = mysqli_real_escape_string($user);
$pass = sha1($pass);
$total = mysqli_query("SELECT COUNT user_id FROM users
WHERE user_name = '$user' AND
user_password = '$pass' ");
return(mysql_result($total, 0) == '1') ? true : false;
}
//add user to database
function add_user($user, $pass)
{
$user = mysqli_real_escape_string(htmlentities($user));
$pass = sha1($pass);
$queryStr = "INSERT INTO users (user_name, user_password) VALUES ('$user', '$pass')";
$R = mysqli_query($mysqli,$queryStr);
}
?>
I also have warning on my register page when I try to add view errors
Warning: mysql_result() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/PostalCloud/core/user.inc.php on line 8
line 8:
return (mysql_result($total, 0) == '1') ? true : false;
I have tried using "sanitize()" however that doesn't exists.
UPDATE: Still getting errors after modifying code. Here part of my register.php code and I have a init.inc.php that uses mysqli to connect to database.
<?php
include('init.inc.php');
$errors = array();
if(isset($_POST['username'], $_POST['password'], $_POST['repeatPassword']))
{
if(empty($_POST['username']))
{
$errors[] = 'The username cannot by empty. ';
}
if(empty($_POST['password']) || empty($_POST['repeatPassword']))
{
$errors[] = 'The password cannot by empty. ';
}
if($_POST['password'] !== $_POST['repeatPassword'])
{
$errors[] = 'Password verification failed. ';
}
if(user_exists($_POST['username']))
{
$errors[] = 'The username you entered is already taken. ';
}
if(empty($errors))
{
add_user($_POST['username'], $_POST['password']);
$_SESSION['username'] = htmlentities($_POST['username']);
header('Location: protected.php');
die();
}
}
?>
init.inc.php:
<?php
session_start();
$exceptions = array('register', 'login');
$page = substr(end(explode('/',$_SERVER['SCRIPT_NAME'])), 0, -4);
if(in_array($page, $exceptions) === false)
{
if(isset($_SESSION['username']) === false)
{
header('Location: login.php');
die();
}
}
$mysqli = mysqli_connect('localhost','root','', 'user_system');
$path = dirname(__FILE__);
include("{$path}/core/user.inc.php");
?>

The problem is that mysql_query() is returning a boolean instead of a result resource. There are two reasons this can happen:
You performed query that returns success/fail instead of a result
set (e.g. UPDATE)
Your query failed
your query contains single quotes on column names..this should be removed :
$total = mysqli_query("SELECT user_id FROM user_system WHERE user_name= '$user'");

Related

User authentication PHP mySQL not working

So I am currently building a user authentication system using php and mysql in Xampp.
I have managed to get it to recognize if a user exists by their email address, but the other functions don't seem to be working. For example to check if the user has activated their account or not comes back as they haven't even if I change their active status to 1 in the database. Or with the login function even if both email and password are correct it will say that they are incorrect.
Here is my login.php script
<?php
include 'init.php';
function sanitize($data){
return mysql_real_escape_string($data);
}
//check if user exists
function user_exists($email){
$email = sanitize($email);
//$query = mysql_query("SELECT COUNT('ID') FROM 'register' WHERE 'email' = '$email'");
return (mysql_result(mysql_query("SELECT COUNT(ID) FROM register WHERE email = '$email'"),0) == 1)? true : false;
}
//check if user has activated account
function user_activate($email){
$email = sanitize($email);
//$query = mysql_query("SELECT COUNT('ID') FROM 'register' WHERE 'email' = '$email'");
return (mysql_result(mysql_query("SELECT COUNT(ID) FROM register WHERE email = '$email' AND 'active' =1"),0) == 1)? true : false;
}
function user_id_from_email($email){
$email = sanitize($email);
return (mysql_result(mysql_query("SELECT id FROM register WHERE email = '$email'"),0,'id'));
}
function login($email,$password){
$user_id = user_id_from_email($email);
$email = sanitize($email);
$password = md5($password);
return (mysql_result(mysql_query("SELECT COUNT(id) FROM register WHERE email = '$email' AND 'password' ='$password'"),0) == 1)? $user_id : false;
}
if(empty($_POST)=== false){
$email = $_POST['email'];
$password = $_POST['password'];
}
if(empty($email)|| empty($password) === true){
$errors[] = "You must enter a username and a password";
}
else if(user_exists($email) === false){
$errors[] = "Email address is not registered";
}
else if(user_activate($email) === false){
$errors[] = "You haven't activated your account yet";
}
else{
$login = login($email, $password);
if($login === false){
$errors[] = "email/password are incorrect";
} else {
echo "ok";
}
}
print_r($errors);
/*$email = $_POST['email'];
$password = $_POST['password'];
if($email&&$password){
$connect = mysql_connect("localhost","root","") or die ("Couldn't Connect");
mysql_select_db("users") or die("Couldn't find Database");
}
else
die("Please enter a username and a password");
$query = mysql_query("SELECT * FROM register WHERE email = '$email'");
$numrows = mysql_num_rows($query);
echo $numrows;*/
?>
My database is called 'users' and at the moment only has 1 table called 'register'. With the rows: id, firstname, lastname, email, password, and active.
in your function login, try to remove the quotes ' arround the field name password. Or prefer use this one ` .
And take care, you are using function mysql_result and mysql_query that both are no longer supported in PHP 7.0
As you can see here :
http://php.net/manual/en/function.mysql-query.php
http://php.net/manual/en/function.mysql-result.php

How do I fix this code (due to MySql deprecated)

So I have written this login system, but there is one big problem. Everytime I try to get the $errors to print when the values inputted are contradictory to the code, it doesn't work. This is the user login code
<?php
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = 'Fill out this field!';
} else if (user_exists($username) === false) {
$errors[] = 'Are you sure you\'ve registered?';
} else if (user_active($username) === false) {
$errors[] = 'you haven\'t activated your account!';
} else {
//Login com.
}
print_r($errors);
}
?>
So I don't see any problems here. Where I suspect problems to be are here. This is the general file:
<?php
function sanitize($data) {
return mysqli_real_escape_string($data);
}
?>
and here is the users code:
<?php
function user_active($username, $con){
$username = sanitize($username, $con);
$q = "SELECT COUNT(`user_id`)
FROM `users`
WHERE `username` = '{$username}'
AND `active` = 1";
if($query = mysqli_query($con, $q)){
return (mysqli_num_rows($query) > 0) ? true : false;
} else {
//TODO: Replace in production
trigger_error('<p>Query ' . mysqli_error($con) . '</p>');
}
}
?>
This is the connect code:
<?php
$con = mysqli_connect('localhost', 'root', '') or die(mysql_error());
mysqli_select_db($con, 'users');
?>
I know that MySql is deprecated so I converted to MySqli but it just caused more problems as the codes kept contradicting each other. Any help would be appreciated. Thank you!
Modify like this,
<?php
function sanitize($data, $con) { //$con parameter added
return mysqli_real_escape_string($con, $data); //$con parameter added
}
?>
Read out here

mysqli_data_seek Function Returns Username Result, When Username Not in Database

I have a function in which if a named user is in my database, I'll have a message on my screen of a string value, that simply says my function works.
However, when I change the name to one that doesn't exist in the database, I still get a string output that says the function works. So I am trying to figure out where my logic is messed in the query. Here's what I have:
Users.php File:
<?php
function user_exists($username)
{
$db = "adults";
$dbH = "localhost";
$dbU = "root";
$dbP = "Jeffery9";
//connection to database
$dbCon = mysqli_connect($dbH, $dbU, $dbP, $db);
$username = sanitize($username);
// $query = mysqli_query($dbCon,"SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'");
return (mysqli_data_seek(mysqli_query($dbCon,"SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'"), 0) == 1) ? true : false;
}
?>
Now here's the login page which processes the function to see if a user actually exists:
Login.php File:
<?php
include 'core/init.php';
if (user_exists('raiders7') === true)
{
echo 'user found!';
}
die();
if(empty($_POST) === false)
{
$username = $_POST['username'];
$password = $_POST['password'];
if(empty($username) === true || empty($password) === true)
{
$errors[] = 'You need to enter a username and password.';
}
else if (user_exists($username) === false)
{
$errors[] = 'We can\'t find that username. Have you registered?';
}
}
?>
Of course I have one row and one user in the database. When the string is user_exists('raiders7'), I get user found! on my index page.
But when it's user_exists('something else') it still returns user found! on the page.
How is this so? The page should be blank if the user doesn't exist.
Lastly, I'm using another function to sanitize my data like such:
General.php File:
<?php
function sanitize($data)
{
$db = "adults";
$dbH = "localhost";
$dbU = "root";
$dbP = "Jeffery9";
// connection to database
$dbCon = mysqli_connect($dbH, $dbU, $dbP, $db);
return mysqli_real_escape_string($dbCon, $data);
}
?>
Don't know if the last part is helpful, but can someone kindly help me fix my logic on how I can stop getting a user found! message, when the user doesn't exist in my test database. Thank you.
You should fetch the results to get the correct/desired result.
What happens is you just move the pointer then of course there will always be a result set row in index 0
+----------------+
| COUNT(user_id) | // even when count is zero, your condition will still be true
+----------------+
| 0 |
+----------------+
Even when the username is wrong/does not exist!
Fetch the result properly then check the count
$username = $dbCon->real_escape_string($username);
$query = mysqli_query($dbCon,"SELECT COUNT(`user_id`) as total FROM `users` WHERE `username` = '$username'");
$row = $query->fetch_assoc();
$count = $row['total']; // fetch the result!
if($count > 0) {
// true
} else {
// false
}
Or as #Fred said, just use num_rows and much better to bind it:
$sql = 'SELECT * FROM `users` WHERE `username` = ?';
$select = $dbCon->prepare($sql);
$select->bind_param('s', $username);
$select->execute();
if($select->num_rows > 0) {
// found
} else {
// not found
}

Where is the logical flaw in this PHP login code?

There is definitely a logical flaw somewhere in this code, but I can't find it. The issue is that regardless of input, it echo's success (simulating a redirect to the main page). I don't know why. Here's the code:
$signIn = new UserService($dbuser, $dbpass, $dbhost, $dbname); //Create new class instance
$signIn->sec_session_start(); //Begin session
$_SESSION['token'] = $token; //Store token valualbe in super global variable
//***************************************************************************************//
//***************************************************************************************//
//Begin Login Functions
if(isset($_POST['username'], $_POST['password'],$_POST['siteToken'])) {
//Assign POST submissions to passable php variables
$username = $_POST['username'];
$password = $_POST['password'];
$passedToken = $_POST['siteToken'];
//Check Token Values (prevent CSRF attacks)
/*
if($passedToken != $_SESSION['token']) {
$error = "CSRF attack detected. Please close your browser and try again.";
$signIn->csrfAttackLog($username);
echo $error;
exit();
}
*/
//Test if both fields are not null
if($username == "" || $password = "")
{
$error = "Not all fields were entered<br />";
echo $error;
exit();
}
//Start login process
else
{
$success = $signIn->login($username, $password);
if ($success == true)
{ //Login Successful
echo "Success!"; //Direct to main page.
exit();
}
//Specific login failure determination
else
{
switch ($success){
case 1:
$error = "Your account has been locked.";
echo $error;
break;
case 2:
$error = "Invalid Username/Password (2)";
echo $error;
break;
case 3:
$error = "Invalid Username/Password";
echo $error;
break;
case 4:
$error = "Invalid Username/Password (3)";
echo $error;
break;
}
}
}
Here's the login class method:
public function login($username, $password)
{
//****************//
$this->username = $username;
$this->password = $password;
$user_Id = "";
$user = "";
$hashPassword = "";
$dbPassword = "";
$salt = "";
$userBrowser = "";
//**************// Local declerations
$this->connect(); //connect to database
if ($stmt = $this->dbh->prepare("SELECT UserId, Username, Pass, Salt FROM user WHERE Username = :param1 LIMIT 1")) //Prepared procedure
{
$stmt->bindParam(':param1', $this->username); //Bind $this->username to parameter
$stmt->execute(); //Execute the prepared query
if ($stmt->rowCount() == 1) //If the user exists
{
$this->user = $stmt->fetch(PDO::FETCH_ASSOC); //Grab the variables from the selected database row
$user_Id = $this->user['UserId']; //Transfer variables from array to local variables
$user = $this->user['Username'];
$dbPassword = $this->user['Pass'];
$salt = $this->user['Salt'];
if($user_Id = "")
echo "Why";
//Check if account has been locked
if($this->checkBrute($user_Id, $this->dbh) == true)
{
//Account is locked
return 1; //Used in userControl as a switch condition: Indicates a locked account
//Possibly send an email here
} else {
$hashPassword = hash('sha512', $this->password.$salt); //Hash the password with the unique salt
if($dbPassword == $hashPassword)
{ //Check if the password in the database matches the password the user submitted
//Password is correct!
$userBrowser = $_SERVER['HTTP_USER_AGENT']; // Get the user-agent string of the user
$_SESSION['p_id'] = $user_Id; //Store user id to global session variable
$_SESSION['userName'] = $user; //Store username to global session variable
$_SESSION['loginString'] = hash('sha512', $hashPassword.$userBrowser); //Hash the concentanation of the hashedpassword (password + salt) and userBrowser
//Login succesful!!!!!!
return true;
} else {
//Password is not correct
//Record this attempt in the database
$now = time();
$userIp = $_SERVER['REMOTE_ADDR'];
$insert = $this->dbh->query("INSERT INTO loginattempts (UserId, UserIp, EventTime) VALUES ('$user_Id', 'userIP', '$now')");
if($insert == false){
return 2; //Used in userControl as a switch condition: Indicated a failure to log failed login attempt
} else {
return 3; //Used in userControl as a switch condition: Indicates an inccorect password
}
}
}
}
else
{
//No user exists
return 4;
}
}
}
I know the SQL queries work: I've tested them outside this code. I don't understand why it keeps returning true. PHP hasn't thrown any exceptions or errors (and yes, I've read many times "don't write your own login functions. Use one that already works." This is not a public site. I'm just doing it for the heck of it). Any help is appreciated.
Your login code has various return codes - true if everything works, or numbers to indicate various error states. You're then checking the return value with:
if ($success == true)
PHP isn't strongly typed, so it will cast return values to a boolean for that comparison; and any non-0 integer will evaluate to true. To do a type check, as well as a value check, you need to use the strict comparison operator:
if ($success === true)
That will evaluate true if $success is both true and a boolean.

Login Check User Exists and is Set to Active

I have been trying to get the below code working for a few hours now. The idea is that it checks my database (b00543346) and the table "members" to see if a user exists (thus if their memberID is there. It then checks if a user is set to active.
At present not matter what username/password i enter and press login, this is displayed "Array ( [0] => Username Not Found. Have You Registered? )"
<?php
function user_exists($username) {
$username = sanitize($username);
return (mysql_result(mysql_query ("SELECT COUNT (`membersID`) FROM `members` WHERE `username` = '$username'"), 0) == 1) ? true : false; //check if user id exists
}
function user_active($username) {
$username = sanitize($username);
return (mysql_result(mysql_query ("SELECT COUNT (`membersID`) FROM `members` WHERE `username` = '$username' AND `active` = 1"), 0) == 1) ? true : false; //check if user has activated account
}
?>
<?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = 'You Must Enter a Username AND Password';
} else if (user_exists($username) === false) {
$errors[] = 'Username Not Found. Have You Registered?';
} else if (user_active($username) === false) {
$errors[] = 'You Haven\'t Activated Your Account, Please Do So!';
}
print_r($errors);
}
?>
EDIT: mysql functions in PHP do not like a space between the function name and the first open parenthesis. So count(membersID) will work, while count (membersID) will get you an error!
I'm curious what your sanitize() function is doing. If it at all modifies the username, it seems likely that your initial test data was input into the table manually and not run through the sanitize() function, then as the code sanitizes and perhaps modifies the data, it's not matching in the SQL.
You may also add some debug to your function to see a bit better what is going on. The current function is obfuscating some of what is happening. Try:
function user_exists($username) {
print "DEBUG: username=[$username]\n";
$query = "SELECT COUNT (`membersID`) FROM `members` WHERE `username` = '$username'";
print "DEBUG: query=$query\n";
$result = mysql_query($query);
if (!$result) {
die('Could not execute query:' . mysql_error());
}
print "DEBUG Result Set Array\n";
print_r(mysql_fetch_assoc($result));
print "DEBUG just the result now\n";
print mysql_result($result, 0);
return mysql_result($result, 0) == 1;
}
I'm not too fond of the standard SQL functions of PHP anymore, so I can't judge that. But have you tried
SELECT COUNT (*) FROM `members` WHERE `username` = '$username'

Categories