Username check comes back as username already exist when it doesnt - php

I have a code that checks if a username exists or not, but when I run the code and enter in a username i inserted into my database using phpmyadmin it says the username dosent exist, am wondering where i went wrong?
here is my php code:
<?php
require_once 'connect.php';
$conn = dbConnect();
if (isset($_POST['username']))
{
$sql = $conn->prepare("SELECT COUNT(id)
FROM users
WHERE username = :username");
$sql->execute(array(":username" => $_POST['username']));
$rows_number = $sql->fetchColumn();
if($rows_number ==0)
{
echo "Username doesn't exist";
exit;
}
else
{
echo "Username already exists";
exit;
}
}
?>
here is my php connect.php:
<?php
function dbConnect(){
$db = null;
$db_host = "localhost";
$db_username ="user";
$db_pass ="pass";
$db_name = "accounts";
try{
$db = new PDO('mysql:host='.$db_host.';dbname'.$db_name,$db_username,$db_pass);
}
catch (PDOException $e) {
echo '<p>Cannot connect to database !!</p>';
exit;
}
return $db;
}
?>

Seeing as I do not have 50+ rep I can't comment but post your connect.php code and exclude the username and password so I can see if its the connect.php that's giving the problem
Edit: your problem lye's here:
';dbname'.$db_name,$db_username,$db_pass);
it should be
';dbname='
and then append on your variable $db_name. Further explanation is the ';dbname is equal to the value you gave your variable.

You may not have initialized the query statement
/* create a prepared statement */
<?php
$stmt = $mysqli->stmt_init();
if ($stmt->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>

Related

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.

PHP bindParam not working - blindValue is not the solution

I can't figure this out. I've googled it and a lot of answers refer to blindValue as the solution but I've also tried that with no luck.
The problem is that the SELECT statement is returning zero records but it should return one record. If I hard code the values into the SQL statement it works but passing them in as parameters isn't. Can some one please help me out with this? Thanks.
<?php
function checklogin($email, $password){
try
{
// Connection
$conn;
include_once('connect.php');
// Build Query
$sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = :email AND Password = :password';
// $sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = "a" AND Password = "a"';
// Prepare the SQL statement.
$stmt = $conn->prepare($sql);
// Add the value to the SQL statement
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
// Execute SQL
$stmt->execute();
// Get the data in the result object
$result = $stmt->fetchAll(); // $result is NULL always...
// echo $stmt->rowCount(); // rowCount is always ZERO....
// Check that we have some data
if ($result != null)
{
// Start session
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Search the results
foreach($result as $row){
// Set global environment variables with the key fields required
$_SESSION['UserID'] = $row['pkUserID'];
$_SESSION['Email'] = $row['Email'];
}
echo 'yippee';
// Return empty string
return '';
}
else {
// Failed login
return 'Login unsuccessful!';
}
$conn = null;
}
catch (PDOexception $e)
{
return 'Login failed: ' . $e->getMessage();
}
}
?>
the connect code is;
<?php
$servername = 'localhost';
$username = 'admin';
$password = 'password';
try {
// Change this line to connect to different database
// Also enable the extension in the php.ini for new database engine.
$conn = new PDO('mysql:host=localhost;dbname=database', $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo 'Connected successfully';
}
catch(PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
I'm connecting to mySQL. Thanks for the help,
Jim
It was a simple but stupid error.
I had a variable called $password also in the connect.php file which was overwriting the $password that I was passing to the checklogin.
Jim

Parsing Json From PHP to Xcode(Swift) with Mysql query

Morning All,
Im after a bit of advice/help with the below issue.
i have tried looking around and google'ing but I still don't understand where I'm going wrong. Please forgive me as I'm a complete noob at this.
some of you may have seem this code before but I'm want to adapt it. Once the user logs in i want to get the user ID from the MySQL Database and send that to swift in the JSON but i can't get it to work, i have tried putting the query in different places with no luck, JSON is completely new to me :(
Ideally > user logs in> swift sends JSON to verify>JSON-PHP verified by MySQL > PHP - JSON reply with success AND user id from the db.
Any Help would be amazing !!
<?php
header('Content-type: application/json');
require("conn.php");
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
$db_name = '***';
$db_user = '***';
$db_password = '***';
$server_url = 'localhost';
$mysqli = new mysqli('localhost', $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 {
if ($stmt = $mysqli->prepare("SELECT username FROM users WHERE username = ? and password = ?")) {
$password = md5($password);
/* bind parameters for markers */
$stmt->bind_param("ss", $username, $password);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($id);
/* fetch value */
$stmt->fetch();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
if ($id) {
error_log("User $username: password match.");
echo '{"success":1, "ID":0}';
} else {
error_log("User $username: password doesn\'t match.");
echo '{"success":0,"error_message":"Invalid Username/Password"}';
}
}
} else {
echo '{"success":0,"error_message":"Invalid Username/Password."}';
}
}else {echo '{"success":0,"error_message":"Invalid Data."}';
}
?>

Cannot update database

<?php
session_start();
if (isset($_POST['userid']) && isset($_POST['password']))
{
// if the user has just tried to log in
$userid = $_POST['userid'];
$password = $_POST['password'];
$db_conn = new mysqli('localhost', 'user', 'passwd', 'dbname');
if (mysqli_connect_errno()) {
echo 'Connection to database failed:'.mysqli_connect_error();
exit();
}
$query = 'select * from users '
."where userid like'$userid' "
." and password like sha1('$password')";
$result = $db_conn->query($query);
if ($result->num_rows >0 )
{
// if they are in the database register the user id
$_SESSION['valid_user'] = $userid;
}
$db_conn->close();
}
?>
<?
$db_conn = new mysqli('localhost', 'user', 'passwd', 'dbname');
if (mysqli_connect_errno()) {
echo 'Connection to database failed:'.mysqli_connect_error();
exit();
}
if (isset($_POST['submit'])) {
if (empty($_POST['name']) || empty ($_POST['dob']) || empty ($_POST['contact'])|| empty ($_POST['address'])|| empty ($_POST['email'])) {
echo "All records to be filled in";
exit;}
}
$name = $_POST['name'];
$dob = $_POST['dob'];
$contact = $_POST['contact'];
$address = $_POST['address'];
$email = $_POST['email'];
$userid = $_SESSION['valid_user'];
$sql = "UPDATE users SET name=$name, dob=$dob, contact=$contact, address=$address, email=$email
WHERE userid ='$userid'";
$result = $db_conn->query($sql);
if (!$result)
echo "Your query failed.";
else
echo "User Information Updated ";
?>
<meta http-equiv="refresh" content="5;URL=members.php" />
I got your query failed when I run it. Anyone have any clue why my database dont get updated?
I'm pretty sure my sql works. Is there any mistake in my coding?
Your query is okay, except that you're not using prepared statements.
The issue lies in your variables. echo them and see what's in them.
Since we don't have access to your database it's hard for us to verify if something else might be wrong with your query. You could for example create an SQL Fiddle.
Something else you should read up on: SQL Injection
Prepared statements look like this:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$city = "Amersfoort";
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Looks like your exist statement is wrong..
if (isset($_POST['submit']))
{
if (empty($_POST['name']) || empty ($_POST['dob']) || empty ($_POST['contact'])|| empty ($_POST['address'])|| empty ($_POST['email']))
{
echo "All records to be filled in";
**exit**;
}
}

PHP login script issues

I have a couple of questions on my login script. It's just directing me to a blank page with no errors.
If I'm using mysqli, do I need to use ? or $username and $password in
my query?
I don't understand anything going on with $stmt -> fetch(); am I using it right?
$result=mysqli_query($stmt); : does this $result variable contain both the username and password?
If that's the case, how does mysqli_num_rows($result) work?
<?php
function clean($str)
{
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$username = clean($_POST['username']);
$password = clean($_POST['password']);
/* Create a new mysqli object with database connection parameters */
$mysqli = mysqli_connect('localhost', 'root', '', 'draftdb');
if(mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
/* Create a prepared statement */
if($stmt = $mysqli -> prepare("SELECT Login_ID, Login_PW,
FROM login
WHERE Login_ID='$username' AND Login_PW ='".md5($_POST['password'])."'"))
{
/* Bind parameters
s - string, b - boolean, i - int, etc */
$stmt -> bind_param("ss", $username, $password);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($username, $password);
/* Fetch the value */
while ($stmt->fetch())
{
$result=mysqli_query($stmt);
//Check whether the query was successful or not
if($result)
{//main if
if(mysqli_num_rows($result) == 1)
{
//Login Successful
session_regenerate_id();
$login = mysqli_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $login['Login_ID'];
//$_SESSION['SESS_FIRST_NAME'] = $login['firstname'];
//$_SESSION['SESS_LAST_NAME'] = $login['lastname'];
session_write_close();
header("location: member-index.php");
exit();
}
else {
//Login failed
header("location: login-failed.php");
exit();
}
}
else
{
die("Query failed");
}
}//main if close
/* Close statement */
$stmt -> close();
}
/* Close connection */
$mysqli -> close();
?>
I was attempting to address each of your questions but, they got so mixed that I couldn't just give you an answer for each. So i took the liberty of modifying your posted script with what i believe will make it work. Perhaps some extra tweaking is still necessary. Please review comments I added inline. Also, review the following php documentation pages for more information on using mysqli functions in its object oriented form:
http://www.php.net/manual/en/mysqli-stmt.num-rows.php
http://www.php.net/manual/en/mysqli-stmt.execute.php
http://www.php.net/manual/en/mysqli-stmt.bind-result.php
http://www.php.net/manual/en/mysqli-stmt.bind-param.php
I haven't tested it and i might have a typo or two, but here is my attempt at improving your script. Let me know what you think:
<?php
function clean($str)
{
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$username = clean($_POST['username']);
$password = clean($_POST['password']);
/* Create a new mysqli object with database connection parameters */
$mysqli = mysqli_connect('localhost', 'root', '', 'draftdb');
if(mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
/* Is your username the same as the login_id? If not you need to change this query's where to use the username column not the login_id. */
/* Create a prepared statement */
if($stmt = $mysqli -> prepare("
SELECT Login_ID, firstname, lastname
FROM login
WHERE Login_ID=? AND Login_PW=?
"))
{
/* Bind parameters
s - string, b - boolean, i - int, etc */
$stmt -> bind_param("ss", $username, md5($password));
/* Execute it */
$result = $stmt -> execute();
//Check whether the query was successful or not
if ($result === false) {
die("Query failed");
}
/* Bind results to variables that will be used within the fetch() loop. */
$stmt -> bind_result($login_id, $firstname, $lastname);
/* Check the number of rows returned. */
if ($stmt->num_rows !== 1) {
//Login failed
header("location: login-failed.php");
exit();
}
/* Iterate over the results of the query. */
while ($stmt->fetch())
{
//Login Successful
session_regenerate_id();
/* We can use $login_id, $firstname and $lastname cause we binded the result to those variables above. */
$_SESSION['SESS_MEMBER_ID'] = $login_id;
//$_SESSION['SESS_FIRST_NAME'] = $firstname;
//$_SESSION['SESS_LAST_NAME'] = $lastname;
session_write_close();
header("location: member-index.php");
exit();
}//main if close
/* Close statement */
$stmt -> close();
}
/* Close connection */
$mysqli -> close();
?>
When you're using a prepared statement, you normally shouldn't substitute variables into the statement. You put ? placeholders there, and then use $stmt->bind_param() to associate these placeholders with variables.
After using $stmt->fetch(), you can reference the variables that you bound with $stmt->bind_result to access the results of the SELECT.
You shouldn't be using mysqli_query at all if you're using a prepared statement. To answer your question about how it works, $result doesn't contain the actual data. You call something like $row = mysqli_fetch_assoc($result) to get the username and password into $row.
You should use $stmt->num_rows()
I am sorry friend i don't know much about mysqli.
But this can be easily done with mysql if you want.
By the way, for your 3rd question,
$result=mysqli_query($stmt); returns only the resource id's if there is any matching records for your search criteria. and mysqli_num_rows($result); will return how many resource id's are available for that criteria.username and password will only returned after mysqli_fetch_array($result); that will make the database to fetch the record as an array for those resource id's.
hope you understand...:))
I think, the problem is with this part of your code
while ($stmt->fetch())
{
$result=mysqli_query($stmt);
You have executed the statement, and fetched it; there is no need for you to query it again . . . . I'm not familiar with mysqli as I use PDO, but I think since you binded the result to $username, $password you can access the returned values with these binded variables.
while ($result = $stmt->fetch())
{
if($result->num_rows == 1)
{
$_SESSION['SESS_MEMBER_ID'] = $result['LOGIN_ID']
//////or $_SESSION['SESS_MEMBER_ID'] = $username
You can proceed like this, I think . . .

Categories