I have the controller below and I would like it do the following things:
Show an error if the username is taken -> currently just submits as
normal even through the specific user is in the database.
Populate with data if there was an error -> currently populates with
the imported data if correct
Keep active state of the selected drop down menu item
View:
<h1><?php echo $companyName; echo nbs(1);?> - <?php echo $pageTitle; ?></h1>
<?php
if($success == TRUE) {
echo '<section id = "validation">Page Updated</section>';
}
?>
<p>Error: <?php echo validation_errors();?></p>
<div class="formContent">
<form action="createUser" method="post">
<fieldset class="control-group">
<label for="userName">User Name:</label><input type="text" id="userName" name="userName" value="<?php echo set_value('userName'); ?>" placeholder="User Name">
<label for="userPassword">User Password:</label><input type="password" id="userPassword" name="userPassword" value="<?php echo set_value('userPassword'); ?>" placeholder="User Password">
<label for="userFirstName">First Name:</label><input type="text" id="userFirstName" name="userFirstName" value="<?php echo set_value('userFirstName'); ?>" placeholder="First Name">
<label for="userLastName">Last Name:</label><input type="text" id="userLastName" name="userLastName" placeholder="Last Name">
<label for="userEmail">E-Mail:</label> <input type="text" id="userEmail" name="userEmail" placeholder="Admin E-mail">
<label for="userGroup"> User Group:</label>
<select name="userGroup" id="userGroup">
<option value="select">Please Select</option>
<option value="admin">Admin</option>
<option value="user">User</option>
</select>
<label for="userActive"> User Active:</label>
<select name="userActive" id="userActive">
<option value="select">Please Select</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
<div>
<button type="submit" class="btn-primary">Create</button>
</div>
</fieldset>
</form>
</div>
Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class createUser extends CI_Controller {
public function index()
{
//Form Validation prep making sure its all clean
$this->form_validation->set_rules('userName', 'User Name', 'trim|required|is_unique[users.userName]|xss_clean');
$this->form_validation->set_rules('userPassword', 'User Password', 'trim|required|xss_clean|sha1');
$this->form_validation->set_rules('userFirstName', 'First Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('userLastName', 'Last Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('userEmail', 'E-Mail', 'trim|required|xss_clean');
$this->form_validation->set_rules('userGroup', 'User Group', 'trim|required|xss_clean');
$this->form_validation->set_rules('userActive', 'User Active', 'trim|required|xss_clean');
//If form validation fails load previous page with errors else do the job and insert data into db
if($this->form_validation->run() == FALSE)
{
$data['success'] = "";
}else{
$username = $this->input->post('userName');
$password = $this->input->post('userPassword');
$firstname = $this->input->post('userFirstName');
$lastname = $this->input->post('userLastName');
$email = $this->input->post('userEmail');
$group = $this->input->post('userGroup');
$active = $this->input->post('userActive');
$passwordHash = $this->encrypt->sha1($password); // Lets encrypt the password why sha1? MD5 is for tossers
// If the data is correct follow through with db insert
if($this->users_model->createUser($username,$passwordHash,$firstname,$lastname,$email,$group,$active))
{
$data['success'] = TRUE;
}
}
$data['companyName'] = $this->core_model->companyName();
$data['pageTitle'] = "Create User";
$this->load->view('admin/assets/header', $data);
$this->load->view('admin/createUser', $data);
$this->load->view('admin/assets/footer');
}
}
/* End of file login.php */
/* Location: ./application/controllers/admin/createUser.php */
If I were you, I would use a callback ( http://codeigniter.com/user_guide/libraries/form_validation.html#callbacks )
$this->form_validation->set_rules('userName', 'User Name', 'trim|required|xss_clean|callback__checkUsername');
as for your select drop downs, use the set_value() function
<select name="userGroup" id="userGroup">
<option value="select"<?=(set_value('userGroup')=='select')?' selected="selected"':''?>>Please Select</option>
<option value="admin"<?=(set_value('userGroup')=='admin')?' selected="selected"':''?>>Admin</option>
<option value="user"<?=(set_value('userGroup')=='user')?' selected="selected"':''?>>User</option>
</select>
Good luck
I am going at this purely from a logical php point as I know nothing about codeigniter
With regards to checking if a username is already taken, I would do a an db query on the username field in your "users" table and see if the name exists.
I see you have done this:
$this->form_validation->set_rules('userName', 'User Name', 'trim|required|is_unique[users.userName]|xss_clean');
I dont know the standard for referencing db tables in igniter, but maybe you are referencing the fields incorrectly. Also I would change every to lowercase while checking to ensure that you check is not case sensitive... unless you want case sensitive usernames.
Related
I am making a simple Form the problem i am facing is when i submit the form values still remains in the field. and I want to clear it after SUCCESSFUL submission. Please help.
here is my code for the form..
<label class="w">Plan :</label>
<select autofocus="" name="plan" required="required">
<option value="">Select One</option>
<option value="FREE Account">FREE Account</option>
<option value="Premium Account Monthly">Premium Account Monthly</option>
<option value="Premium Account Yearly">Premium Account Yearly</option>
</select>
<br>
<label class="w">First Name :</label><input name="firstname" type="text" placeholder="First Name" required="required" value="<?php echo $_POST['firstname'];?>"><br>
<label class="w">Last Name :</label><input name="lastname" type="text" placeholder="Last Name" required="required" value="<?php echo $_POST['lastname'];?>"><br>
<label class="w">E-mail ID :</label><input name="email" type="email" placeholder="Enter Email" required="required" value="<?php echo $_POST['email'];?>"><br>
<label class="w">Password :</label><input name="password" type="password" placeholder="********" required="required" value="<?php echo $_POST['password'];?>"><br>
<label class="w">Re-Enter Password :</label><input name="confirmpassword" type="password" placeholder="********" required="required" value="<?php echo $_POST['confirmpassword'];?>"><br>
<label class="w">Street Address 1 :</label><input name="strtadd1" type="text" placeholder="street address first" required="required" value="<?php echo $_POST['strtadd1'];?>"><br>
<label class="w">Street Address 2 :</label><input name="strtadd2" type="text" placeholder="street address second" value="<?php echo $_POST['strtadd2'];?>"><br>
<label class="w">City :</label><input name="city" type="text" placeholder="City" required="required" value="<?php echo $_POST['firstname'];?>"><br>
<label class="w">Country :</label><select autofocus="" id="a1_txtBox1" name="country" required="required" placeholder="select one" value="<?php echo $_POST['country'];?>">
Any help would be appriciated
They remain in the fields because you are explicitly telling PHP to fill the form with the submitted data.
<input name="firstname" type="text" placeholder="First Name" required="required"
value="<?php echo $_POST['firstname'];?>">
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ HERE
Just remove this, or if you want a condition to not do so make a if statement to that echo or just cleanup the $_POST fields.
$_POST = array(); // lets pretend nothing was posted
Or, if successful, redirect the user to another page:
header("Location: success.html");
exit; // Location header is set, pointless to send HTML, stop the script
Which by the way is the prefered method. If you keep the user in a page that was reached through a POST method, if he refreshes the page the form will be submitted again.
You can use .reset() on your form.
$(".myform")[0].reset();
I was facing this similiar problem and did not want to use header() to redirect to another page.
Solution:
Use $_POST = array(); to reset the $_POST array at the top of the form, along with the code used to process the form.
The error or success messages can be conditionally added after the form.
Hope this helps :)
Here is the solution for when the for is submitted with the successful message all form fields to get cleared. for that set the values equals to false check the code below
<?php
$result_success = '';
$result_error = '';
$full_Name_error = $email_error = $msg_error = '';
$full_Name = $email = $msg = $phoneNumber = '';
$full_Name_test = $email_test = $msg_test = '';
//when the form is submitted POST Method and must be clicked on submit button
if ($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['form-submit'])) {
$full_Name = $_POST['fullName'];
$email = $_POST['email'];
$phoneNumber = $_POST['phoneNumber'];
$msg = $_POST['message'];
// Form Validation for fullname
if (empty($full_Name)) {
$full_Name_error = "Name is required";
} else {
$full_Name_test = test_input($full_Name);
if (!preg_match("/^[a-z A-Z]*$/", $full_Name_test)) {
$full_Name_error = "Only letters and white spaces are allowed";
}
}
//Form Validation for email
if (empty($email)) {
$email_error = "Email is required";
} else {
$email_test = test_input($email);
if (!filter_var($email_test, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid Email format";
}
}
//Form Validation for message
if (empty($msg)) {
$msg_error = "Say atleast Hello!";
} else {
$msg_test = test_input($msg);
}
if ($full_Name_error == '' and $email_error == '' and $msg_error == '') {
// Here starts PHP Mailer
date_default_timezone_set('Etc/UTC');
// Edit this path if PHPMailer is in a different location.
require './PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
/*Server Configuration*/
$mail->Host = 'smtp.gmail.com'; // Which SMTP server to use.
$mail->Port = 587; // Which port to use, 587 is the default port for TLS security.
$mail->SMTPSecure = 'tls'; // Which security method to use. TLS is most secure.
$mail->SMTPAuth = true; // Whether you need to login. This is almost always required.
$mail->Username = ""; // Your Gmail address.
$mail->Password = ""; // Your Gmail login password or App Specific Password.
/*Message Configuration*/
$mail->setFrom($email, $full_Name); // Set the sender of the message.
$mail->addAddress(''); // Set the recipient of the message.
$mail->Subject = 'Contact form submission from your Website'; // The subject of the message
/*Message Content - Choose simple text or HTML email*/
$mail->isHTML(true);
// Choose to send either a simple text email...
$mail->Body = 'Name: ' . $full_Name . '<br>' . 'PhoneNumber: ' . $phoneNumber . '<br>' . 'Email: ' . $email . '<br><br>' . 'Message: ' . '<h4>' . $msg . '</h4>'; // Set a plain text body.
// ... or send an email with HTML.
//$mail->msgHTML(file_get_contents('contents.html'));
// Optional when using HTML: Set an alternative plain text message for email clients who prefer that.
//$mail->AltBody = 'This is a plain-text message body';
// Optional: attach a file
//$mail->addAttachment('images/phpmailer_mini.png');
if ($mail->send()) {
$result_success = "Your message was sent successfully! " .
//Here is the solution for when the for is submitted with the successful message all form fields to get cleared.
$full_Name;
$full_Name = false;
$email = false;
$phoneNumber = false;
$msg = false;
} else {
$result_error = "Something went wrong. Check your Network connection and Please try again.";
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
The POST data which holds the submitted form data is being echoed in the form, eg:
<input name="firstname" type="text" placeholder="First Name" required="required"
value="<?php echo $_POST['firstname'];?>"
Either clear the POST data once you have done with the form - ie all inputs were ok and you have actioned whatever your result from a form is.
Or, once you have determined the form is ok and have actioned whatever you action from the form, redirect the user to a new page to say "all done, thanks" etc.
header('Location: thanks.php');
exit();
This stops the POST data being present, it's know as "Post/Redirect/Get":
http://en.wikipedia.org/wiki/Post/Redirect/Get
The Post/Redirect/Get (PRG) method and using another page also ensures that if users click browser refresh, or back button having navigated somewhere else, your form is not submitted again.
This means if your form inserts into a database, or emails someone (etc), without the PRG method the values will (likely) be inserted/emailed every time they click refresh or revisit the page using their history/back button.
Put the onClick function in the button submit:
<input type="text" id="firstname">
<input type="text" id="lastname">
<input type="submit" value="Submit" onClick="clearform();" />
In the <head>, define the function clearform(), and set the textbox value to "":
function clearform()
{
document.getElementById("firstname").value=""; //don't forget to set the textbox id
document.getElementById("lastname").value="";
}
This way the textbox will be cleared when you click the submit button.
I was just trying to fix same error, I finally fixed it, so I will copy to you part of the code, maybe it helps you.
<input type="text" name="usu" id="usu" value="<?php echo $usu;?>" ></input>
<input type="text" name="pass" id="pass" value="<?php echo $varpass;?>"></input>
those are the inputs I wanted to clean after pressing my button.
And here php code:
$query= "INSERT INTO usuarios (tipo, usuario, password) VALUES ('".$vartipo."', '".$usu."', '".$varpass."')";
if (!mysqli_query($conexion,$query)){
die('Error: ' . mysqli_error($conexion));
}
else{
$usu = '';
$varpass= '';
$result = '<div class="result_ok">El usuario se ha registrado con éxito! <div>';
}
$usu = '';
$varpass= '';
those are the lines that cleans the inputs :D
this code will help you
if($insert){$_POST['name']="";$_POST['content']=""}
If you want your form's field clear, you must only add a delay in the onClick event like:
<input name="submit" id="MyButton" type="submit" class="btn-lg" value="ClickMe" onClick="setTimeout('clearform()', 2000 );"
onClick="setTimeout('clearform()', 1500 );" . in 1,5 seconds its clear
document.getElementById("name").value = ""; <<<<<<just correct this
document.getElementById("telephone").value = ""; <<<<<correct this
By clearform(), I mean your clearing-fields function.
// This file is PHP.
<html>
<?php
if ($_POST['submit']) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$confirmpassword = $_POST['confirmpassword'];
$strtadd1 = $_POST['strtadd1'];
$strtadd2 = $_POST['strtadd2'];
$city = $_POST['city'];
$country = $_POST['country'];
$success = '';
// Upon Success.
if ($firstname != '' && $lastname != '' && $email != '' && $password != '' && $confirmpassword != '' && $strtadd1 != '' && $strtadd2 != '' && $city != '' && $country != '') {
// Change $success variable from an empty string.
$success = 'success';
// Insert whatever you want to do upon success.
} else {
// Upon Failure.
echo '<p class="error">Fill in all fields.</p>';
// Set $success variable to an empty string.
$success = '';
}
}
?>
<form method="POST" action="#">
<label class="w">Plan :</label>
<select autofocus="" name="plan" required="required">
<option value="">Select One</option>
<option value="FREE Account">FREE Account</option>
<option value="Premium Account Monthly">Premium Account Monthly</option>
<option value="Premium Account Yearly">Premium Account Yearly</option>
</select>
<br>
<label class="w">First Name :</label><input name="firstname" type="text" placeholder="First Name" required="required" value="<?php if (isset($firstname) && $success == '') {echo $firstname;} ?>"><br>
<label class="w">Last Name :</label><input name="lastname" type="text" placeholder="Last Name" required="required" value="<?php if (isset($lastname) && $success == '') {echo $lastname;} ?>"><br>
<label class="w">E-mail ID :</label><input name="email" type="email" placeholder="Enter Email" required="required" value="<?php if (isset($email) && $success == '') {echo $email;} ?>"><br>
<label class="w">Password :</label><input name="password" type="password" placeholder="********" required="required" value="<?php if (isset($password) && $success == '') {echo $password;} ?>"><br>
<label class="w">Re-Enter Password :</label><input name="confirmpassword" type="password" placeholder="********" required="required" value="<?php if (isset($confirmpassword) && $success == '') {echo $confirmpassword;} ?>"><br>
<label class="w">Street Address 1 :</label><input name="strtadd1" type="text" placeholder="street address first" required="required" value="<?php if (isset($strtadd1) && $success == '') {echo $strtadd1;} ?>"><br>
<label class="w">Street Address 2 :</label><input name="strtadd2" type="text" placeholder="street address second" value="<?php if (isset($strtadd2) && $success == '') {echo $strtadd2;} ?>"><br>
<label class="w">City :</label><input name="city" type="text" placeholder="City" required="required" value="<?php if (isset($city) && $success == '') {echo $city;} ?>"><br>
<label class="w">Country :</label><select autofocus="" id="a1_txtBox1" name="country" required="required" placeholder="select one" value="<?php if (isset($country) && $success == '') {echo $country;} ?>">
<input type="submit" name="submit">
</form>
</html>
Use value="<?php if (isset($firstname) && $success == '') {echo $firstname;} ?>"
You'll then have to create the $success variable--as I did in my example.
You can check this also
<form id="form1" method="post">
<label class="w">Plan :</label>
<select autofocus="" name="plan" required="required">
<option value="">Select One</option>
<option value="FREE Account">FREE Account</option>
<option value="Premium Account Monthly">Premium Account Monthly</option>
<option value="Premium Account Yearly">Premium Account Yearly</option>
</select>
<br>
<label class="w">First Name :</label><input name="firstname" type="text" placeholder="First Name" required="required" ><br>
<label class="w">Last Name :</label><input name="lastname" type="text" placeholder="Last Name" required="required" ><br>
<label class="w">E-mail ID :</label><input name="email" type="email" placeholder="Enter Email" required="required" ><br>
<label class="w">Password :</label><input name="password" type="password" placeholder="********" required="required"><br>
<label class="w">Re-Enter Password :</label><input name="confirmpassword" type="password" placeholder="********" required="required"><br>
<label class="w">Street Address 1 :</label><input name="strtadd1" type="text" placeholder="street address first" required="required"><br>
<label class="w">Street Address 2 :</label><input name="strtadd2" type="text" placeholder="street address second" ><br>
<label class="w">City :</label>
<input name="city" type="text" placeholder="City" required="required"><br>
<label class="w">Country :</label>
<select autofocus id="a1_txtBox1" name="country" required="required" placeholder="select one">
<option>Select One</option>
<option>UK</option>
<option>US</option>
</select>
<br>
<br>
<input type="reset" value="Submit" />
</form>
After submitting the post you can redirect using inline javascript like below:
echo '<script language="javascript">window.location.href=""</script>';
I use this code all the time to clear form data and reload the current form. The empty href reloads the current page in a reset mode.
You can also use unset function to do this e.g. below is my code where I verify an email existence.
if($mail->check($email)){
$status = 'succ';
$statusMsg = 'Given email <'.$email.'> exists!';
unset($_REQUEST["name"]);
unset($_REQUEST["email"]);
unset($_REQUEST["comment"]);
}elseif(verifyEmail::validate($email)){
$status = 'err';
$statusMsg = 'Given email <'.$email.'> is valid, but does not exist!';
}else{
$status = 'err';
$statusMsg = 'Given email <'.$email.'> is not valid, not exist!';
}
}else{
$status = 'err';
$statusMsg = 'Enter the email address that is to be verified';
}
This can be used after the mysql command of Insert a record in the table and that does it. It resets the values entered there in the fields.
It is possible to ask a browser not to follow the redirect headers, in this case a user can still refresh the page.
I think the best solution is to destroy all the data sent by the form, then attempt to redirect the user to another page.
<?php
// Destroys data _POST
foreach ($_POST as $key => $value) {
unset($_POST[$key]);
}
// redirect user
header("Location: other_page.html");
// terminate the current script
exit();
I have a simple form to submit testimonials, I also was having trouble clearing the form, what I did was after the query is submitted successfully I and before redirecting to another page I cleared the imputs $name =''; ect. The page submitted and redirected with no errors.
I am using a wamp server on my local machine , to host my codeigniter project.
Everything seems to work well , but the form validation wont display the errors when one occur.
The callback to check if email already exist doesnt also work , which is really weird because it was working last night.
this is my controller -
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Signup extends MX_Controller
{
function __construct() {
parent::__construct();
//calling helpers and library classes from ci
$this->load->helper(array('form', 'url'));
$this->load->helper('date');
$this->load->library('form_validation');
}
public function index() {
// loading the registration form
$this->load->view('register');
// form validation
$this->form_validation->set_rules('username', 'Username', 'required|min_length[3]|max_length[12]|is_unique[gamers.username]');
$this->form_validation->set_rules('email','Email','trim|required|valid_email|callback_isEmailExist');
$this->form_validation->set_rules('country', 'Country', 'required');
$this->form_validation->set_rules('region', 'Region', 'required');
$this->form_validation->set_rules('dob', 'Birth Date', 'required');
$this->form_validation->set_rules('phone', 'Mobile Number', 'required');
$this->form_validation->set_rules('passphrase', 'Password', 'trim|required|sha1');
$this->form_validation->set_rules('referral', 'Referred By');
if ($this->form_validation->run() !== FALSE)
{
//loading model
$this->load->model('signup_model');
// preparing form data
$username = $this->input->post('username');
$email = $this->input->post('email');
$country = $this->input->post('country');
$region = $this->input->post('region');
$dob = $this->input->post('dob');
$phone = $this->input->post('phone');
$password = $this->input->post('passphrase');
$referred = $this->input->post('referral');
//check current time stamp
$join_date = date('Y-m-d H:i:s');
//email verification hush key-generator
$token = md5(rand(0,1000).'cashout233');
// packaging form data for transport in an array
$data = array(
'username' => $username,
'email' => $email,
'country' => $country,
'region' => $region,
'birthdate' => $dob,
'phone_number' => $phone,
'password' => $password,
'join_date' => $join_date,
'referral' => $referred,
'token' => $token
);
// finally transporting data to the model
$taxi = $this->signup_model->register_gamer($data);
if ($taxi !== false) {
// send email verification link after sucessfull transport
// $from = 'noreply#talenthut.com';
// $to = $email;
// $subject = 'Email Confirmation Instructions';
// $message = '
// '.$first_name.', Thanks for signing up!
// Please click this link to activate your account:
// localhost/index.php/email_verification?email='.$email.'&hash='.$hash.'
// '; // Our message above including the link
// $this->email->from($from);
// $this->email->to($email);
// $this->email->subject($subject);
// $this->email->message($message);
// $this->email->send();
// Redirect user to Email Confirmation Page
redirect('index.php/signup/EmailConfirmation/'.urlencode($email));
}
}
}
public function isEmailExist($str) {
$this->load->model('signup_model');
$is_exist = $this->signup_model->isEmailExist($str);
if ($is_exist) {
$this->form_validation->set_message(
'isEmailExist', 'Email address is already in use.'
);
return false;
} else {
return true;
}
}
public function EmailConfirmation($to)
{
echo "email has been sent to ".urldecode($to);
// loading the email confirmation page
// $this->load->view('e_confirmation');
}
}
My view that displays the registration form is -
<?php echo form_open('index.php/signup'); ?>
<!-- fieldsets -->
<fieldset>
<div class="errors"> <?php echo validation_errors(); ?> </div>
<label>
<input id="username" type="text" name="username" value="" placeholder="Username" />
</label>
<label>
<input id="email" type="email" name="email" value="" placeholder="Email" />
</label>
<label>
<select name="country"><br/>
<option value="Ghana">Ghana</option>
</select>
</label>
<label>
<select name="region"><br/>
<option value="">Choose Region...</option>
<option value="Greater Accra">Greater Accra</option>
<option value="Central">Central</option>
<option value="Western">Western</option>
<option value="Eastern">Eastern</option>
<option value="Ashanti">Ashanti</option>
<option value="Brong Ahaful">Brong Ahaful</option>
<option value="Northen">Northen</option>
<option value="Volta">Volta</option>
<option value="Upper East">Upper East</option>
<option value="Upper West">Upper West</option>
</select>
</label>
<label>
<input id="dob" type="text" name="dob" value="" placeholder="Birth Date" />
</label>
<label>
<input id="phone" type="text" name="phone" value="" placeholder="Mobile Number" />
</label>
<label>
<input id="password" type="password" name="passphrase" value="" placeholder="Password" />
</label>
<label>
<select name="referral"><br/>
<option value="">how did you know about us</option>
<option value="Search Engine">Search engine</option>
<option value="Twitter">Twitter</option>
<option value="Word of Mouth">Word of mouth</option>
<option value="Newspaper">Newspaper</option>
</select>
</label>
<label>
<span> </span>
<p class="help">By clicking the sign up button below, you confirm that you are 18 years , and you agree to our
Terms and Conditions and Privacy Policy.</p><br/><br/>
<span> </span>
<button class="submit" type="submit">Sigm Up</button>
</label>
</fieldset>
</form>
model function for the isEmailExist controller function is
function isEmailExist($email) {
$this->db->select('id');
$this->db->where('email', $email);
$query = $this->db->get('gamer');
if ($query->num_rows() > 0) {
return true;
} else {
return false;
}
}
Thanks in advance.
worked it out!!!
I realised the validations doesnt work with redirections but only views.
I also called the login form too early before the validation. I placed it in the if condition and everything worked like a charm .
As for the "callback " . I just had to eliminate all that nonsense and replaced it with is_unique.
You can check email exist or Not as simply applying codeigniter inbuild rule:
is_unique[table_name.table_coloum]
$this->form_validation->set_rules('email', 'Email', 'required|trim|xss_clean|is_unique[users.email]');
I'm trying to do simple script with PHP and insert some data, but nothing happens! I knew that I missed something but what is it?
This my code:
<?php
$host= "localhost";
$user="root";
$pass="freedoom19";
$db="dddd";
$con = mysqli_connect($host,$user,$pass,$db) or mysql_error();
//====== Get Variable======= //
$name = $_POST['name'];
$email=$_POST['email'];
$rate=$_POST['select_style'];
$content=$_POST['content'];
$insert="insert into reviews (name,email,rate,content) values ('$name','$email','$rate','$content')";
//====== Get Variable======= //
if($_POST['submit-comment']) {
if($name && $email && $content == true) {
mysqli_query($con,$insert);
$success = "<span class='success_testmonial'>Thank You! .. Your Raiting Has Been Submitted And We Will Post It As Soon We Verify It !</span>";
}
else {
$error = "<span class='error_testmonial'>Error : one or some fields has left empty .. Please fill all field and try again.</span>";
}
}
mysqli_close($con);
?>
And this it the form and the "action" ..
<form method="post" action="" id="form-contact" class="clearfix">
<div id="form-left">
<label for="text-name">Name *</label><br />
<input type="text" name="name" class="input" id="text-name" /><br />
<label for="text-email">From *</label><br />
<input type="text" name="email" class="input" id="text-email" /><br />
<label for="text-phone">Rate us *</label><br />
<div class="select-style">
<select>
<option value="5.0">5.0</option>
<option value="4.5">4.5</option>
<option value="4.0">4.0</option>
<option value="3.5">3.5</option>
<option value="3.0">3.0</option>
<option value="2.5">2.5</option>
<option value="2.0">2.0</option>
<option value="2.0">2.0</option>
<option value="1.5">1.5</option>
<option value="1.0">1.0</option>
</select>
</div>
</div>
<div id="form-right">
<label for="text-comment">Review <span></span></label><br />
<textarea name="content" cols="10" rows="20" class="input textarea" id="text-comment"></textarea><br />
<input type="submit" name="submit-comment" class="button" value="Rate Us" />
</div>
<p id="text-contact">
<br><br><font color="#980303">Please Note *</font> Thate Your Reviews Will Not Published Untill We Check it and sure that the review don't contain Bad words or bad language, and be sure that we will publish all reviews and we accept criticism!
</form>
So what I missed please?
Check this working code. Also you had not set element name for Drop down as select_style. It was throwing error for that too.
PHP Code
if(isset($_POST['submit-comment']) && $_POST['submit-comment']!='') {
$host= "localhost";
$user="root";
$pass="";
$db="test";
$con = mysqli_connect($host,$user,$pass,$db) or mysql_error();
//====== Get Variable======= //
$name = mysqli_real_escape_string($con,$_POST['name']);
$email = mysqli_real_escape_string($con,$_POST['email']);
$rate = mysqli_real_escape_string($con,$_POST['select_style']);
$content = mysqli_real_escape_string($con,$_POST['content']);
$insert="insert into reviews (name,email,rate,content) values ('$name','$email','$rate','$content')";
if($name && $email && $content == true) {
mysqli_query($con,$insert);
$success = "<span class='success_testmonial'>Thank You! .. Your Raiting Has Been Submitted And We Will Post It As Soon We Verify It !</span>";
echo $success;
}
else {
$error = "<span class='error_testmonial'>Error : one or some fields has left empty .. Please fill all field and try again.</span>";
echo $error;
}
mysqli_close($con);
}
HTML
<form method="post" action="" id="form-contact" class="clearfix">
<div id="form-left">
<label for="text-name">Name *</label><br />
<input type="text" name="name" class="input" id="text-name" /><br />
<label for="text-email">From *</label><br />
<input type="text" name="email" class="input" id="text-email" /><br />
<label for="text-phone">Rate us *</label><br />
<div class="select-style">
<select name="select_style">
<option value="5.0">5.0</option>
<option value="4.5">4.5</option>
<option value="4.0">4.0</option>
<option value="3.5">3.5</option>
<option value="3.0">3.0</option>
<option value="2.5">2.5</option>
<option value="2.0">2.0</option>
<option value="2.0">2.0</option>
<option value="1.5">1.5</option>
<option value="1.0">1.0</option>
</select>
</div>
</div>
<div id="form-right">
<label for="text-comment">Review <span></span></label><br />
<textarea name="content" cols="10" rows="20" class="input textarea" id="text-comment"></textarea><br />
<input type="submit" name="submit-comment" class="button" value="Rate Us" />
</div>
<p id="text-contact">
<br><br><font color="#980303">Please Note *</font> Thate Your Reviews Will Not Published Untill We Check it and sure that the review don't contain Bad words or bad language, and be sure that we will publish all reviews and we accept criticism!
</form>
try to put your get variables inside the if else statement
check if there are datas in POST when done submitting:
if($_POST['submit-comment']) {
$name = $_POST['name'];
$email=$_POST['email'];
$rate=$_POST['select_style'];
$content=$_POST['content'];
$insert="insert into reviews (name,email,rate,content) values ('$name','$email','$rate','$content')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
var_dump($_POST);
}
$con->close();
check for errors:
$check = mysqli_query($con,$insert);
var_dump($check);
if you found one, let me know
Note:
Put your insert query and passed on variables (POST) inside your if statement isset(POST["submit-comment"] to eliminate errors of undefined variables.
You should use mysqli_* prepared statement instead to prevent SQL injections.
Answer:
If you insist on retaining your code, you can use mysqli_real_escape_string() function to fertilize a bit the content of your variables before using it in your query.
Your PHP file should look like this:
<?php
$host= "localhost";
$user="root";
$pass="freedoom19";
$db="cookindoor";
$con = mysqli_connect($host,$user,$pass,$db) or mysql_error();
//====== IF SUBMIT-COMMENT ======= //
if(isset($_POST['submit-comment'])) {
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["content"])) {
//====== GET VARIABLES ======= //
$name = mysqli_real_escape_string($con,$_POST['name']);
$email = mysqli_real_escape_string($con,$_POST['email']);
$rate = mysqli_real_escape_string($con,$_POST['select_style']);
$content = mysqli_real_escape_string($con,$_POST['content']);
$insert="INSERT INTO reviews (name,email,rate,content) VALUES ('$name','$email','$rate','$content')";
mysqli_query($con,$insert);
$success = "<span class='success_testmonial'>Thank You! .. Your Raiting Has Been Submitted And We Will Post It As Soon We Verify It !</span>";
}
else {
$error = "<span class='error_testmonial'>Error : one or some fields has left empty .. Please fill all field and try again.</span>";
}
}
mysqli_close($con);
?>
Recommendation:
But if you execute it in mysqli_* prepared statement, your insert query would look like this. Though this is just a simple example but still executable:
if($stmt = $con->prepare("INSERT INTO reviews (name, email, rate, content) VALUES (?,?,?,?)")){ /* CHECK THE QUERY */
$stmt->bind_param('ssss', $_POST["name"], $_POST["email"], $_POST["rate"], $_POST["content"]); /* BIND VARIABLES TO YOUR QUERY */
$stmt->execute(); /* EXECUTE YOUR QUERY */
$stmt->close(); /* CLOSE YOUR QUERY */
}
I am new to CI and have been reading documentation and following a form tutorial. However I'm struggling to get my form written to my database. Actually, the data is being written, but I'm getting the error...
A PHP Error was encountered
Severity: Notice
Message: Use of undefined constant firstname - assumed 'firstname'
Filename: controllers/form.php
Line Number: 25
I also ge the error for the second field I'm writing lastname. I think I'm close enough that MySQL is figuring out what I'm trying to do, but I'm still missing something.
My Form/View...
<html>
<head>
<title>Pledge Details</title>
</head>
<body>
<?php echo validation_errors(); ?>
<?php echo form_open('form'); ?>
<h5>First Name</h5>
<input type="text" name="firstname" value="<?php echo set_value('firstname'); ?>" size="50" />
<h5>Last Name</h5>
<input type="text" name="lastname" value="<?php echo set_value('lastname'); ?>" size="50" />
<h5>Email Address</h5>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />
<h5>Kms/Miles</h5>
<select name="myselect">
<option value="Kms" <?php echo set_select('myselect', 'Kms', TRUE); ?> >Kms</option>
<option value="Miles" <?php echo set_select('myselect', 'Miles'); ?> >Miles</option>
</select>
<h5>Pledge</h5>
<input type="text" name="pledge" value="<?php echo set_value('pledge'); ?>" size="50" />
<br><br>
<div><input type="submit" value="Submit" /></div>
</form>
<?php echo form_close() ?>
</body>
</html>
My controller...
<?php
class Form extends CI_Controller {
function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('firstname', 'First Name', 'trim|required|max_length[12]|xss_clean');
$this->form_validation->set_rules('lastname', 'Last Name', 'trim|required|max_length[12]|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('pledge', 'Pledge', 'trim|required|max_length[12]|decimal|xss_clean');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->database();
$sql = "INSERT INTO donations (firstname, lastname)
VALUES (".$this->db->escape($_POST[firstname]).", ".$this->db->escape($_POST[lastname]).")";
$this->db->query($sql);
echo $this->db->affected_rows();
$this->load->view('formsuccess');
}
}
}
?>
Your error is coming from the following line
$sql = "INSERT INTO donations (firstname, lastname) VALUES (".$this->db->escape($_POST[firstname]).", ".$this->db->escape($_POST[lastname]).")";
You forgot to enclose your $_POST variables in quotes. Notice how $_POST[firstname] has become $_POST['firstname']. It should be
$sql = "INSERT INTO donations (firstname, lastname) VALUES (".$this->db->escape($_POST['firstname']).", ".$this->db->escape($_POST['lastname']).")";
Also like others have said rather than doing $_POST['firstname'] you can do $this->input->post('firstname');
Try this:
$firstname = $this->input->post('firstname');
$lastname = $this->input->post('lastname');
$this->load->database();
$this->db->insert('mytable', array('firstname'=>$firstname , 'lastname'=>$lastname));
echo $this->db->affected_rows();
$this->load->view('formsuccess');
It's better to use active record and also try putting the mysql process in your model and not in the controller because codeigniter is designed for that MVC
I have a form that is not outputting any error messages have I missed something?
Model:
function createUser($username = NULL ,$passwordHash = NULL ,$firstname = NULL ,$lastname = NULL ,$email = NULL,$group = NULL ,$active = NULL)
{
$data = array('userName' => $username, 'userFirstName' => $firstname, 'userLastName' => $lastname, 'userEmail' => $email, 'userPassword' => sha1($passwordHash), 'userGroup' => $group, 'userActive' => $active);
$this->db->insert('users',$data);
return TRUE;
}
View:
<h1><?php echo $companyName; echo nbs(1);?> - <?php echo $pageTitle; ?></h1>
<?php
if($success == TRUE) {
echo '<section id = "validation">Page Updated</section>';
}
?>
<p>Error: <?php echo validation_errors();?> </p>
<div class="formContent">
<form action="createUser" method="post">
<fieldset class="control-group">
<label for="userName">User Name: <input type="text" name="userName" value="<?php echo set_value('userName'); ?>" placeholder="User Name"></label>
<label for="userPassword">User Password: <input type="password" name="userPassword" value="<?php echo set_value('userPassword'); ?>" placeholder="User Password"></label>
<label for="userFirstName">First Name: <input type="text" name="userFirstName" value="<?php echo set_value('userFirstName'); ?>" placeholder="First Name"></label>
<label for="userLastName">Last Name: <input type="text" name="userLastName" value="<?php echo set_value('userLastName'); ?>" placeholder="Last Name"></label>
<label for="userEmail">E-Mail: <input type="text" name="userEmail" value="<?php echo set_value('userEmail'); ?>" placeholder="Admin E-mail"></label>
<label for="userGroup"> User Group:
<select name="userGroup" value="<?php echo set_value('userGroup'); ?>">
<option value="select">Please Select</option>
<option value="admin">Admin Group</option>
<option value="user">User Group</option>
</select>
</label>
<label for="userActive"> User Active:
<select name="userActive" value="<?php echo set_value('userActive'); ?>">
<option value="select">Please Select</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</label>
<button type="submit" class="btn-primary">Create</button>
</fieldset>
</form>
</div>
Controller:
public function index()
{
$data['companyName'] = $this->core_model->companyName();
$data['success'] ="";
$data['pageTitle'] = "Create User";
$this->load->view('admin/assets/header', $data);
$this->load->view('admin/createUser', $data);
$this->load->view('admin/assets/footer');
if($this->input->post('submit'))
{
$this->form_validation->set_rules('userName', 'User Name', 'trim|required|xss_clean|callback_username_check');
$this->form_validation->set_rules('userPassword', 'User Password', 'trim|required|xss_clean|sha1');
$this->form_validation->set_rules('userFirstName', 'First Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('userLastName', 'Last Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('userEmail', 'E-Mail', 'trim|required|xss_clean');
$this->form_validation->set_rules('userGroup', 'User Group', 'trim|required|xss_clean');
$this->form_validation->set_rules('userActive', 'User Active', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$data['companyName'] = $this->core_model->companyName();
$data['success'] ="";
$data['pageTitle'] = "Create User";
$this->load->view('admin/assets/header', $data);
$this->load->view('admin/createUser', $data);
$this->load->view('admin/assets/footer');
}else{
$username = $this->input->post('userName',TRUE);
$password = $this->input->post('userPassword', TRUE);
$firstname = $this->input->post('userFirstName', TRUE);
$lastname = $this->input->post('userLastName',TRUE);
$email = $this->input->post('userEmail',TRUE);
$group = $this->input->post('userGroup',TRUE);
$active = $this->input->post('userActive', TRUE);
$this->db->escape($username);
$this->db->escape($password);
$this->db->escape($firstname);
$this->db->escape($lastname);
$this->db->escape($email);
$this->db->escape($group);
$this->db->escape($active);
$passwordHash = $this->encrypt->sha1($password);
if ($this->core_model->createUser($username,$passwordHash,$firstname,$lastname,$email,$group,$active))
{
$data['success'] = TRUE;
$data['companyName'] = $this->core_model->companyName();
$data['pageTitle'] = "Create User";
$this->load->view('admin/assets/header', $data);
$this->load->view('admin/createUser', $data);
$this->load->view('admin/assets/footer');
}else{
$data['companyName'] = $this->core_model->companyName();
$data['pageTitle'] = "Create User";
$this->load->view('admin/assets/header', $data);
$this->load->view('admin/createUser', $data);
$this->load->view('admin/assets/footer');
}
}
}
}
function __username_check($userName){
{
if ($userName == $user->$userName) {
$this->form_validation->set_message('username_check','Sorry the chosen username %s is taken!');
return false;
}else{
return true;
}
}
}
}
/* End of file login.php */
/* Location: ./application/controllers/admin/createUser.php */
You need to place the <input>s outside the <label> </label> tags! This is the main issue.
Also:
there's no input named "submit": your submit button, in fact, has no name attribute. And, btw, since you're already using form_validation class, that check (if input->post('submit')) is redundant;
Another redundant thing I see is passing TRUE (i.e., having it xss_cleaned) to the input->post method: you already have plenty of xss_clean validation rules, so why passing it again in that expensive extra processing, when already passed through it during validation check?
Sidenote, if you're using Active Record, or query bindings, you don't have to escape variables, so I'd remove that part too :)
And I believe your call to __username_check() will fail: the function, as for what concern the "callback_" validation rule, is "username_check"; and besides the double underscore is usually used for "magic methods" in PHP; you can safely remove both, or if you really want an underscore on the function name (just one) you might want to call "callback__check_username".
And you're loading the same views three times, why? I believe you can rewrite the whole index method like this:
function index()
{
$this->form_validation->set_rules('userName', 'User Name', 'trim|required|xss_clean|callback_username_check');
$this->form_validation->set_rules('userPassword', 'User Password', 'trim|required|xss_clean|sha1');
$this->form_validation->set_rules('userFirstName', 'First Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('userLastName', 'Last Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('userEmail', 'E-Mail', 'trim|required|xss_clean');
$this->form_validation->set_rules('userGroup', 'User Group', 'trim|required|xss_clean');
$this->form_validation->set_rules('userActive', 'User Active', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$data['success'] ="";
}else{
$username = $this->input->post('userName');
$password = $this->input->post('userPassword');
$firstname = $this->input->post('userFirstName');
$lastname = $this->input->post('userLastName');
$email = $this->input->post('userEmail');
$group = $this->input->post('userGroup');
$active = $this->input->post('userActive');
$passwordHash = $this->encrypt->sha1($password);
if ($this->core_model->createUser($username,$passwordHash,$firstname,$lastname,$email,$group,$active))
{
$data['success'] = TRUE;
}
}
$data['companyName'] = $this->core_model->companyName();
$data['pageTitle'] = "Create User";
$this->load->view('admin/assets/header', $data);
$this->load->view('admin/createUser', $data);
$this->load->view('admin/assets/footer');
}
UPDATE:
as for the username check, since v.2.0 of CodeIgniter you have that ability featured among the validation rules: if you place the is_unique rule, in fact, it will automatically query the database to check for that. The syntax is:
is_unique[table.field]
In your case, might be
$this->form_validation->set_rules('userName', 'User Name', 'trim|required|is_unique[users.userName]|xss_clean');