loading a view twice in codeigniter - php

Hello I just started CodeIgniter. I am having problem in loading view.
My scenrio is I am creating a sample add form. After submit it goes to controller and insert entries in database. I want if the database operation is successfull it again comes to same view having again some values. And on the basis of those values I am showing some particular rows informing user about insertion operation. My function in controller looks like
public function add_user()
{
$this->load->view('add_user');
$post=$this->input->post();
if(isset($post['name']))
{
$data=array(
'name'=>$post['name'],
'designation'=>$post['designation']
);
if($this->db->insert('user',$data))
$result['update']=true;
else
$result['update']=false;
$this->load->view('add_user',$result);
}
}
And my view looks like
<h1 align="center">Add User</h1>
<table border="0" cellpadding="2" cellspacing="2" align="center">
<?php
if(isset($update))
{
if($update)
{
?>
<tr bgcolor="#00FF00">
<td>Record Added Successfully</td>
</tr>
<?php
}
else
{
?>
<tr bgcolor="#FF0000">
<td>Insertion Operation Failed</td>
</tr>
<?php
}
}
?>
<?php echo(form_open('first/add_user'));?>
<tr>
<td>Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td>Designation</td>
<td>
<select name="designation">
<option value="Junior PHP Developer">Junior PHP Developer</option>
<option value="Senior PHP Developer">Senior PHP Developer</option>
</select>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="submit" value="Add User" />
</td>
</tr>
</form>
</table>
Now What I want that if insertion operation is successfull I am sending true value to view and if not I am sending false value. And on the basis of this value I am showing some rows. I am loading the view two times as per I understood the logic. Because first time it loads the form and second time It loads view with some value of true or false. But what happens that after it reloads there are two forms. I know this problem is due to double loading of my view. i want to ask if there is another way of sending values after database operation to view?

Simply load your view once:
public function add_user()
{
$post=$this->input->post();
$result = array();
if(isset($post['name']))
{
$data=array(
'name'=>$post['name'],
'designation'=>$post['designation']
);
if($this->db->insert('user',$data))
$result['update']=true;
else
$result['update']=false;
}
$this->load->view('add_user',$result);
}
By the way your code is a bit messy, work on it

// try something like this
//you may need to use form validation helper
//load add user form
public function add_user(){
//any data required for the form
$data['anything'] = '';
$this->load->view('add_user',$data);
}
//to process adding user action, form action will point to this
function adding_user(){
if($this->input->post('name')){
$data=array(
'name'=>$post['name'],
'designation'=>$post['designation'];
if($this->db->insert('user',$data)){
echo 'user added successfully!';
}else{
redirect(user/add_user);
}
);
}
}

Related

How to stop uniqid() from regenerating in a PHP form

I want to generate a random key for the user to use during registration. The code compares the generated key with the user input but the key gets regenerated when the user submits the form, so they are never the same. I tried to protect the generator function by checking if it was already generated but it didn't work. Then, I tried to use session as well, which didn't work either. Here's the code which always produces "fail" rather than "success":
Edit: I made some corrections according to your comments.
<?php
session_start();
$_SESSION['key'] = randomKey();
$key1 = $_SESSION['key'];
error_reporting(E_ALL);
ini_set('display_errors', 1);
function randomKey() {
if (empty($_SESSION['key'])) {
$key = uniqid();
$_SESSION['key'] = $key;
return $key;
} else {
return $_SESSION['key'];
}
}
if(isset($_POST['submit']))
{
$input = $_POST['inputKey'];
if (strcmp($input,$_SESSION['key']) == 0) {
echo 'success';
} else {
echo 'fail';
}
}
?>
<html>
<head>
</head>
<body>
<form method="POST" action="">
<table border="0">
<tr>
<td>Your key:</td>
<td>
<b>
<?php echo $key1; ?></b>
</td>
</tr>
<tr>
<td>Enter your key:</td><td><input type="text" name="inputKey"></td>
</tr>
<tr>
<td><input id="button" type="submit" name="submit" value="Sign-Up"></td>
</tr>
</table>
</form>
</body>
</html>
You stated in comments that there was now a headers sent warning.
The following link will help you figure out why that is.
Warning: Cannot modify header information - headers already sent by ERROR
However, I did find a slight bug in your code.
Even upon success, your code will produce the same key when the page is reloaded; where "randomness" would literally be "thrown out the window", since that is what the whole purpose is with your usage of the unique function.
You need to destroy the session on success.
Here is what your code should look like and using session_destroy():
if(isset($_POST['submit']))
{
$input = $_POST['inputKey'];
if (strcmp($input,$_SESSION['key']) == 0) {
echo 'success';
session_destroy();
} else {
echo 'fail';
}
}
Reference:
http://php.net/manual/en/function.session-destroy.php
Once you've corrected the problem with the headers being sent, consider redirecting somewhere (or the same page for that matter), after succession.
You can do this with a header, but you cannot echo and use a header at the same time, so remember that.
Reference:
http://php.net/manual/en/function.header.php
and be sure to add an exit; after the header (as stated in the manual), otherwise your code may want to continue to execute and if you have more code below it.
Sorry, for the delay. I think I've found a workaround. I just posted the form to another page which grabs and controls the information. That way, the random code isn't regenerated. So, I have two pages instead of one.
test1.php:
<?php
$key = randomKey();
function randomKey() {
$i = 0;
do {
$key = uniqid();
return $key;
} while ($i > 0);
}
?>
<html>
<head>
</head>
<body>
<form method="POST" action="randomkey2.php">
<table border="0">
<tr>
<td>Your key:</td>
<td>
<b>
<?php echo $key?></b><input type="hidden" name="keyHidden" value="<?php echo $key;?>" />
</td>
</tr>
<tr>
<td>Enter your key:</td><td><input type="text" name="inputKey"></td>
</tr>
<tr>
<td><input id="button" type="submit" name="submit" value="Sign-Up"></td>
</tr>
</table>
</form>
</body>
</html>
test2.php:
<?php
$input = $_POST['inputKey'];
$key = $_POST['keyHidden'];
$control = strpos($key, $input);
if($control !== false)
{
echo 'success';
} else {
echo 'fail';
}
?>
This way, I also don't have to use session globals. Well, this may look a bit odd but the process is normally a bit more complicated and it requires to give some instructions. So, subdividing the process isn't a problem for me and it works. I'm sorry if I've wasted your time, I've just started to fiddle with PHP. Thank you for your corrections and suggestions.

controller not displaying a message in phalcon php

I’m trying to make a simple example in Phalcon PHP framework, so i have a view which contain two fields name and email and a submit button. When i click in this button a function of a controller is called to store the name and the email in the DB. This action goes well the problem is I’m trying to display a message after the action ends but i still have the view that contain the form (name, email). Here's my code.
My checkout controller.
<?php
class CheckoutController extends \Phalcon\Mvc\Controller
{
public function indexAction()
{
}
public function registerAction()
{
$email = new Emails();
//Stocker l'email et vérifier les erreurs
$success = $email->save($this->request->getPost(), array('name', 'email'));
if ($success) {
echo "Thanks for shopping with us!";
} else {
echo "Sorry:";
foreach ($user->getMessages() as $message) {
echo $message->getMessage(), "<br/>";
}
}
}
}
The view
<!DOCTYPE html>
<html>
<head>
<title>Yuzu Test</title>
</head>
<body>
<?php use Phalcon\Tag; ?>
<h2>Checkout</h2>
<?php echo Tag::form("checkout/register"); ?>
<td>
<tr>
<label for="name">Name: </label>
<?php echo Tag::textField("name") ?>
</tr>
</td>
<td>
<tr>
<label for="name">E-Mail: </label>
<?php echo Tag::textField("email") ?>
</tr>
</td>
<td>
<tr>
<?php echo Tag::submitButton("Checkout") ?>
</tr>
</td>
</form>
</body>
</html>
You can use Flash Messages, so you don't have to break the application flow.
Regards
echo() during controller code won't (shouldn't) work unless you turn off your views, because its buffered and cleared after dispatching.
If you want to be sure it's happening this way, just add die() at the end of registerAction() method.
If you create separate view for registerAction(), you can use there variables you declare with $this->view->message = ... or $this->view->setVar('message', ...) in controller method. Than, in view file you can reuse them by <?php echo $this->view->message; ?> or <? echo $message; ?>.
I think you have to write following line in the end of your controller function registerAction
$this->view->disable();

how to save featured data into featured table from product table in codeigniter

I hope you are doing well. I am new in codeigniter :::
I have two tables in database 1. tbl_product 2. tbl_featured_products. I get data from tbl_product in a form with foreach loop in checkbox system. After that I need to save product data into tbl_featured_products. I can not save it (multiple data in row ).... please help me out ..
My Question::
1. how can I save data into tbl_featured_products ?
2. how can I show image and others info and save data from view page ?
Controller:::
$data=array();
$data['featured_id']=$this->input->post('featured_id',true);
$data['product_id']=$this->input->post('product_id',true);
$data['product_name']=$this->input->post('product_name',true);
$data['product_price']=$this->input->post('product_price',true);
$data['product_image']=$this->input->post('product_image',true);
$this->sa_model->save_featured_product_info($data);
}
Model :::::
public function save_featured_product_info($data)
{
$this->db->insert('tbl_featured_products',$data);
}
view::::
<tr>
<td width="130">Product Name: </td>
<td>
<?php foreach($all_product as $values) { ?>
<input type="checkbox" name="product_name" value="<?php echo $values->product_name;?>"> <?php echo $values->product_name;?> <br>
<?php } ?>
</td>
</tr>
I would try the following:
first load data to your view
Controller:
function dataToView(){
$data = $this->sa_model->tbl_product_info($data); //gets information from your model db
$this->load->view('templates/home', $data); //sends data to the view
}
View:
<tr>
<td width="130">Product Name: </td>
<td>
<form id="product_form">
<?php foreach($all_product as $values) { ?>
<input type="checkbox" name="product_name" value="<?php echo $values->product_name;?>"> <?php echo $values->product_name;?> <br>
<?php } ?>
<input type="submit" />
</form>
</td>
</tr>
Javascript
<script>
$(document).ready(function(){
$('#product_form').submit(function(){
var url = 'controller/save';
$.post(url, function(result){
if (result){
//...your success function..
}
});
return false;
});
});
</script>
Controller
<?php
function save(){
$product = $this->input->post('product_name');//this will get your posted product into the controller
//...add your own function
if (works){
echo true;
}else{
echo false;
}
}
?>

Submit button is not working after using javascript

I created a login page that has a login form which submits username and password to loginproc.php in order to check their validity and everything was working perfectly. Anyway, on the login page I wrote a JavaScript function that alert the user in case the username and password fields are empty. After I've done that, the JavaScript works fine but when i click the submit button nothing happens absolutely!
----------------------------------------This is the JavaScript----------------------
<script type='text/javascript'>
function formValidator(){
// Make quick references to our fields
var username = document.getElementById('username');
var password = document.getElementById('password');
// Check each input in the order that it appears in the form!
if(notEmpty(username, "The username field is empty!")){
if(notEmpty(password, "The password is empty!")){
}
}
return false;
}
function notEmpty(elem, helperMsg){
if(elem.value.length == 0){
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}
return true;
}
</script>
----------------------------------------This is the form----------------------
<form method="post" action="loginproc.php" onsubmit="return formValidator()" >
<tr><td colspan="3"><img src="icons/login.jpg" alt="Edugate" width="366" height="123"></td></tr>
<tr><td colspan="3" nowrap bgcolor="#990033" class="infoTitle"><div align="center"></div></td></tr>
<tr><td colspan="3" nowrap class="infoTitle"><div align="left">user login </div></td></tr>
<tr><td colspan="3" nowrap bgcolor="#990033" class="infoTitle"><div align="center"></div></td></tr>
<tr><td width="58">Username</td>
<td width="4">:</td>
<td width="297"><input type="text" id="username" name="username" size="20"></td></tr>
<tr><td>Password</td><td>:</td><td><input type="password" id="password" name="password" size="20"></td></tr>
<tr><td> </td><td> </td><td><input type="submit" class="BtnInTable" value="Login"></td></tr>
<?php if ($error == 1)
print "<tr><td colspan='3' class='ppos'><img src='icons/error.png' alt='error'> Icorrect usename or password...</td></tr>";?>
<tr><td colspan="3" nowrap bgcolor="#990033" class="infoTitle"><div align="center"></div></td></tr>
</form>
Kindly, can anybody guide me. Thanks in advace
You forgot return true;, it will go to return false; otherwise.
// Check each input in the order that it appears in the form!
if(notEmpty(username, "The username field is empty!")){
if(notEmpty(password, "The password is empty!")){
return true;
}
}
You formValidator() always returns false, and if you return false to the onsubmit, it will not submit.
Be sure to return true if everything is valid.
heres the problem..
this function only returns FALSE.
no return true statement..
for form to submit, the "onsubmit" should return true :)

Switching controllers and sending data in codeigniter

I have to devellop an internal web based application with codeigniter and I need to chain different forms (generate upon data choosen with previous form).
Right now, I tried to use form validation in the same method of the controller but the chaining only validate the first form, I tried also with $_SESSION variables but I have to send a large amount of data between each form. I tried with class variable (in controllers and models) but every time the form is send the variable are initialise...
So i wonder if there is a way to switch from a method to another one in my controller giving the data to the new controller.
my first form:
<p>Filtres: </p>
<br/><br/>
<form action="" method="post" id="form_ajout_manip" >
<label for="thematique[]">Thématique</label><br/>
<select name="thematique[]" size="20" multiple>
<?php
foreach($list_thema->result() as $thema)
{
echo "<option value='".$thema->THEMATIQUE_ID."'>".$thema->PARENT_THEMATIQUE_ID." - ".
$thema->NOM."</option>";
}
?>
</select>
<input type="hidden" value="true"/>
<br/>
<br/>
<br/>
<input type="submit" value="Rechercher" />
</form>
my second form:
<form action="" method="post" id="form_ajout_manip_cdt">
<label for="nom_manip" >Nom manipulation: </label>
<br/>
<input type="text" name="nom_manip"/>
<TABLE border="1">
<CAPTION><?php echo $data->num_rows.' '; ?>resuuultat</CAPTION>
<TR>
<?php
foreach($data->list_fields() as $titre)
{
echo '<TH>'.$titre.'</TH>';
}
?>
</TR>
<?php
foreach($data->result() as $ligne)
{
echo '<TR>';
foreach($ligne as $case)
{
echo '<TD>'.$case.'</TD>';
}
echo '<TD><input type="checkbox" name="cdt[]" value="'.$ligne->ID_CANDIDAT.'"
checked="true"</TD>';
echo '</TR>';
}
?>
</TABLE>
<br/><br/>
<input type="submit" value="créer"/>
</form>
Those are the two method of my controller
public function choix()
{
//controller for the second form
$this->info_page['title']='Ajout manipulation';
$this->load->view('ui_items/header',$this->info_page);
$this->load->view('ui_items/top_menu');
$this->load->view("manipulation/choix",$data);
}
public function filtre()
{
//controller for the first form
$this->form_validation->set_rules('thematique[]','Thematique','');
if($this->form_validation->run())
{
$data['data']=$this->manipulation_mod->select_par_filtre($this->input->post('thematique'));
//need to send $data to the second method "choix()"
}
else
{
$this->info_page['title']='Filtre ajout manipulation';
$this->load->view('ui_items/header',$this->info_page);
$this->load->view('ui_items/top_menu');
$data= array();
$data['list_op']= $this->candidat_mod->list_operateur();
$data['list_thema']= $this->thematique_mod->list_all_thematique();
$data['list_gene']= $this->candidat_mod->list_gene();
$this->load->view('manipulation/filtre', $data);
}
}
Have you any idea? I totally stuck...
Based on your clarification, let me give you an outline on what will work
View
Have both the forms in the same page
<? if(!$filtered): ?>
<input type="hidden" name="filtered" value="true"/>
/* Form 1 content here */
<? else: ?>
<input type="hidden" name="filtered" value="true"/>
/* Form 2 content here */
<? endif; ?>
Controller
You just need to use one controller
public function filter() {
$filtered = $this->input->post('filtered');
$data['filtered'] = $filtered;
if(empty($filtered)) {
/* Form validation rules for Form 1 */
/* Run form validation etc. */
/* Set title etc. for Form 1 */
} else {
/* Form validation rules for Form 2 */
/* Run form validation etc. */
/* Set title etc. for Form 2 */
}
/* Load view */
}
There might just be a better way to do this, but I am sure this will work. Good luck!

Categories