How to check if email exists with MYSQLi - mysqli

I'm 11 and I'm making a chat site for me and my friends. I'm using MYSQLi to handle the database things, and I'm kinda new to it. I always used normal mysql.
Oh! And if you can share a link to a mysqli tutorial, it would be great :)
Well here's my config file
<?PHP
define("HOST", "localhost"); define("USER", "root"); define("PASSWORD", "****"); define("DATABASE", "secure_login");
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
?>
The database is secure_login, then I have a table called members, and then a column named email in that table.
I included this to a file (register.php) where I have to check if the email exists or not. And if it exists, redirect to home.
If you guys can help me it would be cool!!! I hope to finish this soon :)

I'd start with reading the MySQLi documentation at http://php.net/manual/en/book.mysqli.php, in specific the methods related to the class. If you are in need of a tutorial I would suggest to search on Google, there are loads of tutorials on the web.
As for your question, something like this should work:
$query = "SELECT email FROM members WHERE USER = ? AND PASS = ?";
if ($stmt = $mysqli->prepare($query)){
// Bind the parameters, these are the ?'s in the query.
$stmt->bind_param("ss", $username, sha1($password));
// Execute the statement
if($stmt->execute()){
// get the results from the executed query
$stmt->store_result();
$email_res= "";
// This stores the value of the emailaddres inside $email_res
$stmt->bind_result($email_res);
$stmt->fetch();
// There is a result
if ($stmt->num_rows == 1){
// Validate the emailadres here, check the PHP function filter_var()
}
else {
// Not a valid email
}
}
else {
printf("Execute error: %s", $stmt->error);
}
}
else {
printf("Prepared Statement Error: %s\n", $mysqli->error);
}
}
I hope this helps

Related

How to check if email exist in data base yii2 basic

How I can check if an email exist in the data base in yii2 basic , I connect the database with the framework,but need help ,how to check this (its needed for the forgot password (form) )
assuming the the email you are looking for is in $email_to_check and the ActiveRecord is YourClass should be somethings like this
$model = YourClass::find()->where(['email'=> $email_to_check]);
If (isset($model)) {
// then your email exists
}
could be
$modelUser = User::find()->where(['email'=> $email_to_check]);
If (isset($modelUser)) {
// then the User with your email exists
}

how to auto login after submitting sign up form in php?

i am using php mysqli coding,i create sign up form and login form both are working separately but now i want to provide login after sign up successfully.
this is my sign up code:
{
# insert data into mysql database
$sql = "INSERT INTO `users` (`id`, `username`, `password`, `phone`, `email`)
VALUES (NULL, '{$name}', '{$password}', '{$phone}', '{$email}')";
$query="SELECT * FROM users WHERE email= '$email'";
if ($mysqli->query($sql)) {
$reslt=$mysqli->query($query);
$usr=$reslt->fetch_array();
$_SESSION[user_email]=$usr['email'];
redirect_to("profile.php?email={$_SESSION['user_email']}");
} else {
echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>";
exit();
}
}
I tried this way but insertion operation is doing properly but page is refreshing and not redirecting to "profile.php" which is i mentioned in code
first of all, I would suggest that for for a login you check both email and password. Your query should look like:
$query="SELECT * FROM users WHERE email= '$email' and password = '$password'";
Next, if ($mysqli->query($sql)) { just verifies if the sql operation has succeeded. If the user and password are wrong, the sql will succeed but you will have no rows returned.
What you have to do is to verify that you have only 1 row returned by the query. In fact your code should more look like:
...
// check how many users correspond to the query
// ! the result will be an arry
$users = $reslt->fetch_array();
// if I have only one user, login is successfull
if(count($users) === 1) {
$_SESSION['user_email'] = $users[0]['email'];
} else {
// login failed
}
...

silverstripe external authentification

there is a custom login form that should give users access to certain contents on the same page. That works so far with Users stored as Members in the SS database and I was checking after Login if the user has permissions like this in the Page Class:
function isAllowed() {
if (Member::currentUser()) {
$PresseGroup = DataObject::get_one('Group', "Code = 'presse'");
$AdminGroup = DataObject::get_one('Group', "Code = 'administrators'");
if (Member::currentUser()->inGroup($PresseGroup->ID) || Member::currentUser()->inGroup($AdminGroup->ID)) {
return true;
}
}
}
in the Template I just did this:
<% if isAllowed %>
SecretContent
<% end_if %>
OK so far, but now the users will not be stored in the silverstripe database - they are stored on a another server.
On that external server is running a little php script accepting the username and password. The script just returns user has permission: true or false.
I´m calling that script via cURL.
I planned to overwrite the dologin Function of MemberLoginForm. Now I just wonder how to check after Login that the User got the permission and display the contents... I tried to set a variable in the controller of the Page or should I set a session Variable? Thats my attempt (CustomLoginForm extends MemberLoginForm):
public function dologin($data) {
if(userHasPermission("user1", "pw")==true){
$this->controller->Test("test");
}
$link = $this->controller->Link();
$this->performLogin($data);
$this->controller->redirect($link);
}
I hope someone can help me with that - I know very specific - problem.
Many thanx,
Florian
In SilverStripe you can create a custom authenticator, which means users can log in on your website with accounts that are stored somewhere else, or even just a hard coded user and password.
You can check out the OpenID Authentication Module for example code on how to do it
But for your task this might even be to complex of a solution, how about after login just do something like Session::set('isAllowed', true); and to check if the user is allowed to view:
function isAllowed() {
if (Member::currentUser()) {
$PresseGroup = DataObject::get_one('Group', "Code = 'presse'");
$AdminGroup = DataObject::get_one('Group', "Code = 'administrators'");
if (Member::currentUser()->inGroup($PresseGroup->ID) || Member::currentUser()->inGroup($AdminGroup->ID)) {
return true;
}
}
// if Member::currentUser() is not allowed to view,
// return the session, which is either set to true or it returns null if not set
return Session::get('isAllowed');
}

Zend_Auth not working

In my model, "Users", I have the following authorization after validating the username/password
$db = Zend_Db_Table::getDefaultAdapter();
$authAdapter = new Zend_Auth_Adapter_DbTable($db,'users','username','password');
$authAdapter->setIdentity($username);
$authAdapter->setCredential(md5($password));
$auth_result = $authAdapter->authenticate();
if( $auth_result->isValid() )
{
$auth = Zend_Auth::getInstance();
$storage = $auth->getStorage();
$storage->write($authAdapter->getResultRowObject(array('id','username')));
return 'logged_in';
}
return 'auth_failed';
it keeps returning 'auth_failed'. I had the code running on a localhost, and everything works fine, but when I upload it online, it fails to authorize the user. What is going on?
Thanks
I can't tell what's wrong without checkin the logs, so perhaps you might want to use the method I use for storing auth data. Basically you validate manually and set the storageThis doesn't solve the problem, but its impossible to do so without accessing your code.
function login($userNameSupplied,$passwordSupplied){
$table= new Application_Model_Dbtable_Users();//Or Whatever Table you're using
$row=$table->fetchRow($table->select()->where('username=?',$userNameSupplied)->where('password=?',md5($passwordSupplied));
if($row){
Zend_Auth::getInstance()->getStorage()->write($row->toArray());
return 'logged_in';
}
else{return 'failed';}
}
//To check if the user is logged in, use
$userInfo=Zend_Auth::getInstance()->getStorage()->read();
if($userInfo)//user is logged in

Joomla JUser getinstance Questions

I am attempting to make an authentication plugin. JUser::getInstance() takes one input, and it is supposed to be the id. Is there any way to get an instance of a User using some other indentifier? such as username, email etc.
Probably there isnt any such method. But yes if you are sure that username or email are unique then you can modify your file user.php in libraries/joomla/user/ and add a method there.
getInstanceByEmail($email)
{
$query = "select id from jos_users where email=".email;
// use the code to get the id;
return getInstance($id);
} // this is just a sample code of how it can be achieved
Since Joomla's own authentication is done by checking the user's username (and password of course), it has to be unique. And yes you can do something like what #Rixius suggested.
Here's my version:
// Get a database object
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('id, password');
$query->from('#__users');
$query->where('username=' . $db->Quote($credentials['username']));
$db->setQuery($query);
$result = $db->loadObject();
$user = JFactory::getUser();
if ($result)
{
$user = JUser::getInstance($result->id);
}