Check if email and username exist in PHP and mysqli - php

I'm trying to check if a handle or email exists for the riegistration on my mock Twitter project I'm doing called bleeter, but I'm getting this error:
Notice: Object of class mysqli_result could not be converted to int in first.php on line 20
This is the line where I check if num_rows_handle == 0. How am I supposed to do this?
$query_check_handle = "SELECT * FROM users WHERE handle = " . $handle;
$num_rows_handle = mysqli_query($dbc, $query_check_handle);
if ($num_rows_handle == 0) { // Line 20
//check email
$query_check_email = "SELECT * FROM users WHERE email = " . $email;
$num_rows_email = mysqli_query($dbc, $query_check_email);
if ($num_rows_email == 0) {
$query_register = "INSERT INTO users (first_name, last_name, handle, password, email, ACL)
VALUES ('$fname', '$lname', '$handle', '$pass', '$email', '$ACL')"
or DIE ("error running the query.");
mysqli_query($dbc, $query_register);
echo "<br>";
echo "You have succesfully registered, please login";
} else {
echo "<br>";
echo "Email already in use. Please try again";
}
} else {
echo "<br>";
echo "Handle already in use. Please try again";
}

When the query is SELECT, mysqli_query returns the object of type mysqli_result, which has property num_rows containing the number of rows. Thus
$result = mysqli_query($dbc, $query_check_email);
$num_rows_email = mysqli_num_rows($result);

Related

Receiving Error Message, despite data being sent

I have recently implemented a number of if statements that check to see if the require data has been entered, if not then I receive the error message something is wrong with.... But after implementing them I now recieve that error message regardless of whether the data is in fact being sent to the database (the data that is being sent is all correct) and I can't for the life of me figure out why.
$query = "insert into $sql_table (Eoi, Job_reference_number, First_Name, Last_Name, Street_Address, Suburb, State, Postcode, Email, Phone_Number, Skills) values ('$eoi','$jobNumber', '$firstName', '$lastName', '$streetAddress', '$suburb', '$state', '$postcode', '$emailAddress', '$phoneNumber', '$skills')";
$result = mysqli_query($conn, $query);
if($jobNumber = ''){
$result = false;
}
if($firstName = ''){
$result = false;
echo "<p> Something is wrong with your First Name </p>";
}
if($lastName = ''){
$result = false;
echo "<p> Something is wrong with your Last Name </p>";
}
if($streetAddress = ''){
$result = false;
echo "<p> Something is wrong with your Street Address </p>";
}
if($suburb = ''){
$result = false;
echo "<p> Something is wrong with your Suburb </p>";
}
if($postcode = ''){
$result = false;
echo "<p> Something is wrong with your Postcode </p>";
}
if($email = ''){
$result = false;
echo "<p> Something is wrong with your Email </p>";
}
if($phoneNumber = ''){
$result = false;
echo "<p> Something is wrong with your Phone Number </p>";
}
if($skills = ''){
$result = false;
echo "<p> Something is wrong with your Skills </p>";
}
if($result != mysqli_query($conn, $query)) {
echo "<p>Something is wrong with ", $query, "</p>";
}else {
echo "<p class=\"ok\">Successfully added a New EOI record</p>";
}
}
}
mysqli_close($conn);
I expect the result to be Successfully added a new EOI record when the user inputs valid data but instead I get the error message.
First you have a syntax error in if statement
if statement should be == not =
if($yourVariable == ''){
echo "<p> Something is wrong with your yourVariable </p>";//no meaning of this line
$result = false;
}
it means if your variable is empty then $result will false and you're can check it in your last if
Second you are checking all variable after DB insertion, you need to do it before insertion in db

PHP and Swift : Fatal error on password_hash()

I have set up my sign up and sign in php files they're on the server and it works with my swift app. I can sign in and sign up easily. But when i added the password_hash() method to had security to the user password it gives an error on Xcode when I try to sign up. Is there any other way to have a store the password securely if this doesn't work anymore. Yes I have php 5.5.34 installed:
error via Xcode:
DATA: <br />
<b>Fatal error</b>: Call to undefined function password_hash() in <b>/*/*/public_html/*/signup.php</b> on line <b>92</b><br />
signup.php
// Hash password and insert new user to table
$hashPassword = password_hash($password, PASSWORD_DEFAULT);
$command = " INSERT INTO USER
(firstname, lastname, username, email, password)
VALUES
('$firstname', '$lastname', '$username', '$email', '$hashPassword')";
if ( mysqli_query($DB, $command) ) {
// Search for newUser
$command = "SELECT * FROM USER WHERE username = '$username'";
$sql = mysqli_query($DB, $command);
if ( mysqli_num_rows($sql) != 0 ) {
$newUser = mysqli_fetch_array($sql);
$returnData["status"] = "200";
$returnData["message"] = "Success!";
$returnData["ID"] = $newUser["ID"];
$returnData["firstname"] = $newUser["firstname"];
$returnData["lastname"] = $newUser["lastname"];
$returnData["username"] = $newUser["username"];
$returnData["email"] = $newUser["email"];
}
echo json_encode($returnData);
return;
} else {
$returnData["status"] = "400";
$returnData["message"] = "Sorry, something must've went wrong. Please try again...";
echo json_encode($returnData);
return;
}
signin.php
// Find user from table and sign in
$command = "SELECT * FROM USER WHERE email = '$email'";
$sql = mysqli_fetch_array( mysqli_query($DB, $command) );
if ( isset($sql) ) {
$hashPassword = $sql["password"];
if ( password_verify($password, $hashPassword) ) {
$returnData["status"] = "200";
$returnData["message"] = "Success!";
$returnData["ID"] = $sql["ID"];
$returnData["username"] = $sql["username"];
}
echo json_encode($returnData);
return;
} else {
$returnData["status"] = "400";
$returnData["message"] = "Sorry, something must've went wrong. Please try again...";
echo json_encode($returnData);
return;
}
You can use this library to get the password_*() functions. Also provides < PHP 5.5 support.

How to see if result of SQL query is empty before performing other queries in PHP

I have the following PHP code which is for a voting system of an app.
Its a Q&A app, and the user can vote for questions and answers that are posted.
In my php code, I first check if the user has voted for a specific question.
This would exist in the QVOTES table, with the email and the id of the question being voted for.
When performing this check, I am not sure of how to see if $result is an empty set, so as to submit the user's vote if they have not voted for the question yet.
How can i get this working? All help is greatly appreciated.
<?php
$con=mysqli_connect("127.2.1.1","S837","887","D887");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$qid = $_POST['qid'];
$email = $_POST['email'];
$result = mysqli_query($con, "SELECT * FROM QVOTES WHERE QID = $qid AND EMAIL = '$email'");
if (!mysqli_num_rows($result) ){
if ($result = mysqli_query($con, "INSERT INTO QVOTES (QID, EMAIL) VALUES ($qid, '$email')")) {
mysqli_query($con, "Update QUESTIONS SET VOTES = VOTES +1 WHERE QID = $qid");
echo "Update successful";
} else{
echo "Update unsuccessful";
}
} else{
echo "null";
}
mysqli_close($con);
Actually you are doing in a wrong way. Please try to do like this:-
<?php
$con=mysqli_connect("127.2.1.1","S837","887","D887");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$qid = $_POST['qid'];
$email = $_POST['email'];
$result = mysqli_query($con, "SELECT * FROM QVOTES WHERE QID = $qid AND EMAIL = $email") or die(mysqli_error($con)); // no need of extra quote
if ($result->num_rows == 0 ){ // means no vote-up done till now
$result = mysqli_query($con, "INSERT INTO QVOTES (QID, EMAIL) VALUES ($qid, $email)")or die(mysqli_error($con)); // insert
if($result){
echo "Vote Added successfully.";
} else{
echo "Error occur while adding vote.Please try again.";
}
} else{
$result = mysqli_query($con, "Update QUESTIONS SET VOTES = VOTES +1 WHERE QID = $qid AND EMAIL = $email")or die(mysqli_error($con)); // upddate
if($result){
echo "Vote updated successfully.";
} else{
echo "Error occur while updating vote.Please try again.";
}
}
mysqli_close($con);
Note:- I change message for better understanding. You can change according to your wish. thanks.
How to see if $result is an empty set?
From the docs:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE (Ref)
Use $result->num_rows if $result is not FALSE;

PHP if statement within if statement

I'm building a php site where i want the user to create his company.
The script is checking if the user has any companies registered already and then it should display if he does or doesn't.
If he doesnt have a registered company, he should see a form where he can register.
If he choose to register a company the script will check for any company with the same name or insert the row.
My only problem is that when there's already a company with that name the echo doesnt display.
I have written inside the code where the problem is.
<?php
$con=mysqli_connect("mysql","USER","PASS","DB");
if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
$result_get_companies = mysqli_query($con,"SELECT * FROM companies WHERE userid='". $login_session ."' ORDER BY companyid ASC") or die(mysqli_error());
if (mysqli_num_rows($result_get_companies) >= 1) {
while($row_companies = mysqli_fetch_array( $result_get_companies )) {
$result_get_company_owner = mysqli_query($con,"SELECT username FROM users WHERE userid='". $login_session ."'") or die(mysqli_error());
$company_owner = mysqli_fetch_assoc($result_get_company_owner);
echo 'THIS WORKS';
}
} else {
if (isset($_POST['create_first_company']) && !empty($_POST['company_name'])) {
$company_name_unsafe = mysqli_real_escape_string($con, $_POST['company_name']);
$company_name = preg_replace("/[^a-zA-Z0-9\s]/","",$company_name_unsafe );
$check_companies = "SELECT companyid FROM companies WHERE company_name='". $company_name ."'";
$what_to_do_companies = mysqli_query($con,$check_companies);
if (mysqli_num_rows($what_to_do_companies) != 0) {
echo 'THIS DOESNT WORK
It does register that is should go here
because it does not insert new row.
and when the value is = 0 it does go
to else ELSE below and insert row.';
} else {
$result_create_company = mysqli_query($con,"INSERT INTO companies (companyname)
VALUES ('". $login_session ."')")
or die(mysqli_error());
echo 'THIS WORKS';
}
} else {
echo 'THIS WORKS!';
}
}
?>

Query Checking for Existence - PHP

I'm trying to to test to see if an email address exists in my database by running a query check.
I can connect to the database fine.
However no matter what, even if the email exists it returns "doesn't exist".
<?php
//----------------------------------------------------------------------------------//
//Setup
require_once('SB_Constants.php');
//----------------------------------------------------------------------------------//
//Connect to the database
//----------------------------------------------------------------------------------//
$connection = mysqli_connect(DATABASE_HOST, SAVE_USERNAME, SAVE_PASSWORD, DATABASE_NAME);
// check the connection was successful
if (mysqli_connect_errno($connection)) {
header('HTTP/1.0 500 Internal Server Error', true, 500);
die(FailedToAccessDatabase . ". Failed to connect to Database");
} else {
echo "Connection Success!";
}
//Query Check
$assessorEmail = mysqli_query($connection, "SELECT email_address FROM assessorID WHERE email_address = 'ryan#ablah.com'");
if (mysqli_num_rows($query_identifier) == 0) {
die(UnregisteredAssessor . ". Doesn't Exist");
} else {
// Exists
echo "Exists getting ace id.";
//Get the assessor ID
$result = mysqli_query($connection, "SELECT ace_id FROM assessorID WHERE email_address = 'ryan#blah.com'");
echo $result;
}
/* close connection */
mysqli_close($connection);
?>
Any ideas of the problem? :)
Various mistakes. Fix:
$assessorEmail = mysqli_query($connection, "SELECT ace_id,email_address FROM assessorID WHERE email_address = 'ryan#ablah.com'");
if (mysqli_num_rows($assessorEmail) == 0) {
die(UnregisteredAssessor . ". Doesn't Exist");
} else {
// Exists
echo "Exists getting ace id.";
//Get the assessor ID
$result = mysqli_fetch_assoc($assessorEmail);
echo $result['ace_id'];
}
Your problem is mysqli_num_rows($query_identifier) is accessing an undefined variable instead of $assessorEmail.
Additionally, you only need one query if you just want the ace_id:
$assessorEmail = mysqli_query($connection, "SELECT ace_id FROM assessorID WHERE email_address = 'ryan#ablah.com'");
If mysqli_num_rows($assessorEmail) returns a row, than the email exists and you already have the ace_id
while(mysqli_fetch_assoc($assessorEmail) = $row) {
echo $result['ace_id'];
}

Categories