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

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

Related

Cannot add to mySQL database using XAMPP for mac

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

Checking if e-mail exists but returning empty query?

I am trying to write a bit of code that checks if an email exists in my table but keep receiving a "Query was empty" error. I can't seem to find why the query is returning empty?
I am new to PHP and am following a tutorial online for this, the code to which I am following seems to be identical. My code:
recover1.php
<?php require_once('Connections/localhost.php'); ?>
<?php
session_start();
if(isset($_SESSION['MM_Username'])) {
header("Location: My_Account.php");
die;
}
?>
<?php include('functions2.php'); ?>
<?php
$mode_allowed = array('username', 'password');
if (isset($_GET['mode']) === true && in_array($_GET['mode'], $mode_allowed) == true) {
if (isset($_POST['email']) === true && empty($_POST['email']) === false) {
if (email_exists(($_POST['email'])) === true) {
echo "ok";
} else {
echo '<div id="error"> We could not find that email address, please try again. </div>';
}
}
?>
<?php
} else {
header('Location: subscribe.php');
exit();
}
?>
functions2.php
<?php
function sanitize($data) {
return mysql_real_escape_string($data);
}
function recover ($mode, $email) {
$email = sanitize($email);
$mode = sanaitize($mode);
$user_data = user_data(UserID_from_email($email), `Username`);
if ($mode == 'username') {
email($email, 'Your Username', "Hi/n As requested your username is " . $user_data['Username'] . "/n/n Infinity Crates");
} else if ($mode == 'password') {
//recover password
}
}
function email_exists($email) {
$email = sanitize($email);
$query = mysql_query("SELECT COUNT (`UserID`) FROM `users` WHERE `Email` = '$email'");
$result = mysql_query($query) or die(mysql_error());
return (mysql_result($result, 0) == 1) ? true : false;
}
function UserID_from_email($email) {
$email = sanitize($email);
return mysql_result(mysql_query("SELECT `UserID` from `Users` WHERE `Email` = '$email'"), 0, `UserID`);
}
function email($to, $subject, $body) {
mail($to, $subject, $body, 'From: infinitycrate#gmail.com');
}
?>
You're using mysql_query 2 times.
Make it:
function email_exists($email) {
$email = sanitize($email);
$query = "SELECT COUNT (`UserID`) FROM `users` WHERE `Email` = '$email'";
$result = mysql_query($query) or die(mysql_error());
return (mysql_result($result, 0) == 1) ? true : false;
}
You can even modify your function like this:
function email_exists($email) {
$email = sanitize($email);
$result = mysql_query("SELECT * FROM `users` WHERE `Email` = '$email'") or die(mysql_error());
return (mysql_num_rows($result) > 0) ? true : false;
}
Note: Default Mysql API is deprecated from PHP 5.5. Please use PDO and Mysqli instead. For more information you can take a look at http://php.net/manual/en/mysqlinfo.api.choosing.php
Your functions either need to globalize the mysql_connect resource variable or have the resource passed to the function. Check your first require_once file and see if the mysql_connect resource is stored in a variable. If not, modify it to save the resource to a variable like $dbh and modify the "email_exists", "sanitize" and "UserID_from_email" functions by inserting global $dbh; as the first line in those functions.

oop cant get this small script to work properly logging in

I can't figure out why this isn't working. I'm new and just learning.
login.php
<?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
$user = new User();
if (empty($username) === true || empty($password) === true) {
echo 'you need to enter a username and password';
} else if ($user->userExists($username) === false) {
echo 'we cant find that username. have you registered?';
} else echo 'ok';
}
?> <?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
$user = new User();
if (empty($username) === true || empty($password) === true) {
echo 'you need to enter a username and password';
} else if ($user->userExists($username) === false) {
echo 'we cant find that username. have you registered?';
} else echo 'ok';
}
?> <?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
$user = new User();
if (empty($username) === true || empty($password) === true) {
echo 'you need to enter a username and password';
} else if ($user->userExists($username) === false) {
echo 'we cant find that username. have you registered?';
} else echo 'ok';
}
?>
User.php
<?php
require_once 'core/classes/Connect.php';
class User {
private $db;
public function __construct() {
$this->db = new Connect();
$this->db = $this->db->dbConnect();
}
public function userExists($username) {
$st = $this->db->prepare("SELECT COUNT(user_id) FROM users WHERE username=?");
$st->bindParam(1, $username);
$st->execute();
if ($st->rowCount() == 1) {
return true;
} else return false;
}
}
?>
Ive been tring to learn OOP and everyone tells me the best way to learn is to try rather than ask for help. I'm tring to build a simple login and then make it more complex.
When I enter the correct username it doesn't echo ok. Instead, it echos we can't find that username. Have you registered? Any help please. Thanks
I don't know how your Connect-class (and especially the method rowCount) works, but the problem seems to be the following: Your query returns the number of user_ids with the given username but you count rows.
Replacing
$st = $this->db->prepare("SELECT COUNT(user_id) FROM users WHERE username=?");
with
$st = $this->db->prepare("SELECT user_id FROM users WHERE username=?");
should do the trick.
And since you are learning some more comments:
empty($username) === true is equal to empty($username). Most programmers prefer the latter (since its shorter).
Also it seems to make more sense to declare the method userExists as static.

redirect based on user role stored in mysql database

I've made a website that users can now successfully login to but depending on which group the user is in, I would like to redirect them to different pages after logging in. I have a database with a row "training_group" and if for example, they are in group 2013_1, they would be directed to homepage_20131.php after logging in.
I've been looking for tutorials online and have found a possible solution with a switch function? but I am unsure of how/where to implement this. I just started learning php and would be grateful for any advice given!
Right now, my login page looks like this:
<?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = 'please input a username and password first! ';
} else if (user_exists($username) === false) {
$errors[] = 'We could not locate you in our database.';
}
$login = login($username, $password);
if ($login === false) {
$errors [] = 'That username/password combination is incorrect';
}
else {
$_SESSION['user_id'] = $login;
header('Location:logged_in/templates/logged_in_home.php');
exit ();
}
}
else {
$errors [] = 'No data received';
}
include 'includes/overall/header.php';
if (empty ($errors) === false) {
?>
<h2>We tried to log you in, but...</h2>
<?php
echo output_errors($errors);
}
include 'includes/overall/footer.php';
?>
Here are a couple snippets that might get you going in the right direction.
function login($username, $password){
//... your login code .. database call
if($validLogin){
$user_id = id from database;
$group_id = id from database;
$return = array('user_id' => $user_id, 'group_id' => $group_id);
}
else{
$return = false;
}
return $return;
}
$userinfo = login($username, $password);
if ($userinfo === false) {
$errors [] = 'That username/password combination is incorrect';
}
else {
$_SESSION['user_id'] = $userinfo['user_id'];
$_SESSION['group_id'] = $userinfo['group_id'];
$page = 'homepage_' . str_replace('_', '', $userinfo['group_id'] . '.php';
header('Location:' . $page);
exit ();
}

Dont know what i did wrong php login script

As instructed i have to insert the code inbetween the dashed lines.
Supposed to refresh and see 'exists'
I have the correct database, table, everything im pretty sure but
i see no exist.
Should i keep following the guide or did i mess up?
Does anyone have a guide that is GUARANTEED to work if i follow it correctly?
my login.php
<?php
include 'core/init.php';
-----------------------------------------
if (user_exists('alex') === true) {
echo "exists";
}
die('no exist');
-------------------------------------------
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 not find that user';
}
}
?>
i have init.php
<?php
session_start();
error_reporting(0);
require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
$errors = array();
?>
i have users.php
<?php
function user_exists($username) {
$username = sanitize($username);
$query = mysql_query("SELECT COUNT('user_id') FROM 'users' WHERE 'username' = '$username'");
return (mysql_result($query, 0) == 1) ? true : false;
}
?>
i have general.php
<?php
function sanitize($data) {
return mysql_real_escape_string($data);
}
?>
i use:
<form action="login.php" method="post">
note: if anyone is familiar with phpacademy i am following his guide
Your die is always called, you should change your code to:
if (user_exists('alex') === true) {
echo "exists";
}
else{
die('no exist');
}

Categories