This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 5 years ago.
I'm working on a CMS using PHP OOP. And in this CMS, there's a feature which admins of a website can add another admin. What I did for this, is that I created a form and added the action. This file is called admin_new.php and goes like this:
<?php
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_validation'] = "The email that you have entered is not a valid one";
}else{
$registration = new Register();
$notice = $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>
<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>
<?php
if(isset($notice['email_validation'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['email_validation'].".
</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-success'>
<strong>Hey!</strong> ".$notice['success_message'].".
</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>
As you can see I have called a class named Register and this class also goes here:
<?php
class Register
{
protected $notice = array();
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)&&!empty($email)&&!empty($password)&&!empty($groups)&&!empty($level))
{
$chk1 = $this->db->prepare("SELECT user_name FROM admins WHERE user_name = ?");
$chk1->bindParam(1,$username);
$chk1->execute();
if($chk1->rowCount() == 1)
{
$notice['username_exists'] = "Try different username";
return $this->notice;
}else{
$chk2 = $this->db->prepare("SELECT email_address 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 $this->notice;
}else{
$this->NewAdmin($username,$email,$password,$groups,$level);
$notice['success_message'] = "New admin was successfully added";
return $this->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();
}
}
public function getNotice()
{
return $this->notice;
}
}
?>
So it look basically fine and perfect but the ONLY problem with this is that, whenever I try to submit in the form, I get this error:
Undefined variable: groups in admin_new.php on line 22
And line 22 of admin_new.php is this:
$notice = $registration->CheckUname($username,$email,$password,$groups,$level);
So you can see in the code that I have defined the $groups variable already and it gets the groups value in the form. Therefore I REALLY don't know why am I getting this error ?!
So if you know what should I do or what is my fault, please let me know.. I really really appreciate that. Thanks
You are getting this error since $groups in call
$notice = $registration->CheckUname($username,$email,$password,$groups,$level);
$groups is written in different encoding and has non-ASCII characters. Probably one or more of the letters is in different language typed. Just type it in regular latin or copy over from above one of the variable mention.
That should solve the problem.
Edit:
In addition to future problems, if you stumble upon similar issue, just convert code to ASCII encoding and back to UTF-8, and all NON-ASCII characters will be replaced with some generic replacement like underscore or questionmark
In below function you have used $groups1 instead of $groups >> Update with $groups.
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,$groups1);
$reg->bindParam(5,$level);
$reg->execute();
}
}
Related
I have recently learned Object Oriented Programming PHP, and I tried to test my knowledge on that, so I tried to write some queries by myself...
(Example practice: inserting new row, updating a row and deleting a row).
And here is of the templates that I've coded myself in order to Insert New Row into database:
class Register
{
protected $notice = array();
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)&&!empty($email)&&!empty($password)&&!empty($groups)&&!empty($level))
{
$chk1 = $this->_db->prepare("SELECT user_name FROM admins WHERE user_name = ?");
$chk1->bindParam(1,$username);
$chk1->execute();
if($chk1->rowCount() == 1)
{
$notice['username_exists'] = "Try different username";
return $this->notice;
}else{
$chk2 = $this->_db->prepare("SELECT email_address 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 $this->notice;
}else{
$this->NewAdmin($username,$email,$password,$groups,$level);
$notice['success_message'] = "New admin was successfully added";
return $this->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();
}
}
public function getNotice()
{
return $this->notice;
}
}
And I called this Class on index:
<?php
if (isset($_POST['submit'])){
$username = $_POST['uname'];
$email = $_POST['email'];
$password = $_POST['pass'];
$groups = $_POST['groups'];
if($groups == "Administrator"){
$level = 2;
}else if($groups == "ContentCreatorBlog"){
$level = 3;
}else if($groups == "ContentCreatorShop"){
$level = 4;
}else if($groups == "ContentCreatorGallery"){
$level = 5;
}else if($groups == "Secretary"){
$level = 6;
}else if($groups == "SocialMediaManager"){
$level = 7;
}else if($groups == "Analyst"){
$level = 8;
}else{
$level = Null;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$notice['email_validation'] = "The email that you have entered is not a valid one";
}else{
$registration = new Register();
$notice[] = $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>
<section class="content">
<div class="row">
<div class="col-md-12">
<div class="box box-primary" id="myModal1">
<div class="box-header with-border">
<h3 class="box-title">Required Information</h3>
</div>
<?php
if(isset($notice['email_validation'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['email_validation'].".
</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-success'>
<strong>Hey!</strong> ".$notice['success_message'].".
</div>
";
}
?>
<form role="form" method="POST" action="" data-tour-index="1" data-tour-title="Card Type" data-tour-description="A card will usually be one of multiple similar type items on a page.">
<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="Administrator">Administrator</option>
<option value="ContentCreatorBlog">Blog Content Creator</option>
<option value="ContentCreatorShop">Shop Content Creator</option>
<option value="ContentCreatorGallery">Gallery Content Creator</option>
<option value="Secretary">Secretary</option>
<option value="SocialMediaManager">Social Media Manager</option>
<option value="Analyst">Analyst</option>
</select>
</div>
</div>
<div class="box-footer">
Visit admin new documentation to know more about this page.
</div>
<div class="box-footer">
<button name="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
</section>
</div>
So shortly what it does is showing the form and take some information and assign to parameters and then call the Class:
$registration = new Register();
$notice[] = $registration->CheckUname($username,$email,$password,$groups,$level);
So if the form faced any error such as:
already registerd username error
already exists email address error
It should simply take back an error message and show it to users by these code on the index page:
if(isset($notice['email_validation'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['email_validation'].".
</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-success'>
<strong>Hey!</strong> ".$notice['success_message'].".
</div>
";
}
Question:
The problem with this code is that the error messages does not pop up when a user enters information despite of the rules. However it still adds new row to table correctly.
So now the question is "Why the errors does not show up on page when users enters wrong information? Which part I made a mistake"
There's an diffrence between $notice and $this->notice. $notice is a local var and $this->notice is a class var. In your case, you only create a local var, assign a value, but return the still empty class var.
To fix this, simply replace it with $this->notice[..] = ....
But there are also other logical issues. Why does CheckUname creates a user? It would be the task of NewAdmin to call CheckUname. Also you could merge the two database queries into one, asking, if there's a entry with the username or the password. There's more to fix/change, but that would be part of Code Review
Your $notice variable will always be "not set" below. All the variables will be reset after post processing. However, you can redirect to the url that has the $notice variable. For instance, after all the processing you can:
redirect_to('index.php?notice=1');
where redirect_to is a function that takes a url.
function redirect_to($path){
die("<meta http-equiv='refresh' content=0;URL='".$path."' />");
}
And then in your index.php, you can check the notice variable if it is set. There are different ways on how to do this though.
EDIT:
function redirect_to($path){
header("Location: " . $path);
}
I have a bootstrap form and i use jquery modal so i can open it on the same index.php window and when it is submitted the form should close and save data to database which it does on the other hand if there are error messages from formValidation.php file then it should show error messages instead of closing form.Now it does disappear even if there are errors and when i open it up again error messages are shown.I know there has been similar questions but i really cant make up solution for weeks from all sources i can get so i am a bit frustrated.Would appreciate help.Here is my code.
Here is my form from index.php file
<div class="container" id="register" style="display:none">
<div class="row centered-form">
<div class="col-xs-12 col-sm-8 col-md-4 col-sm-offset-2 col-md-offset-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Banāns <small>Sia</small></h3>
</div>
<div class="panel-body">
<form role="form" class="ajax" method="post" action="index.php">
<?php include('classes/errors.php'); ?>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<label>Vārds</label>
<input type="text" name="firstname" value="<?php echo $firstName;?>" id="firstname" class="form-control input-sm" placeholder="Vārds">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<label>Uzvārds</label>
<input type="text" name="lastname" value="<?php echo $lastName;?>" id="lastname" class="form-control input-sm" placeholder="Uzvārds">
</div>
</div>
</div>
<div class="form-group">
<label>Lietotājvārds</label>
<input type="text" name="username" value="<?php echo $userName;?>" id="username" class="form-control input-sm" placeholder="Lietotājvārds">
</div>
<div class="form-group">
<label>E-pasts</label>
<input type="email" name="email" value="<?php echo $email;?>" id="email" class="form-control input-sm" placeholder="E-pasta adrese">
</div>
<div class="form-group">
<label>Telefona numurs</label>
<input type="number" name="number" value="<?php echo $number;?>" id="number" class="form-control input-sm" placeholder="Telefona numurs">
</div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<label>Parole</label>
<input type="password" name="password1" id="password1" class="form-control input-sm" placeholder="Parole">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<label>Apstipriniet paroli</label>
<input type="password" name="password2" id="password2" class="form-control input-sm" placeholder="Apstipriniet paroli">
</div>
</div>
</div>
<input type="submit" name="submit" id="submit" value="Register" class="btn btn-info btn-block">
<span id="success_msg"></span>
<span id="error_msg"></span>
<p>Aizvērt ...</p>
</form>
</div>
</div>
</div>
</div>
</div>
Here is my formValidation.php
<?php
include('classes/config.php');
$firstName = $lastName = $userName = $email = $number = $password1 = $password2 = "" ;
$errors = array();
if(isset($_POST["submit"])) {
$firstName = mysqli_real_escape_string($con, $_POST["firstname"]);
$lastName = mysqli_real_escape_string($con, $_POST["lastname"]);
$userName = mysqli_real_escape_string($con, $_POST["username"]);
$email = mysqli_real_escape_string($con, $_POST["email"]);
$number = mysqli_real_escape_string($con, $_POST["number"]);
$password1 = mysqli_real_escape_string($con, $_POST["password1"]);
$password2 = mysqli_real_escape_string($con, $_POST["password2"]);
if (empty($firstName)) {
array_push($errors, "Lūdzu ievadiet vārdu.");
} else {
$firstName = test_input($firstName);
if (!preg_match("/^[a-zēūīāšžčķļņA-ZŅĒŪĪĀŠŽČĶĻŅ]*$/",$firstName)) {
array_push($errors, "Lūdzu ievadiet tikai burtus.");
}
}
if (empty($lastName)) {
array_push($errors, "Lūdzu ievadiet uzvārdu.");
} else {
$lastName = test_input($lastName);
if (!preg_match("/^[a-zēūīāšžčķļņA-ZŅĒŪĪĀŠŽČĶĻŅ]*$/",$lastName)) {
array_push($errors, "Lūdzu ievadiet tikai burtus.");
}
}
if (empty($userName)){
array_push($errors, "Lūdzu ievadiet lietotājvārdu.");
} else {
$userName = test_input($userName);
if(strlen($userName <= "6")){
array_push($errors, "Lietotājvārdam jāsastāv no vismaz 6 burtiem un/vai cipariem.");
}
}
if (empty($email)) {
array_push($errors,"Lūdzu ievadiet e-pasta adresi.");
} else {
$email = test_input($email);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
array_push($errors, "Lūdzu pārbaudiet e-pasta adresi.");
}
}
if (empty($number)) {
$number = "NULL";
} else {
$number = test_input($number);
if (!preg_match("/^[0-9]{8}$/", $number)) {
array_push($errors, "Lūdzu ievadiet 8 ciparu numuru.");
}
}
if(!empty($password1) && $password1 == $password2){
$password1 = test_input($password1);
$password2 = test_input($password2);
} elseif ($password1 != $password2){
array_push($errors, "Paroles nesakrīt.");
} else {
array_push($errors, "Lūdzu ievadiet paroli.");
}
if(count($errors) == 0){
$password = md5($password1);
$query = "INSERT INTO users(firstname, lastname, username, email, phonenumber, password)
VALUES ('$firstName', '$lastName', '$userName', '$email', '$number', '$password')";
mysqli_query($con, $query);
$_SESSION["username"] = "$userName";
$_SESSION["succes"] = "Apsveicu, tu esi pieslēdzies!";
header("location: index.php");
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
and my error messages are looped trough in seperate errors.php file and are echoed in error class in index.php
<?php if (count($errors) > 0) : ?>
<div class="error">
<?php foreach ($errors as $error) : ?>
<p><?php echo $error ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
And finally Ajax
This submits the form and it closes even if there are error messages.
$("#submit").click(function() {
e.preventDefault();
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
var username = $("#username").val();
var email = $("#email").val();
var number = $("#number").val();
var password1 = $("#password1").val();
var password2 = $("#password2").val();
var submit = $("#submit").val();
$.ajax({
url: "classes/formValidation.php",
method: "POST",
data: {
firstname: firstname,
lastname: lastname,
username: username,
email: email,
number: number,
password1: password1,
password2: password2,
},
success: function(data){
if(data == "success"){
$("#register").hide();
location.reload();
}else{
return false;
}
}
});
});
And i have tried this
If i open up console it retrieves all my form name attributes in an object.I have tried to change action to my formValidation.php or errors.php but it does not work.
$('form.ajax').on('submit', function(){
var bzz = $(this),
url = bzz.attr('action'),
method = bzz.attr('method'),
data = {};
bzz.find('[name]').each(function(index, value) {
var bzz = $(this),
name = bzz.attr('name'),
value = bzz.val();
data[name] = value;
console.log(data);
});
$.ajax({
url: url,
type: method,
data: data,
success: function(response) {
console.log(response);
}
});
return false;
});
I want to display an error if a username exists, however no error is being thrown.
the function is on the User.php and im trying to display an error from that function.
i referenced this, however it is not relevant to the OOP way.
User.php
public function check_user_exists($username)
{
try{
$stmt = $this->db->prepare("SELECT user_name FROM users WHERE user_name=:username");
$stmt->execute(array(':username'=>$username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$row['user_name'] == $username;
}
catch(PDOExeception $e)
{
echo $e->getMessage();
}
}
Index.php
<?php
session_start();
require_once 'User.php';
$guest = new User();
if($guest->is_logged())
{
$guest->redirect('profile');
}
if (isset($_POST['btn_signup']) ){
$username = htmlentities($_POST['txt_username']);
$unpass = htmlentities($_POST['txt_password']);
$password = password_hash($unpass, PASSWORD_BCRYPT, ['cost' => 12] );
$unemail = $_POST['txt_email'];
$email = filter_var($unemail, FILTER_VALIDATE_EMAIL);
$guest = new User();
if($email == ""){
$errors[]= "Enter a Email";
}
if($username == ""){
$errors[]= "Enter a Username please";
}
if($password == ""){
$errors[]= "Enter a Password";
}
if($guest->check_user_exists($username)){
$errors[]= "Username Already Taken";
}
if($guest->signup($email,$password,$username)){
$guest->redirect('profile');
die('didnt redirect');
}
else{
$errors[]= "Invalid Entry";
}
}
$title = "Home";
require_once 'layouts/header.php';
?>
<div class="container">
<div class="row">
<div class="col-md-6">
<?php
if(isset($errors))
{
foreach($errors as $error)
{
?>
<div class="alert alert-danger">
<i class="glyphicon glyphicon-warning-sign"></i> <?php echo $error; ?>
</div>
<?php
}
}
else if(isset($_GET['joined']))
{
?>
<div class="alert alert-info">
<i class="glyphicon glyphicon-log-in"></i> Successfully registered <a href='index.php'>login</a> here
</div>
<?php
}
?>
<h1>Sign Up</h1>
<form action ="" method="POST">
<div class="form-group">
<label for="Email">Email address</label>
<input type="email" class="form-control" aria-describedby="emailHelp" name="txt_email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="Username">Username</label>
<input type="text" class="form-control" aria-describedby="emailHelp" name="txt_username" placeholder="Enter Username">
</div>
<div class="form-group">
<label for="Password">Password</label>
<input type="password" class="form-control" aria-describedby="emailHelp" name="txt_password" placeholder="Enter password">
</div>
<button type="submit" name="btn_signup" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</body>
</html>
public function check_user_exists($username)
{
try{
$stmt = $this->db->prepare("SELECT user_name FROM users WHERE user_name=:username");
$stmt->execute(array(':username'=>$username));
return $stmt->fetchColumn() > 0; // fetchColumn return the number of rows selected
}
catch(PDOExeception $e)
{
echo $e->getMessage();
}
}
Your function doesn't actually return or do anything. Return the result of fetch(), if it returns true - a result was found. If it returns false, there was no row matching the username. You don't need to check anything after that, as the fetch() method will only be true if a result was found.
Adjusted for that, your function would look like this
public function check_user_exists($username) {
try{
$stmt = $this->db->prepare("SELECT user_name FROM users WHERE user_name=:username");
$stmt->execute(array(':username' => $username));
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOExeception $e) {
echo $e->getMessage();
}
}
Also, its not a good idea to output errors directly (on a testing/development environment its fine, but on a live environment you should log it (error_log()) instead.
http://php.net/manual/en/pdostatement.fetch.php
public function ifUserAlreadyExist(string $email):bool{
$sql = "SELECT 1 FROM users WHERE email= :Email";
$statment = $this->conn->prepare($sql);
if (false === $statment) {
return false;
}
$statment->execute([':Email' => $email]);
return (bool)$statment->fetchColumn();
}
//You need to just select 1 object if is already exist and in this case function hint will be so handy, can set the function to boolean and see if it return true or false.
I hope I could help.
I'm making my own custom CMS using PHP Object Oriented... I have made a page where a main admin of a site can add another admin. In order to do this I made this form:
<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">
<option>Main Admin</option>
<option>Administrator</option>
<option>Content Creator</option>
<option>Analyst</option>
</select>
</div>
</div>
<div class="box-footer">
<button name="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
Then I added this as action file:
if (isset($_POST['submit'])) {
$username = $_POST['uname'];
$email = $_POST['email'];
$password = $_POST['pass'];
$registration = new Register();
$registration->CheckUname($username,$email);
}
So as you can see I have called a class called Register and in this class I coded this:
class Register {
private $db;
public function __construct() {
$this->db = new Connection();
$this->db = $this->db->dbConnect();
}
public function CheckUname($username,$email) {
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";
} 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";
}else{
// I want to call the NewAdmin function here
}
}
}
}
public function NewAdmin($username,$email,$password) {
if(!empty($username)&&!empty($email)&&!empty($password)) {
$reg = $this->db->prepare("INSERT INTO admins (user_name, email_address, password_hash) VALUES ( '?', '?', '?')");
$reg->bindParam(1,$username);
$reg->bindParam(2,$email);
$reg->bindParam(2,$password);
$reg->execute();
}
}
}
Basically I tried to check if that username already exists or not then I also checked if the email exists and if not I want to call the NewAdmin function so the admin can be inserted to db. The problem is I don't know how to do that inside of the CheckUname function. Any help please ?
Also I've got another question which is why the errors that should be produced when the user enter a username or email that already exists in database does not shown! However I have set a variable for this:
if($chk1->rowCount() == 1) {
$notice['username_exists'] = "Try different username";
} 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";
} else {
// I want to call the NewAdmin function here
}
}
I have also set the error in the page like this:
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>";
}
But no errors appears on the page while submitting a username or an email that exists in the db!
Use $this->NewAdmin($username,$email,$password) inside the CheckUname() function of Register class. You can call same class function inside another class by using $this. $this represents the current class object.
I am just learning to use stack overflow, please don't approve this edit of mine...! Thanks..
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Goodday house,i'm developing this site that has a registration/login page as my first project and i'm stucked right now.
I added php validation to my registration form but the database insert statement refuses to work after,though all conditional statements were fulfilled,i tried putting a redirect loop immediately after the insert statement but my script automatically (somehow) jumps the "Insert statement" and processes the redirect code..
This is the code below
<!-- Php validation-->
<?php
include 'var.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array(); // Starts an array to store errors.
//Validation rules involves trimming,validating and sanitizating
$name = trim($_POST['name']);
$strippedname = mysqli_real_escape_string($con, strip_tags($name)) ;
$length = mb_strlen($strippedname, 'utf-8') ;
if ($length < 8 ) {
$errors[]= 'Your full name shouldn\'t be less than 8 letters' ;
} else {
$name = $strippedname ;
}
$email = FALSE ;
if (empty($_POST['email'])) {
$errors[] = 'You didn\'t provide any email address' ;
} // Next is removal of spaces and validation.
if (filter_var((trim($_POST['email'])), FILTER_VALIDATE_EMAIL)) {
$email = mysqli_real_escape_string($con, (trim($_POST['email'])));
}
else {
$errors[] = 'Email address was provided in the wrong format';
}
$pho = trim($_POST['phone']) ; // next line of code removes all characters that aren't digits
$phon = preg_replace('/\D+/', '', ($_POST['phone']));
$strippedphone = mysqli_real_escape_string($con, strip_tags($phon));
$length = mb_strlen($strippedphone, 'utf-8') ;
if ($length <> 11 ) {
$errors[] = 'Phone number should contain only eleven digits';
}
else {
$phone = $strippedphone ;
}
$add = trim($_POST['address']) ;
$strippedadd = mysqli_real_escape_string($con, strip_tags($add)) ;
$length = mb_strlen($strippedadd, 'utf-8') ;
if ($length < 15) {
$errors[]= 'Address should not be lesser than 15 letters' ;
} else {
$address = $strippedadd ;
}
if (empty($_POST['gender'])) {
$errors[] = 'You didn\'t select a gender';
} else {
$gend = trim($_POST['gender']);
}
$user = trim($_POST['username']);
$strippeduser = mysqli_real_escape_string($con, strip_tags($user)) ;
$length = mb_strlen($strippeduser, 'utf-8') ;
if ($length < 6) {
$errors[] = 'Username should contain a minimum of 6 letters and maximum of 18';
} else {
$confirmeduser = $strippeduser ;
}
if (empty($_POST['password'])){
$errors[] ='Please enter a valid password';
}
if(!preg_match('/^\w{10,40}$/', $_POST['password'])) {
$errors[] = 'Invalid password, use 10 to 40 characters without applying spacing.';
} else{
$password = $_POST['password'];
}
if($_POST['password'] == $_POST['confirm_password']) {
$pass = mysqli_real_escape_string($con, trim($password));
$newpass = password_hash($pass, PASSWORD_DEFAULT) ;
}else{
$errors[] = 'passwords don\'t match.';
}
if(empty($errors)) { // If no problems occurred
//Determine whether the email address has already been registered for a user
$query = mysqli_query($con, "INSERT INTO `customer`(`name`, `email`,
`phone`, `address`, `gender`, `username`, `password`) VALUES($name,$email,$phone,
$address,$gend,$confirmeduser,$newpass)") ;
echo "Done";
// end of mysqli_num_Rows
} // End of if (empty($errors))
else{ // Display the errors if any are found.
echo '
<p class="error">The following error(s) were found in the submitted form :<br>';
foreach ($errors as $msg) { // Echo each error
echo " $msg<br>";
}
}
}
?>
This is the html form
<form action="register.php" method="POST" class="form-horizontal" style="margin-top:30px" id="signup">
<fieldset> <div class="form-group">
<legend> Customer Details </legend>
</div>
<div class="form-group">
<label for="name" class="control-label"> Full Name : </label>
<input type="text" value="<?php if (isset($_POST['name'])) echo $_POST['name']; ?>"
name="name" placeholder="Your Full Name" class="required" title="Please type in your name" >
</div>
<div class="form-group">
<label for="email" class="control-label"> Email address </label>
<input type="text" name="email" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>"
placeholder="someone#example.com">
</div>
<div class="form-group">
<label for="phone" class="control-label"> Phone Number :</label>
<input type="tel" name="phone" value="<?php if (isset($_POST['phone'])) echo $_POST['phone']; ?>"
placeholder="08137871320" class="required digits">
</div>
<div class="form-group">
<label for="address" class="control-label"> Contact Address : </label>
<input type="text" name="address" value="<?php if (isset($_POST['address'])) echo $_POST['address']; ?>"
placeholder="No 4,street name,ikeja"
class="required" title="Please type in contact address plus your city's name">
</div>
<!--<div class="form-group">
Drop down menu for selecting a state from the 36 states to be provided
</div>-->
<div class="form-group">
<label for="name">Select Your gender :</label>
<select name="gender" class="form-control">
<option value="male" > Male </option>
<option value="female">Female </option>
</select>
</div>
</fieldset>
<fieldset> <div class="form-group">
<legend> Login Information </legend>
</div>
<div class="form-group">
<label for="username" class="control-label"> Username : </label>
<input type="text" name="username" placeholder="e.g Lords" value="<?php if (isset($_POST['username']))
echo $_POST['username']; ?>">
</div>
<div class="form-group">
<label for="password" class="control-label"> Password : </label>
<input type="password" name="password" id="password" placeholder="Your Password Here">
</div>
<div class="form-group">
<label for="cpassword" class="control-label">Confirm Password : </label>
<input type="password" name="confirm_password" placeholder="Confirm Your Password Here">
</div>
</fieldset>
</div>
</div>
</div>
<div class="form-group" style="text-align:center">
<button type="submit" class="btn btn-success" name="submit"> REGISTER </button>
<button type="reset" id="fat-btn" class="btn btn-danger" data-loading-text="Loading..."> RESET </button> <br>
<p class="lead">
Already a registered user ?,do make use of the
<a href="login.php" class="navbar-link" data-toggle="tooltip" title="When clicked upon,
a page requesting for your username and password is generated,allowing you to book orders">
login page </a>
</p>
</div>
</form>
Thanks a lot for your reply
Since we're more than likely dealing with strings, these variables in your VALUES
($name,$email,$phone,$address,$gend,$confirmeduser,$newpass)
needs to be quoted:
('$name','$email','$phone','$address','$gend','$confirmeduser','$newpass')
Had you checked for errors using or die(mysqli_error($con)) to mysqli_query()
would have signaled the quotes errors.
Sidenote:
You should use prepared statements, or PDO with prepared statements, they're much safer.
Additional note that Barmar spotted:
<?phpinclude 'var.php';
there needs to be a space in there between php and include
<?php include 'var.php';
unless that's a copy/paste error or typo.
and >? again, another spotted error which should be ?>
On the PHP side of things:
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.