PHP query not working to check database for username - php

So I made a function that checks if the data that the user enters is already in my database of users. The function works in a testing environment (but runs on open of the page). For some reason it assigns the user input to the $username function regardless of the outcome of the query. I think I may have to AJAX it but I don't know how.
<?php
function checkIfEntered($data, $conn)
{
$query = "SELECT * FROM users
WHERE username= '" . $data . "'";
if ($result = mysqli_query($conn, $query)) {
/* determine number of rows result set */
$row_cnt = mysqli_num_rows($result);
/* close result set */
mysqli_free_result($result);
}
if (($row_cnt) >= 1)
{
return TRUE;
}
if (($row_cnt) == 0)
{
return FALSE;
}
}
error_reporting(E_ALL);
ini_set('display_errors',1);
// define variables and set to empty values
$servername = "localhost"; $username = "root";
$password = "root";
$dbname = "MyDatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$email = '';
$emailErr = '';
$usernameErr = '';
$UserPasswordErr = '';
$username = '';
$UserPassword = '';
$confirm = '';
$confirmErr = '';
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["username"]))
{
$usernameErr = "username is required";
}
else
{
if (checkIfEntered($username, $conn))
{
$usernameErr = "There is already a user with the username: " . $username;
}
else
{
$username = test_input($_POST["username"]);
}
}

You are not even calling the "checkIfEntered" function. Instead, you are calling "isEnteredUsername" function, which I don't see it here. So the code is always going in else and assigning the POST value to $username.
I am not sure why you think AJAXing it will solve the problem, but you can use AJAX call on document ready or some event like this $.ajax({ ... }) as explained here.
http://api.jquery.com/jquery.ajax/

you are forgot return num of record this function "checkIfEntered"
<?php
function checkIfEntered($data, $conn)
{
$query = "SELECT * FROM users
WHERE username= '" . $data . "'";
if ($result = mysqli_query($conn, $query)) {
/* determine number of rows result set */
$row_cnt = mysqli_num_rows($result);
/* close result set */
mysqli_free_result($result);
return $row_cnt;
}
if (($row_cnt) >= 1)
{
return TRUE;
}
if (($row_cnt) == 0)
{
return FALSE;
}
}
error_reporting(E_ALL);
ini_set('display_errors',1);
// define variables and set to empty values
$servername = "localhost"; $username = "root";
$password = "root";
$dbname = "MyDatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$email = '';
$emailErr = '';
$usernameErr = '';
$UserPasswordErr = '';
$username = '';
$UserPassword = '';
$confirm = '';
$confirmErr = '';
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["username"]))
{
$usernameErr = "username is required";
}
else
{
if (checkIfEntered(test_input($_POST["username"]), $conn))
{
$usernameErr = "There is already a user with the username: " . $username;
}
else
{
$username = test_input($_POST["username"]);
}
}
?>

The Problem with this code is the function checkIfEntered() is coming up false because when you pass the $username parameter it has not been assigned. so it is coming up as false.
Code:
if (checkIfEntered(test_input($_POST["username"]), $conn))
{
$usernameErr = "There is already a user with the username: " . $username;
}
else
{
$username = test_input($_POST["username"]);
}
Correction
$username = test_input($_POST["username"]);
if (checkIfEntered(test_input($_POST["username"]), $conn))
{
$usernameErr = "There is already a user with the username: " . $username;
$username = '';
//set username back to nothing to avoid more errors.
}
else
{
$username = test_input($_POST["username"]);
}

Related

password is blank after decoding in base64_decode

I want to save my password in encrypted formatting, so, I saved my password using base64_encode in table, For login when i used to fetch my password again in decode format, using base64_decode, it returns blank data, please help me for better solution.
Here is my code.
login_admin.php
<?php
include('connection.php');
if(isset($_POST['submit'])){
$email = $_POST['email'];
$password = decryptIt($_POST['pwd']);
print_r($password); die;
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
$admin= $_SESSION['email'];
$query = "SELECT * FROM `user` Where (email = '$email' && role_id = 'admin' )";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
if($row > 0){
if($admin == $row['email'] && $password == $row['password']){
header('location:dashboard1.php');
}
}
}
else{
echo "Login Failed";
}
?>
connection.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "example_user";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function encryptIt( $q ) {
$cryptKey = 'qJB0rGtIn5UB1xG03efyCp';
return base64_encode( base64_encode($q).'+'.$cryptKey );
}
function decryptIt( $q ) {
$cryptKey = '+qJB0rGtIn5UB1xG03efyCp';
return base64_decode(str_replace($cryptKey, "",base64_decode( $q ))) ;
}
?>
Code seems fine, try to put check in the "decryptIt" method for empty value in parameter.
function decryptIt( $q ) {
if($q==''){
return array('error'=>1,"msg"=>"parameter cant be empyt")
}else{
$cryptKey = '+qJB0rGtIn5UB1xG03efyCp';
return array('success'=>1,"decrypt"=>base64_decode(str_replace($cryptKey, "",base64_decode( $q ))))
}}

php sqlsrv connection by multiple servers to one specific database

So I have 3 servers(192.168.0.21 , 192.168.0.22 and 192.168.0.23) and I would like them to connect to a database called Pensions they are all using sql server (UID and PWD)authentication. Is it possible to achieve this using php and sqlsrv_connect()? This the connect.php:
<?php
#first start session
session_start();
// session time out after no activity for 4 minutes
if ($_SESSION['TimeOut'] + (5 * 60) < time()) {
// session timed out
header("Location: ./sessdestroy.php");
exit;
} else {
// store new request time.
$_SESSION["TimeOut"] = time();
}
function getConnection(){
$db = 0;
if(!$_SESSION['Database']){
$db = 0;
}else{
$db = $_SESSION['Database'];
}
$databaseName = 'Pension';
if ($db == 0)
{ // Country A
$serverName ='192.168.0.21';
$UID ='sa';
$PWD ='pass!';
$databaseName = 'Pension';
}
else if($db ==1)
{ // Country B
$serverName ='192.168.0.22';
$UID ='sa';
$PWD ='pass!';
$databaseName = 'Pension';
}
else
{ //Country C
$serverName ='192.168.0.23';
$UID ='sa';
$PWD ='pass!';
$databaseName = 'Pension';
}
//connection string
//echo "test here...";
//echo " S: ".$serverName." u: ".$UID." P: ".$PWD;
$serverName = "serverName";
$connectionInfo = array( "Database"=>"$databaseName", "UID"=>"$UID", "PWD"=>"$PWD");
$conn = sqlsrv_connect($serverName,$connectionInfo);
//exit();
//phpinfo();
if (!$conn)
{
exit("Connection Failed: " . $conn);
//try local server
if ($db == 1) {
$serverName ='192.168.0.20';
$UID ='fund_user';
$PWD ='fund_user';
$databaseName = 'Pension';
$conn = sqlsrv_connect($serverName,$connectionInfo);
if (!$conn) return 0;
$stmt = sqlsrv_query($databaseName,$conn);
return $conn;
}
return 0;
}
else
{
$stmt = sqlsrv_query($databaseName,$conn);
return $conn;
}
}
?>
Then this is the process.php (when a connection is established it leads the user to a homepage depending on the user role )
<?php
//give no error
ini_set("display warning",0);
#include connection
include('Connections/fundmaster.php');
if(!isset($_SESSION))
{
session_start();
}
//temp store for the database session before destory
$db = 0;
$db = $_SESSION["Database"];
if ($db==""){
$db = 0;
}
if (!isset($_SESSION["Database"]))
{
$_SESSION["Database"] = 0;
}
$_SESSION["Database"] = $db;
if($_POST['subLogin'])
{
$nationalID = $_POST['sname'];
$PWD = $_POST['Memberno'];
$conn = getConnection();
$sql = "select * from netlogin where NationalID = '";
$sql .= $nationalID ."' and vcPassword= '" .$PWD."'";
$sql = stripslashes($sql);
$stmt = sqlsrv_query($sql, $conn);
if($row = sqlsrv_fetch_array($stmt)){
$SchemeNo = $row[0];
$MemberNo = $row[1];
$userRole = $row[6];
session_start();
if (!isset($_SESSION["SchemeNo"]))
{
$_SESSION["SchemeNo"] = $SchemeNo;
}
if (!isset($_SESSION["MemberNo"]))
{
$_SESSION["MemberNo"] = $MemberNo;
}
if (!isset($_SESSION["userRole"]))
{
$_SESSION["userRole"] = $userRole;
}
$_SESSION["SchemeNo"] = $SchemeNo;
$_SESSION["MemberNo"] = $MemberNo;
$_SESSION["userRole"] = $userRole;
$_SESSION["Database"] = $db;
if($userRole == "1"){
header("Location:admin/adminarea.php");
}else{
header("Location:membersarea.php");
}
}else{
header("Location: login.php");
}
}else{
header("Location: login.php");
}
?>

Error while outputting sessions in other page

I created a login page in PHP with session. everything is going well. but when i try to output the session in other page. it giving me NOTICE
Notice: Undefined variable: email in C:\xampp\htdocs\COIN Website\test5.php on line 81
Notice: Undefined variable: email in C:\xampp\htdocs\COIN Website\test5.php on line 82
Notice: Undefined variable: email in C:\xampp\htdocs\COIN Website\test5.php on line 84
I don't know whats wrong. Actually, I am new to PHP.
here is the login page
<?php
session_start();
if (isset($_POST['submit'])) {
$servername = "localhost";
$username = "root";
$password = "";
$db_name = "coins";
$con = mysqli_connect("$servername", "$username", "$password","$db_name");
$email = mysqli_real_escape_string($con, $_POST['email']);
$eth = mysqli_real_escape_string($con, $_POST['eth']);
if (empty($email) || empty($eth)) {
header("Location: home.php?Login=Empty_fields");
exit();
} else{
$sql = "SELECT * FROM users WHERE email='$email' ";
$result = mysqli_query($con, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck < 1) {
header("Location: home.php?Login=user_does_not_exist");
exit();
}
else {
$check = mysqli_query($con, "SELECT email FROM users WHERE eth='$eth'");
if (mysqli_num_rows($check) >= 1) {
$_SESSION['email'] = $row['email'];
$_SESSION['eth'] = $row['eth'];
header("Location: pow.php?Login=Success");
} else {
header("Location: home.php?Login=invaild_email_or_eth address");
}
}
}
}else {
header("Location: home.php?Login=Error");
exit();
}
?>
and the other page code
if (isset($_POST['submit'])) {
$servername = "localhost";
$user = "root";
$password = "";
$dbname = "coins";
// Create connection
$conn = new mysqli($servername, $user, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$_SESSION['email'] = $email;
echo $email;
$sql = "INSERT INTO profile (email, action_points)
VALUES ('$email' , '0.003')";
if ($conn->query($sql) === TRUE) {
echo "success";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
You can try like this. you are doing wrong with get session variable value.
<?php session_start();
// check session
if(isset($_SESSION['email']))
{
$email = $_SESSION['email'];
// Now you can do your stuff
}
else
{
echo "session not set for email";
die;
}

Having trouble pushing data from a sql query to an array for comparison

So I am trying to compare user input from a form with data from a database, first name, last name, and email. My problem has been comparing my results with the ones that the user put in. What I am trying to do is put the results from my query into an array and then compare each array item against the input of the user. Yet I can't get through my process. What am I doing wrong?
Thank you all in advance.
P.S. I am a php newbie so any suggestions would also be appreciated
<?php
$servername = "localhost";
$username = "jon";
$password = "test";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
//test connection
if($conn -> connect_error) {
die("Connection Error: " . $conn -> connect_error);
}
//input from the user
$firstname = $_POST['first'];
$lastname = $_POST['last'];
$email = $_POST['email'];
//query for the database to select the columns
$queryFirst = "SELECT firstname FROM users";
$queryLast = "SELECT lastname FROM users";
$queryEmail = "SELECT email FROM users";
//query results
$resultFirst = $conn -> query($queryFirst);
$resultLast = $conn -> query($queryLast);
$resultEmail = $conn -> query($queryEmail);
$firstResult = array();
$lastResult = array();
$emailResult = array();
array_push($firstResult, $resultFirst);
array_push($lastResult, $resultLast);
array_push($emailResult, $resultEmail);
$firstValid = mysqli_result::fetch_array($firstResult);
$lastValid = mysqli_result::fetch_array($lastResult);
$emailValid = mysqli_result::fetch_array($emailResult);
//comparing query results to user input
foreach($firstResult as $comp) {
if(strpos($firstname, $comp) !== false) {
$firstname = true;
} else {
return false;
}
}
foreach($lastResult as $comp) {
if(strpos($lastname, $comp) !== false) {
$lastname = true;
} else {
return false;
}
}
foreach($emailResult as $comp) {
if(strpos($email, $comp) !== false) {
$email = true;
} else {
return false;
}
}
//redirection if successful or if failure
$success = "../loggedin.php";
$failure = "../fail.php";
if($firstname && $lastname && $email = true) {
header($success);
exit();
} else {
header($failure);
exit();
}
$conn -> close();
?>
Okay so first thing as already told you andrewsi, you can get all the info in one query. But if you want to select only one row, you should use a WHERE clause telling what to look for.
Check this:
<?php
$servername = "localhost";
$username = "jon";
$password = "test";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
//test connection
if($conn -> connect_error) {
die("Connection Error: " . $conn -> connect_error);
}
//input from the user . addslashes is for security, so they won't break your query and potentially abuse it.
$firstname = addslashes($_POST['first']);
$lastname = addslashes($_POST['last']);
$email = addslashes($_POST['email']);
//query for the database to select the columns
$query = "SELECT firstname, lastname, email FROM users WHERE firstname = '$firstname' and lastname = '$lastname' and email = '$email'";
//query results
$result = $conn -> query($query);
$numRows = $result->num_rows;
//redirection if successful or if failure
$success = "../loggedin.php";
$failure = "../fail.php";
if($numRows > 0) {
header($success);
exit();
} else {
header($failure);
exit();
}
$conn -> close();
?>
Haven't tested it but the idea is to check for a match in the query, not afterwards. Then if there's a match, it will return at least one row (if you defined your table correctly it shouldn't be possible to have duplicates).
Then based on that you make your choice.

ADMIN panel doesn't operate

This is my admin panel for Add and Delete users from the members table in my database but when I press OK it doesn't operate:
I don't know where the problem is.
I'm not pro in PHP so please provide easy to understand answers.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user="admin";
$pass="whatever";
$host="localhost";
$db_name="login";
$con=mysqli_connect($host, $user, $pass, $db_name);
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = ($_POST['id']);
$password = md5($_POST['pass']);
$fieldset = ($_POST['fieldset']);
$id = mysqli_real_escape_string($con,$password);
$password = mysqli_real_escape_string($con,$password);
$fieldset = mysqli_real_escape_string($con,$fieldset);
if ($fieldset == "add") {
$sqlcommand="INSERT INTO members (student_id,student_pass) VALUES ('$id','$password')";
} elseif (fieldset == "delete") {
$sqlcommand="DELETE FROM members WHERE student_id LIKE '$id'";
} else {
echo "Your information is incorrect";
}
}
?>
I would guess that the error would be here
$id = mysqli_real_escape_string($con,$password); // <<<<<<
$password = mysqli_real_escape_string($con,$password);
$fieldset = mysqli_real_escape_string($con,$fieldset);
I guess that's supposed to be
$id = mysqli_real_escape_string($con,$id);
And also you're not running any queries, as another person said, you're just setting up SQLs. Basically your script should look like
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user="admin";
$pass="whatever";
$host="localhost";
$db_name="login";
$con=mysqli_connect($host, $user, $pass, $db_name);
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = ($_POST['id']);
$password = md5($_POST['pass']);
$fieldset = ($_POST['fieldset']);
$id = mysqli_real_escape_string($con,$id);
$password = mysqli_real_escape_string($con,$password);
$fieldset = mysqli_real_escape_string($con,$fieldset);
if ($fieldset == "add") {
$sqlcommand="INSERT INTO members (student_id,student_pass) VALUES ('$id','$password')";
} elseif (fieldset == "delete") {
$sqlcommand="DELETE FROM members WHERE student_id LIKE '$id'";
} else {
$sqlcomand='';
echo "Your information is incorrect";
}
mysqli_query($con,$sqlcommand);
}
You're not actually executing the SQL query anywhere. You need to run mysqli_query($con,$sqlcommand); somewhere.
You are not executing the query; use mysql_query($sql);
Hope it will help you :)

Categories