I am learning PHP and able to create a Registration form. But the code doesn't working properly. It always goes to else statement of Username exists Try Again. Any help appreciated and any explanation greatly welcomed :)
function session() {
$usn = $_POST['username'];
$pwd = $_POST['password'];
$email = $_POST['Email'];
$con=mysqli_connect("********","***********","**********","*********");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Accounts
WHERE username = '$usn'");
If($result == Null) {
mysqli_query($con,"INSERT INTO Accounts (username, password, Email)
VALUES ('$usn', '$pwd','$email')");
$result = mysqli_query($con,"SELECT * FROM Accounts WHERE username = '$usn'");
while($row = mysqli_fetch_array($result)) {
if (($row['password']==$pwd) and ($row['Email']==$email)) {
echo "Registration Success";
}
else {
echo "Registration Failed";
}
}
}
else {
echo "Username Exists Try Again";
}
mysqli_close($con);
}
$result will never be null. You need to check for something like number of rows -
$row_cnt = mysqli_num_rows($result);
If that is greater than 0, then go to your else.
Related
I am trying to register a user by checking if the variable in the dynamic link I sent them by email matches the hash value that is stored in mysql.
I tried debugging this. I found that $verify and $hash are indeed equal when echoed out into the browser just before my if statement.
One hash value comes from mysqli select query whereas the other comes from a $_GET[''] post.
My hash contains (=,$+) symbols. Could that be preventing it from evaluating correctly? When my code is displayed in the browser it doesn't do anything with the if statement.(I don't receive a echo of "it works" nor an echo of "it doesn't work")
If you know what this problem might be or have advise on trouble shooting it would be much appreciated. Thanks for all your help in advance.
Part of the code I seem to be having trouble with:
if ($verify === $hash ){
echo "It works!";}
else{ echo "It doesn't work!";}
I also tried evaluating it with the 2 following alternatives and they didn't work:
$values = array($verify, $hash);
if(count(array_unique($values)) === 1) {
echo "It works!";}
if (strcmp("$verify","$hash")===0){
echo "It works!";
Here is my complete code:
$servername = "localhost";
$un = "root";
$password = "";
$dbname = "secure_login";
$conn = new mysqli($servername, $un, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$username = mysqli_real_escape_string($conn,$_GET['username']);
$hash = mysqli_real_escape_string($conn,$_GET['hash']);
$sql = "SELECT hash FROM login WHERE username = '$username'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$verify = $row["hash"];
}
} else {
echo "0 results";
echo "Error Selecting record: " . $conn->error;
}
echo $username;
echo $hash;
if ($verify == $hash ){
echo "It works!";
$sql = "UPDATE login SET active = 1 WHERE username = '$username'";
}
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo $conn->error;
}
$conn->close();
}
<?php
$server_host = "host";
$server_username = "username";
$server_password = "password";
$server_dbName = "data base name";
$player_username = $_POST ["usernamePost"];
$player_password = $_POST ["passwordPost"];
$player_displayName = $_POST ["displayNamePost"];
$conn = new mysqli ($server_host, $server_username, $server_password, $server_dbName);
if (!$conn) {
echo "Error connecting to the server.";
}
$query_code = "SELECT Username FROM users WHERE Username = '{$_POST[usernamePost]}'";
$result_login = mysqli_query ($conn,$query_code);
$anything_found = mysqli_num_rows ($result_login);
if ($anything_found > 0) {
echo "An account with this username or display name already exsists, please choose another.";
}
if ($anything_found <= 0) {
$sql = "INSERT INTO users (Username, Password, Display_Name)
VALUES ('".$player_username."','".$player_password."','".$player_displayName."')";
$result = mysqli_query ($conn,$sql);
if ($result) {
echo "You may now login.";
}
if (!$result) {
echo "Error.";
}
}
?>
I'm using the Unity Engine to display the echoed result, does this script seem that it will echo "An account with this username or display name already exsists, please choose another." if there is already a username with the username entered? Also, would it echo "You may now login." if the account was created?
I made this script myself, I'm new to this PHP stuff. I'd appreciate it if someone looked this code over and explained to me why this isn't working.
The logic is wrong. Conditional statements are hanging dangerously :-)
Use this
<?php
$server_host = "host";
$server_username = "username";
$server_password = "password";
$server_dbName = "data base name";
$player_username = $_POST ["usernamePost"];
$player_password = $_POST ["passwordPost"];
$player_displayName = $_POST ["displayNamePost"];
$conn = new mysqli ($server_host, $server_username, $server_password, $server_dbName);
if (!$conn) {
echo "Error connecting to the server.";
}
else{
$query_code = "SELECT Username FROM users WHERE Username = '{$_POST[usernamePost]}'";
$result_login = mysqli_query ($conn,$query_code);
$anything_found = mysqli_num_rows ($result_login);
if ($anything_found > 0) {
echo "An account with this username or display name already exsists, please choose another.";
}
elseif ($anything_found <= 0) {
$sql = "INSERT INTO users (Username, Password, Display_Name)
VALUES ('".$player_username."','".$player_password."','".$player_displayName."')";
$result = mysqli_query ($conn,$sql);
if ($result) {
echo "You may now login.";
}
else{
echo "Error.";
}
}
}
?>
I am trying to build a register page using PHP and MySQLi. However, it doesn't work, and I cannot understand the issue. It was previously with no MySQL improved syntax. There is just an empty page in browser.
<?php
include ("bd.php");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['login']))
{
$login = $_POST['login'];
if ($login == '')
{
unset($login);
}
}
if (isset($_POST['password']))
{
$password=$_POST['password'];
if ($password =='')
{
unset($password);
}
}
if (empty($login) or empty($password))
{
exit ("You have entered not all of the information, go back and fill in all the fields!");
}
$login = stripslashes($login);
$login = htmlspecialchars($login);
$password = stripslashes($password);
$password = htmlspecialchars($password);
$login = trim($login);
$password = trim($password);
$myrow = mysqli_query($db,"SELECT id FROM users WHERE login='$login'");
if (!empty($myrow['id']))
{
exit ("Sorry, you entered login which is already registered . Please enter a different username.");
}
$result2=mysqli_query($db,"INSERT INTO users (login,password) VALUES('$login','$password')");
if ($result2=='TRUE')
{
echo "You have successfully signed up!";
}
else
{
echo "Failed to sign up";
}
?>
bd.php:
<?php
$db = new mysqli ("localhost","root","root","kotik");
?>
<?php
include ("bd.php");
if (mysqli_connect_errno()){echo "Failed to connect to MySQL: " . mysqli_connect_error();}
$login = isset($_POST['login'] && !empty($_POST['login'])) ? stripslashes(trim($_POST['login'])) : null;
$password = isset($_POST['login'] && !empty($_POST['login'])) ? stripslashes(trim($_POST['login'])) : null;
$password = htmlspecialchars($password);
if (empty($login) || empty($password)){exit ("You have entered not all of the information, go back and fill in all the fields!");}
$res = mysqli_query($db,"SELECT id FROM users WHERE login='$login'");
$myrow = mysqli_fetch_assoc($res);
if (!empty($myrow['id'])) {
exit ("Sorry, you entered login which is already registered . Please enter a different username.");
}
$result2 =mysqli_query($db,"INSERT INTO users (login,password) VALUES('$login','$password')");
if ($result2 == true)//use true not 'True' because 'True' is a string
{
echo "You have successfully signed up!";
}
else {
echo "Failed to sign up";
}
?>
EDIT: You should use mysqli_fetch_assoc to get an associative array which corresponds to the fetched row or NULL if there are no more rows.
You cannot use the variable $myrow like this:
$myrow['id']
You need to get the row then you can treat it like an array. It would look something like this:
$row = $myrow->fetch_row()
$row['id']
this gets the first row of the results of the query. If the query returns multiple results you can use something like this:
while($row = $myrow->fetch_row()) {
$rows[]=$row;
}
Then you use $rows as a normal array and get the individual rows 1 by 1 in a for loop, then you can use the same format:
$temp = $rows[0];
$temp['id']
No results when trying to insert new register by checking if username is not exist already.
I've tried to insert the query also with msql and not msqli - didn't work also.
can anyone describe what i have done wrong ?
this is my code:
<?php
if (isset($_POST["submit"])) {
if (!empty($_POST['user']) && !empty($_POST['pass'])) {
$user = $_POST['user'];
$pass = $_POST['pass'];
$con = mysqli_connect("xxxxxxx", "xxxx", "xxxx", "xxxxx") or die(mysqli_error());
mysqli_select_db($con, 'xxxxxx') or die("cannot select DB");
mysqli_set_charset($con, 'utf8');
if ($result = mysqli_query($con, "SELECT * FROM login WHERE username='" . $user . "'")) {
$row_cnt = mysqli_num_rows($result);
if ($row_cnt == 0) {
$sql = "INSERT INTO login(username,password)VALUES('$user','$pass')";
$query = mysqli_query($con, $sql);
if ($query) {
echo "Account Successfully Created";
} else {
echo "Failure!";
}
} else {
echo "That username already exists! Please try again with another.";
}
/* close result set */
//mysqli_free_result($result);
}
} else {
echo "All fields are required!";
}
}
?>
I'm very new to using MySql and am having trouble retrieving values from my database. I was under the impression that i was going about it the correct way but my echo statements don't print anything.
I'd appreciate some help. My code is below. I know i'll have to add security later on like sanitizing user input.
<?php
$email = $_POST['email'];
$password = $_POST['password'];
$hashedPass = sha1($password);
if ((!isset($email)) || (!isset($password))) {
//Visitor needs to enter a name and password
echo "Data not provided";
} else {
echo "Received details $email and $password <br/>";
// connect to mysql
$mysql = mysqli_connect("localhost", "root", "root");
if(!$mysql) {
echo "Cannot connect to PHPMyAdmin.";
exit;
} else {
echo "Connected to phpmyadmin <br/>";
}
}
// select the appropriate database
$selected = mysqli_select_db($mysql, "languageapp");
if(!$selected) {
echo "Cannot select database.";
exit;
} else {
echo "DB Selected";
}
// query the database to see if there is a record which matches
$query = "select count(*) from user where email = '".$email."' and password = '".$hashedPass."'";
$result = mysqli_query($mysql, $query);
if(!$result) {
echo "Cannot run query.";
exit;
}
$row = mysqli_fetch_row($result);
$count = $row[0];
$userdata = mysqli_fetch_array($result, MYSQLI_BOTH);
echo $userdata[3];
echo $userdata['firstName'];
if ($count > 0) {
echo "<h1>Login successful!</h1>";
echo "<p>Welcome.</p>";
echo "<p>This page is only visible when the correct details are provided.</p>";
} else {
// visitor's name and password combination are not correct
echo "<h1>Login unsuccessful!</h1>";
echo "<p>You are not authorized to access this system.</p>";
}
?>
I believe the problem is that you call twice the *fetch* family function which will cause the $userdata to be empty.
From the documentation mysql_fetch_row will fetch the next row and move the internal data pointer ahead. So when you call mysqli_fetch_array($result, MYSQLI_BOTH) and I suppose the user/password is unique there is nothing to retrieve. Also another mistake you did is that your SELECT doesn't retrieve the actual user data, but just the count number for the user/password combination. So your userdata will be always incorrect, even if you fetch the data right.
So change your query to something like that:
$query = "select * from user where email = '".$email."' and password = '".$hashedPass."' LIMIT 1";
Then use mysql_fetch_array to check if the entry exist and then retrieve the user data.