How to starts adding data to MySQL table with id of !=0 - php

I have a page to add new users to the MySQL with PHP. And the problem with this is, that it sets id of a new user to 0 whenever it runs. So I don't want that.. I want it to start from id of 1 and if it exists in table, try more than that like 2 for example.
I don't think for this example, you won't need to look at my php files but if you do, here you can see the admin_new.php:
<?php
$notice = array();
if (isset($_POST['submit'])){
$username = $_POST['uname'];
$email = $_POST['email'];
$password = $_POST['pass'];
$groups = $_POST['groups'];
if($groups == "Main Admin"){
$level = 1;
}else if($groups == "Administrator"){
$level = 2;
}else if($groups == "Content Creator"){
$level = 3;
}else if($groups == "Social Media Manager"){
$level = 4;
}else{
$level = 5;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$notice['email'] = "The email that you have entered is not a valid one";
}else{
$registration = new Register();
$registration->CheckUname($username,$email,$password,$groups,$level);
}
}
?>
<div class="content-wrapper">
<section class="content-header">
<h1>
Add New Admin
<small>You can add new admin here</small>
</h1>
<ol class="breadcrumb">
<li class="active">addnewadmin.php</li>
</ol>
</section>
<?php
if(isset($notice['validation_email'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['validation_email'].".
</div>
";
}
if(isset($notice['username_exists'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['username_exists'].".
</div>
";
}
if(isset($notice['email_exists'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['email_exists'].".
</div>
";
}
if(isset($notice['success_message'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['success_message'].".
</div>
";
}
?>
<section class="content">
<div class="row">
<div class="col-md-6">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Required Information</h3>
</div>
<form role="form" method="POST" action="">
<div class="box-body">
<div class="form-group">
<label>User name</label>
<input type="text" class="form-control" placeholder="Enter username" name="uname" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email" name="email" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Temporary password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Enter password" name="pass" required>
</div>
<div class="form-group">
<label>Group admin</label>
<select class="form-control" name="groups">
<option value="Main Admin">Main Admin</option>
<option value="Administrator">Administrator</option>
<option value="Content Creator">Content Creator</option>
<option value="Social Media Manager">Social Media Manager</option>
<option value="Analyst">Analyst</option>
</select>
</div>
</div>
<div class="box-footer">
Visit admin types documentation to know the differences between each admin.
</div>
<div class="box-footer">
<button name="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
</section>
</div>
And here is the class that I have used which is called Register.class.php:
<?php
class Register
{
private $db;
public function __construct()
{
$this->db = new Connection();
$this->db = $this->db->dbConnect();
}
public function CheckUname($username,$email,$password,$groups,$level)
{
if(!empty($username)&&($email))
{
$chk1 = $this->db->prepare("SELECT username FROM admins WHERE user_name= ?");
$chk1->bindParam(1,$username);
$chk1->execute();
if($chk1->rowCount() == 1)
{
$notice['username_exists'] = "Try different username";
return $notice;
}else{
$chk2 = $this->db->prepare("SELECT email FROM admins WHERE email_address= ?");
$chk2->bindParam(1,$email);
$chk2->execute();
if($chk2->rowCount() == 1)
{
$notice['email_exists'] = "The email address that you have entered is already exists in database";
return $notice;
}else{
$this->NewAdmin($username,$email,$password,$groups,$level);
$notice['success_message'] = "New admin was successfully added";
return $notice;
}
}
}
}
public function NewAdmin($username,$email,$password,$groups,$level)
{
if(!empty($username)&&!empty($email)&&!empty($password)&&!empty($groups)&&!empty($level))
{
$reg = $this->db->prepare("INSERT INTO admins (user_name, email_address, password_hash, group_admin, date_joined, admin_level) VALUES ( ?, ?, ?, ?, NOW(), ?)");
$reg->bindParam(1,$username);
$reg->bindParam(2,$email);
$reg->bindParam(3,$password);
$reg->bindParam(4,$groups);
$reg->bindParam(5,$level);
$reg->execute();
}
}
}
?>

Run this commend on mysql terminal:
ALTER TABLE tablename MODIFY COLUMN id INT auto_increment PRIMARY KEY
the above command will make the id an auto_increment as well as primary key. So for every value you insert, auto_increment will generate a new value for column id, you don't have to assign some value in it.

Related

How to make PHP register errors go underneath their dedicated input boxes

I'm just wondering if anyone knows how to make the errors shown on this screenshot: https://imgur.com/a/eaTVR9g go underneath their dedicated input boxes like shown on this image: https://imgur.com/a/Sb1AfUj If anyone is kind enough to do it for me I would greatly appreciate it. Thank you!
Here is my code:
<?php
$title = "Register";
include ($_SERVER['DOCUMENT_ROOT'] . '/private/header.php');
if ($AUTH) {
header ('Location: /');
die();
}
if (isset($_POST['go'])) {
$username = $_POST['username'];
$email = strtolower($_POST['email']);
$password = $_POST['password'];
$passwordConfirm = $_POST['confirmPassword'];
$protectedPassword = password_hash($password, PASSWORD_ARGON2I);
// Validation Checks
$errors = array();
$Emailstmt = $db->prepare("SELECT * FROM `Users` WHERE `Email` = :email;");
$Emailstmt->bindParam(':email', $email, PDO::PARAM_STR);
$Emailstmt->execute();
if ($Emailstmt->rowCount() > 0) {
$error[] = 'The email you tried to use is already being used on an different account, please use another one.';
}
$Userstmt = $db->prepare("SELECT * FROM `Users` WHERE `Username` = :username;");
$Userstmt->bindParam(':username', $username, PDO::PARAM_STR);
$Userstmt->execute();
$checkIP = $db->prepare("SELECT count(*) FROM `Users` WHERE `LastIP` = :regIP");
$checkIP->bindParam(":regIP", $UserIP, PDO::PARAM_STR);
$checkIP->execute();
$checkIpAdress = $checkIP->fetchColumn();
if (empty($checkIpAdress)) {
$checkIpAdress = 0;
}
if ($checkIpAdress) {
if ($checkIpAdress > 3) {
array_push($errors, 'It looks like you have registered too many accounts under this IP address.');
}
}
if (strlen($username) < 3) {
array_push($errors, 'Your username must be at least 3 characters in total.');
}
if (strlen($password) < 5) {
array_push($errors, 'Your password must be at least 5 characters in total.');
}
if ($Userstmt->rowCount() > 0) {
array_push($errors, 'The username you tried to use is already being used, Maybe try to pick another one.');
}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
//echo("$email is a valid email address");
} else {
array_push($errors, 'The email you specified(' . htmlspecialchars($email, ENT_QUOTES, "UTF-8") . ') is invaild.');
}
if (!preg_match("/^[a-zA-Z0-9][\w\.]+[a-zA-Z0-9]$/", $username)) {
array_push($errors, 'The username you specified(' . htmlspecialchars($username, ENT_QUOTES, "UTF-8") . ') contains special symbols or is invaild.');
}
if (strtolower($username) == strtolower($password)) {
array_push($errors, 'Your password can not be the same as your username.');
}
if ($password !== $passwordConfirm) {
array_push($errors, 'It looks like your passwords do not match.');
}
// Begin form submission
if (empty($errors)) {
$insert = $db->prepare("INSERT INTO `Users` (`Username`,`Email`,`Password`,`LastIP`,`TimeRegister`,`AvatarURL`) VALUES (:Username,:Email,:Password,:LastIP,:TimeRegister,:AvatarURL)");
$insert->bindParam(":Username", $username, PDO::PARAM_STR);
$insert->bindParam(":Email", $email, PDO::PARAM_STR);
$insert->bindParam(":Password", $protectedPassword, PDO::PARAM_STR);
$insert->bindParam(":LastIP", $UserIP, PDO::PARAM_STR);
$insert->bindParam(":TimeRegister", $now, PDO::PARAM_INT);
$insert->bindValue(":AvatarURL", '8ca17bec-0320-4293-90e5-dfc5b8690156', PDO::PARAM_STR);
$insert->execute();
?>
<div class="space">
<section class="hero is-success">
<div class="hero-body modal-button" data-target="modal" aria-haspopup="true"
style="padding: 1rem 1rem !important;">
<center>You have successfully registered! Please wait while we redirect you.</center>
</div>
</section><br>
</div>
<meta http-equiv='refresh' content='5;url=/auth/login' />
<?php
} else {
}
}
if ($SiteSettings->Registration == 0) {
echo '<section class="section">
<div class="container">
<div class="columns is-centered">
<div class="column is-7">
<div class="box">
<p>We\'re sorry, but account creation is currently disabled right now. Please try again later.</p>
</div>
</div>
</div>
</section>
';
include($_SERVER['DOCUMENT_ROOT'] . "/private/footer.php");
die;
}
?>
<section class="section">
<div class="container">
<div class="columns is-centered">
<div class="column is-7">
<div class="box">
<div class="title is-size-4">Register</div>
<form action="#" method="POST">
<input type="hidden" name="token" value="<?php echo $_SESSION["csrf_token"]; ?>" />
<div class="field">
<label class="label">Username</label>
<div class="control has-icons-left">
<input class="input" name="username" type="text" id="username" maxlength="15"
autocomplete="off" placeholder="Enter a username">
<span class="icon is-small is-left"><i class="fas fa-user"></i></span>
<p id="username_message"></p>
</div>
</div>
<div class="field">
<label class="label">E-Mail address</label>
<div class="control has-icons-left">
<input class="input" name="email" type="email" id="email" maxlength="128"
autocomplete="off" placeholder="Enter your e-mail address.">
<span class="icon is-small is-left"><i class="fas fa-envelope"></i></span>
<p id="email_message"></p>
</div>
</div>
<div class="field">
<label class="label">Password</label>
<div class="control has-icons-left">
<input class="input" name="password" type="password" id="password" maxlength="45"
autocomplete="off" placeholder="Enter your password.">
<span class="icon is-small is-left"><i class="fas fa-lock"></i></span>
<p id="password_message"></p>
</div>
</div>
<div class="field">
<label class="label">Confirm Password</label>
<div class="control has-icons-left">
<input class="input" name="confirmPassword" type="password" id="confirmPassword"
maxlength="45" autocomplete="off" placeholder="Confirm your password">
<span class="icon is-small is-left"><i class="fas fa-lock"></i></span>
<p id="confirmPassword_message"></p>
</div>
</div>
<div class="push-5"></div>
<button class="button is-success is-fullwidth" type="submit" name="go"><b>Register</b></button>
</form>
<?php
if (!empty($errors)) {
?>
<?php
foreach ($errors as $error) {
echo '<p class="help has-text-danger">' . $error . '</p>';
}
} ?>
</div>
<p class="has-text-centered">Already a member? Login</p>
</div>
</div>
</div>
</section>
<?php include ($_SERVER['DOCUMENT_ROOT'] . '/private/footer.php'); ?>
You can organize the array keys to reflect the fields they relate to, IE:
if (strlen($username) < 3) {
$errors['username'][] = 'Your username must be at least 3 characters in total.';
}
and then on the display side you can use said keys to identify what errors belong to what field, IE:
<div class="field">
<label class="label">Username</label>
<div class="control has-icons-left">
<input class="input" name="username" type="text" id="username" maxlength="15" autocomplete="off" placeholder="Enter a username">
<span class="icon is-small is-left"><i class="fas fa-user"></i></span>
<p id="username_message">
<?php if (isset($errors['username'])): ?>
<?php foreach($errors['username'] as $error): ?>
<?= $error ?> <br/>
<?php endforeach; ?>
<?php endif; ?>
</p>
</div>

How to overcome can not change the admin name data and change the password?

how to overcome the failure to change the username and password for the admin, this code succeeded in the profile of the user page, but it was not successfully used in the admin profile. Does anyone know where my code error is?
<?php
include('header.php');
$admin_user_name = '';
$admin_password = '';
$error_admin_user_name = '';
$error_admin_password = '';
$error = 0;
$success = '';
if (isset($_POST["button_action"])) {
if (empty($_POST["admin_user_name"])) {
$error_admin_user_name = 'Nama Admin harus di isi';
$error++;
} else {
$admin_user_name = $_POST["admin_user_name"];
}
if (!empty($_POST["admin_password"])) {
$admin_password = $_POST["admin_password"];
}
if ($error == 0) {
if ($admin_password != "") {
$data = array(
':admin_user_name' => $admin_user_name,
':admin_password' => password_hash($admin_password, PASSWORD_DEFAULT),
':admin_id' => $_POST["admin_id"]
);
$query = "
UPDATE tbl_admin
SET admin_user_name = :admin_user_name,
admin_password = :admin_password,
WHERE admin_id = :admin_id
";
} else {
$data = array(
':admin_user_name' => $admin_user_name,
':admin_id' => $_POST["admin_id"]
);
$query = "
UPDATE tbl_admin
SET admin_user_name = :admin_user_name,
WHERE admin_id = :admin_id
";
}
$statement = $connect->prepare($query);
if ($statement->execute($data)) {
$success = '<div class="alert alert-success">Profil anda sudah diperbaharui</div>';
}
}
}
$query = "
SELECT * FROM tbl_admin
WHERE admin_id = '" . $_SESSION["admin_id"] . "'
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<div class="container" style="margin-top:30px">
<span id="message_operation"><?php echo $success; ?></span>
<div class="card">
<form method="post" id="profile_form">
<div class="card-header">
<div class="row">
<div class="col-md-9">Profil</div>
<div class="col-md-3" align="right">
</div>
</div>
</div>
<div class="card-body">
<div class="form-group">
<div class="row">
<label class="col-md-4 text-right">Nama Admin<span class="text-danger">*</span></label>
<div class="col-md-8">
<input type="text" name="admin_user_name" id="admin_user_name" class="form-control" />
<span class="text-danger"><?php echo $error_admin_user_name; ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<label class="col-md-4 text-right">Password <span class="text-danger">*</span></label>
<div class="col-md-8">
<input type="password" name="admin_password" id="admin_password" class="form-control" placeholder="Kosongkan Jika Tidak Ingin Diubah" />
<span class="text-danger"></span>
</div>
</div>
</div>
</div>
<div class="card-footer" align="center">
<input type="hidden" name="admin_id" id="admin_id" />
<input type="submit" name="button_action" id="button_action" class="btn btn-success btn-sm" value="Simpan" />
</div>
</form>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function() {
<?php
foreach ($result as $row) {
?>
$('#admin_user_name').val("<?php echo $row['admin_user_name']; ?>");
$('#admin_id').val("<?php echo $row['admin_id']; ?>");
<?php
}
?>
});
</script>
This code aims to change the admin name and change the admin password on the admin profile page

How to populate the value of a field on another field on same table

I have a table that has "customer registration" "Update Billing Address" and "Update Shipping Address" a group of fields. Upon registration the user fills the "customer registration".
I'd like the values on this field ("customer registration") to be populated automatically on "Update Billing Address" and "Update Shipping Address" instead of filling both fields manually. Note these are different fields but on same table in the Database.
How do I achieve this? Please pardon me if this question is too elementary, I've tried to find the answer here from previous post but can't get what I want. enter image description here
<?php require_once('header.php'); ?>
<?php
// Check if the customer is logged in or not
if(!isset($_SESSION['customer'])) {
header('location: '.BASE_URL.'logout.php');
exit;
} else {
// If customer is logged in, but admin make him inactive, then force logout this user.
$statement = $pdo->prepare("SELECT * FROM tbl_customer WHERE cust_id=? AND cust_status=?");
$statement->execute(array($_SESSION['customer']['cust_id'],0));
$total = $statement->rowCount();
if($total) {
header('location: '.BASE_URL.'logout.php');
exit;
}
}
?>
<?php
if (isset($_POST['form1'])) {
$valid = 1;
if(empty($_POST['cust_name'])) {
$valid = 0;
$error_message .= LANG_VALUE_123."<br>";
}
if(empty($_POST['cust_phone'])) {
$valid = 0;
$error_message .= LANG_VALUE_124."<br>";
}
if(empty($_POST['cust_address'])) {
$valid = 0;
$error_message .= LANG_VALUE_125."<br>";
}
if(empty($_POST['cust_country'])) {
$valid = 0;
$error_message .= LANG_VALUE_126."<br>";
}
if(empty($_POST['cust_city'])) {
$valid = 0;
$error_message .= LANG_VALUE_127."<br>";
}
if(empty($_POST['cust_state'])) {
$valid = 0;
$error_message .= LANG_VALUE_128."<br>";
}
if(empty($_POST['cust_zip'])) {
$valid = 0;
$error_message .= LANG_VALUE_129."<br>";
}
if($valid == 1) {
// update data into the database
$statement = $pdo->prepare("UPDATE tbl_customer SET cust_name=?, cust_cname=?, cust_phone=?, cust_country=?, cust_address=?, cust_city=?, cust_state=?, cust_zip=? WHERE cust_id=?");
$statement->execute(array(
strip_tags($_POST['cust_name']),
strip_tags($_POST['cust_cname']),
strip_tags($_POST['cust_phone']),
strip_tags($_POST['cust_country']),
strip_tags($_POST['cust_address']),
strip_tags($_POST['cust_city']),
strip_tags($_POST['cust_state']),
strip_tags($_POST['cust_zip']),
$_SESSION['customer']['cust_id']
));
$success_message = LANG_VALUE_130;
$_SESSION['customer']['cust_name'] = $_POST['cust_name'];
$_SESSION['customer']['cust_cname'] = $_POST['cust_cname'];
$_SESSION['customer']['cust_phone'] = $_POST['cust_phone'];
$_SESSION['customer']['cust_country'] = $_POST['cust_country'];
$_SESSION['customer']['cust_address'] = $_POST['cust_address'];
$_SESSION['customer']['cust_city'] = $_POST['cust_city'];
$_SESSION['customer']['cust_state'] = $_POST['cust_state'];
$_SESSION['customer']['cust_zip'] = $_POST['cust_zip'];
}
}
?>
<div class="page">
<div class="container">
<div class="row">
<div class="col-md-12">
<?php require_once('customer-sidebar.php'); ?>
</div>
<div class="col-md-12">
<div class="user-content">
<h3>
<?php echo LANG_VALUE_117; ?>
</h3>
<?php
if($error_message != '') {
echo "<div class='error' style='padding: 10px;background:#f1f1f1;margin-bottom:20px;'>".$error_message."</div>";
}
if($success_message != '') {
echo "<div class='success' style='padding: 10px;background:#f1f1f1;margin-bottom:20px;'>".$success_message."</div>";
}
?>
<form action="" method="post">
<?php $csrf->echoInputField(); ?>
<div class="row">
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_102; ?> *</label>
<input type="text" class="form-control" name="cust_name" value="<?php echo $_SESSION['customer']['cust_name']; ?>">
</div>
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_103; ?></label>
<input type="text" class="form-control" name="cust_cname" value="<?php echo $_SESSION['customer']['cust_cname']; ?>">
</div>
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_94; ?> *</label>
<input type="text" class="form-control" name="" value="<?php echo $_SESSION['customer']['cust_email']; ?>" disabled>
</div>
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_104; ?> *</label>
<input type="text" class="form-control" name="cust_phone" value="<?php echo $_SESSION['customer']['cust_phone']; ?>">
</div>
<div class="col-md-12 form-group">
<label for=""><?php echo LANG_VALUE_105; ?> *</label>
<textarea name="cust_address" class="form-control" cols="30" rows="10" style="height:70px;"><?php echo $_SESSION['customer']['cust_address']; ?></textarea>
</div>
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_106; ?> *</label>
<select name="cust_country" class="form-control">
<?php
$statement = $pdo->prepare("SELECT * FROM tbl_country ORDER BY country_name ASC");
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
?>
<option value="<?php echo $row['country_id']; ?>" <?php if($row['country_id'] == $_SESSION['customer']['cust_country']) {echo 'selected';} ?>><?php echo $row['country_name']; ?></option>
<?php
}
?>
</select>
</div>
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_107; ?> *</label>
<input type="text" class="form-control" name="cust_city" value="<?php echo $_SESSION['customer']['cust_city']; ?>">
</div>
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_108; ?> *</label>
<input type="text" class="form-control" name="cust_state" value="<?php echo $_SESSION['customer']['cust_state']; ?>">
</div>
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_109; ?> *</label>
<input type="text" class="form-control" name="cust_zip" value="<?php echo $_SESSION['customer']['cust_zip']; ?>">
</div>
</div>
<input type="submit" class="btn btn-primary" value="<?php echo LANG_VALUE_5; ?>" name="form1">
</form>
</div>
</div>
</div>
</div>
</div>
I expect the value of the cust_name, cust_cname, cust_phone, cust_country, cust_address, cust_city, cust_state, cust_zip to populate on the equivalent fields. If you understand what I mean.
The answear is in your code:
$statement = $pdo->prepare("SELECT * FROM tbl_country ORDER BY country_name ASC");
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row){ }?>
The last foreach is a cicle it runs on all the result table, so if you want to update the filds, you need to change the "question" to the table you want to query and then on the cicle store them in the correct variables cust_name, cust_cname, cust_phone, cust_country, cust_address, cust_city, cust_state, cust_zip i suppose.
Good Luck

My PHP signup form not working

I have created a signup form for my php website using Bootstrap but nothing happens when I click on register. Signup form is made in Bootstrap and it is not working.
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
<?php
require_once("company-db.php");
if (!isset($_POST['submit'])) {
?>
<form role="form" action="<?=$_SERVER['PHP_SELF']?>" method="post">
<h2>Please Sign Up <small>It's free and always will be.</small></h2>
<hr class="colorgraph">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6">
<div class="form-group">
<input type="text" name="username" id="username" class="form-control input-lg" placeholder="Username" tabindex="1">
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6">
<div class="form-group">
<input type="password" name="password" id="password" class="form-control input-lg" placeholder="Password" tabindex="2">
</div>
</div>
</div>
<div class="form-group">
<input type="text" name="company_name" id="company_name" class="form-control input-lg" placeholder="Company Name" tabindex="3">
</div>
<div class="form-group">
<input type="text" name="description" id="description" class="form-control input-lg" placeholder="Company Description" tabindex="4">
</div>
<div class="form-group">
<input type="email" name="email" id="email" class="form-control input-lg" placeholder="Email Address" tabindex="4">
</div>
<div class="row">
<div class="col-xs-4 col-sm-3 col-md-3">
<span class="button-checkbox">
<button type="button" class="btn" data-color="info" tabindex="7">I Agree</button>
<input type="checkbox" name="t_and_c" id="t_and_c" class="hidden" value="1">
</span>
</div>
<div class="col-xs-8 col-sm-9 col-md-9">
By clicking <strong class="label label-primary">Register</strong>, you agree to the Terms and Conditions set out by this site, including our Cookie Use.
</div>
</div>
<hr class="colorgraph">
<div class="row">
<div class="col-xs-12 col-md-6"><input type="submit" value="submit" class="btn btn-primary btn-block btn-lg" tabindex="7"></div>
<div class="col-xs-12 col-md-6">Sign In</div>
</div>
</form>
<?php
} else {
## connect mysql server
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
## query database
# prepare data for insertion
$username = $_POST['username'];
$password = $_POST['password'];
$company_name = $_POST['company_name'];
$description = $_POST['description'];
$email = $_POST['email'];
# check if username and email exist else insert
$exists = 0;
$result = $mysqli->query("SELECT username from companies WHERE username = '{$username}' LIMIT 1");
if ($result->num_rows == 1) {
$exists = 1;
$result = $mysqli->query("SELECT email from companies WHERE email = '{$email}' LIMIT 1");
if ($result->num_rows == 1) $exists = 2;
} else {
$result = $mysqli->query("SELECT email from companies WHERE email = '{$email}' LIMIT 1");
if ($result->num_rows == 1) $exists = 3;
}
if ($exists == 1) echo "<p>Username already exists!</p>";
else if ($exists == 2) echo "<p>Username and Email already exists!</p>";
else if ($exists == 3) echo "<p>Email already exists!</p>";
else {
# insert data into mysql database
$sql = "INSERT INTO `companies` (`id`, `username`, `password`, `company_name`, `description`, `email`)
VALUES (NULL, '{$username}', '{$password}', '{$company_name}', '{$description}', '{$email}')";
if ($mysqli->query($sql)) {
//echo "New Record has id ".$mysqli->insert_id;
echo "<p>Registred successfully!</p>";
} else {
echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>";
exit();
}
}
}
?>
</div>
</div>
You don't have a name for your submit button, so this won't get posted.
<input type="submit" value="submit" name="submit"
class="btn btn-primary btn-block btn-lg" tabindex="7">
Give the name attribute and make it set.
Note: You must never rely on Submit button's attribute!
The (!isset($_POST['submit'])) conditional statement depends on the execution of your code.

Forget password page, email/username form and new password form

Basically if the user comes to the page they get a form where they type in their username. That then checks against the db and then adds a generated key to their row in the db and emails the key link to them. The link brings them back to the same page but with a different form asking to update their password.
This is where my problem lies. The script first checks if that key exists. Even though it does exist I keep getting the uh oh key does not exist error. I've read through it a few times, taken breaks and still can't get it. Hopefully someone here can catch the issue!
Snippet of the problem:
<?php
if ($_GET['do'] == "password") {
$forgetKeyEmail = mysql_real_escape_string($_GET['key']);
if ($forgetKeyEmail !== "") {
$keyQuery = mysql_query("SELECT * FROM users WHERE forgetKey = '$forgetKeyEmail' LIMIT 1");
$keyCheck - mysql_num_rows($keyQuery);
if ($keyCheck == 1) {
?>
form goes here to update password
<?php
if ($_GET['do'] == "update") {
$hasher = new PasswordHash(10, false);
$resetPasswdord = $hasher->HashPassword(mysql_real_escape_string($_POST['inputPassword']));
$resetPassword = $_POST['inputPassword'];
if ($_POST['inputPassword'] !== "") {
mysql_query("UPDATE users SET password = '$resetPassword' WHERE forgetKey = '$forgetKeyEmail'");
echo "g";
?>
success message
<?php
}
else {
?>
empty field message
<?php
}
}
}
else{
?>
incorrect key message (what I keep getting)
<?php
}
}
}
Full code:
<?php
if ($_GET['do'] == "password") {
$forgetKeyEmail = mysql_real_escape_string($_GET['key']);
if ($forgetKeyEmail !== "") {
$keyQuery = mysql_query("SELECT * FROM users WHERE forgetKey = '$forgetKeyEmail' LIMIT 1");
$keyCheck - mysql_num_rows($keyQuery);
if ($keyCheck == 1) {
?>
<form method="POST"class="form-horizontal" action="?do=update&key=<?php echo $forgetKeyEmail; ?>" >
<div class="control-group">
<label class="control-label" for="inputPassword">New Password</label>
<div class="controls">
<input type="text" id="inputPassword" name="inputPassword" placeholder="Password">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-primary">Reset!</button>
</div>
</div>
</form>
<?php
if ($_GET['do'] == "update") {
$hasher = new PasswordHash(10, false);
$resetPasswdord = $hasher->HashPassword(mysql_real_escape_string($_POST['inputPassword']));
$resetPassword = $_POST['inputPassword'];
if ($_POST['inputPassword'] !== "") {
mysql_query("UPDATE users SET password = '$resetPassword' WHERE forgetKey = '$forgetKeyEmail'");
echo "g";
?>
<div class="alert alert-success" style="margin:0;">
<strong>Woooo!</strong> Your password has been changed, you can now login.
</div>
<?php
}
else {
?>
<div class="alert alert-error" style="margin:0;">
<strong>Woops!</strong> You need to fill out a password!
</div>
<?php
}
}
}
else{
?>
<div class="alert alert-error" style="margin:0;">
<strong>Uh oh!</strong> That key is incorrect.
</div>
<?php
}
}
}
elseif ($_GET['do'] == "reset") {
$resetUsername = mysql_real_escape_string($_POST['inputUser']);
if ($resetUsername !== "") {
$checkQuery = mysql_query("SELECT * FROM users WHERE username = '$resetUsername' LIMIT 1");
$checkExist = mysql_num_rows($checkQuery);
$userData = mysql_fetch_array($checkQuery);
$mailEmail = $userData['email'];
if ($checkExist == 1) {
$forgetKey = genRandomString() . genRandomString();
mysql_query("UPDATE users SET forgetKey = '$forgetKey' WHERE username = '$resetUsername'");
$message = "Hey there, ".$resetUsername." - We've received a request to reset your password. <br /><br /> Please click the following link to do so: <a href=\"http://localhost/vanilla/forgot.php?do=reset&key=".$forgetKey."\"";
echo $forgetKey;
mail($mailEmail, 'realvanil.la Password Reset', $message);
?>
<div class="alert alert-info" style="margin:0;">
An email has been sent to <strong><?php echo $userData['email']; ?></strong> with your reset information!
</div>
<?php
}
else {
?>
<div class="alert alert-error">
<strong>Uh oh!</strong> We can't seem to find an account with that username. Remember, it's your Minecraft username!
</div>
<form method="POST"class="form-horizontal" action="?do=reset" >
<div class="control-group">
<label class="control-label" for="inputUser">Username</label>
<div class="controls">
<input type="text" id="inputUser" name="inputUser" placeholder="Username">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-primary">Send Email!</button>
</div>
</div>
</form>
<?php
}
}
else {
?>
<div class="alert alert-error">
<strong>Uh oh!</strong> You need to tell us your username ;)
</div>
<form method="POST"class="form-horizontal" action="?do=reset" >
<div class="control-group">
<label class="control-label" for="inputUser">Username</label>
<div class="controls">
<input type="text" id="inputUser" name="inputUser" placeholder="Username">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-primary">Send Email!</button>
</div>
</div>
</form>
<?php
}
}
else {
?>
<form method="POST"class="form-horizontal" action="?do=reset" >
<div class="control-group">
<label class="control-label" for="inputUser">Username</label>
<div class="controls">
<input type="text" id="inputUser" name="inputUser" placeholder="Username">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-primary">Send Email!</button>
</div>
</div>
</form>
<?php
}
?>
you may want to edit you script so it does not have any syntax errors.
$keyCheck - mysql_num_rows($keyQuery);
change to
$keyCheck = mysql_num_rows($keyQuery);

Categories