Form on Page:
<div>
<?php echo form_open('add/player');
echo form_label('First Name','playerFirstName');
echo form_input('playerFirstName','test');
echo "<br />";
echo form_label('Last Name','playerLastName');
echo form_input('playerLastName','test');
echo "<br />";
echo form_submit('addPlayer','Add Player');
echo form_close(); ?>
</div>
Called Controller:
class Add extends CI_Controller
{
public function index()
{
$this->load->view('header');
$this->load->view('add');
$this->load->view('footer');
}
public function Player()
{
if(strtoupper($_SERVER['REQUEST_METHOD']) == 'POST')
{
if(basename($_SERVER['HTTP_REFERER']) == basename($_SERVER['PHP_SELF']))
{
$this->load->model('players');
$returnMessage = $this->players->add_player($this->input->post('playerFirstName'), $this->input-post('playerLastName'));
}
}
$this->load->view('header');
$this->load->view('addplayer');
$this->load->view('footer');
}
}
I'm a very green novice when it comes to PHP, CodeIgniter and MySQL (or web coding in general), so if you see any suggestions, please don't hesitate to make them (though the credit will be given to the one who answers my question, not makes my code work the best). However, as to my question, is there a way to see if a string is within another string? My $returnMessage, if successful will have the word successfully in it. What I want to do is if the player is not added, I want to reload the values from the form and put them back. Here's where it gets tricky.
The names are saved in table people_names. In the players table, I save the nameid that is associated with that name in the people_names table. In my add_player function, I check to see if the names are in the table, if they aren't I add them, then I add the player to the players table with the appropriate ids. Because of this, I'm not sure form_validation would be able to be used or not. If it were, please let me know.
So what I want to do is check the $returnMessage and if it doesn't contain successfully, then I want to add the values back to the fields. However, I'm not finding a function where I can see if a string is inside of another string. I see string compares and substring functions, but no string contains. Any ideas? Thanks.
Use native PHP's strpos: http://php.net/manual/en/function.strpos.php
Cheers
http://php.net/manual/en/function.strpos.php
if (strpos($returnMessage,'successfully') !== false) {
echo 'true';
}
Related
I just started using Code Igniter framework and also just started learning on PHP OOP. I came across something when coding for the forms.
In a form if I have two buttons that would lead to different pages, what would be the most suitable way to do it? I found two ways. The first is to have a dynamic action/link, let's call it method A:
Method A
Variable $form_link is 'form_link'.
(View) main_user_view.php
<?php echo form_open($form_link); ?>
<?php echo form_button($add_user_button); ?>
<?php echo form_button($delete_user_button); ?>
<?php echo form_close(); ?>
(Controller) User.php
public function form_link()
{
// Value of button clicked
$form_submitted = $this->input->post('submit_form');
if($form_submitted == 'add_user')
{
redirect('User/add_user');
}
elseif($form_submitted == 'delete_user')
{
redirect('User/delete_user');
}
elseif($form_submitted == 'back')
{
redirect('User');
}
}
And the other way is instead of having a second button I would use an anchor and make an absolute path for it.
Method B
Variable $form_link is 'add_user' which is a function in the controller.
(View) main_user_view.php
<?php echo form_open($form_link); ?>
<?php echo form_button($add_user_button); ?>
<?php echo anchor('add_delete_user/delete_users_view', 'Delete', array('class'=>'btn btn-info', 'role'=>'button'));?>
<?php echo form_close(); ?>
The only problem I have with method A is that if in the form I have input fields, I cannot get the data through POST as redirect does not carry over the data to other functions. I resolved that by using method B where the anchor would lead to the function I want whereby I can get the POST data.
So my main question is, should I use method B instead whenever I have two or more buttons in a form?
You have to use button names for form post actions,
public function form_link()
{
if($this->input->post('add_user'))
{
redirect('User/add_user');
}
if($this->input->post('delete_user'))
{
redirect('User/delete_user');
}
}
What my opinion is also to use the Method B. To make the URL more nicer you can use custom routing (which is located at 'application/config/routes.php')
I am making a website in CodeIgniter and for one of these pages I need to insert information into a database, however every time I enter information into my form and submit it, the page refreshes like it had been submitted but nothing enters the database.
Controller:
public function insertjob()
{
$this->load->helper('form');
$data['title']="Add a new job";
$this->load->view("insertjob", $data);
}
public function addingjob()
{
$jobtype=$this->input->post('jobtype');
$jobinfo=$this->input->post('jobinfo');
$this->load->model("cmodel");
if($this->cmodel->addjob($jobtype, $jobinfo)){
$data['msg']="New job addition successful";
}else{
$data['msg']="There was an error please try again";
}
$this->load->view("confirmation",$data);
Model:
function addjob($jobtype,$jobinfo)
{
$newjob=array("jobtype"=>$jobtype,"jobinfo"=>$jobinfo);
return $this->db->insert('clientjobs', $newjob); exit;
View:
</p>
<?php
echo form_open('client/insertjob');
echo form_label('Job:', 'Job');
echo form_input('jobtype');
echo form_label('Job information:', 'Job information');
echo form_input('jobinfo');
echo form_submit('Add job', 'Submit Post!');
echo form_close();
?>
Try removing the exit from your model:
function addjob($jobtype,$jobinfo)
{
$newjob=array("jobtype"=>$jobtype,"jobinfo"=>$jobinfo);
return $this->db->insert('clientjobs', $newjob);
}
It's not neccessary and could be breaking the database class, as well as halting any execution for the application.
Here's your problem:
echo form_open('client/insertjob');
If you look at your HTML code in your browser, you'll see something like this:
<form action="client/insertjob">
There will probably be a whole bunch of other attributes in your form tag - they're not important for this answer.
That action attribute is telling the browser where to go after you click submit. Where is it going? Back to the insertjob method. But it needs to go to your addingjob method - that's where the database update is actually being done. So change the form_open call to:
echo form_open('client/addingjob');
As I see your are using 2 controller functions for posting, page 1 to page 2. You have error on form open you should post your data to addingjob not insertjob.
echo form_open('client/addingjob');
will fix your issue but I highly recommend you to use, one controller for form submit. Below code will send post to same url. And you could add some attributes on it.
<?php
$attributes = array('class' => 'form-horizontal');
echo form_open($this->uri->uri_string(),$attributes); ?>
Is it possible to create an HREF link that calls a PHP function and passes a variable along with it?
<?php
function sample(){
foreach ($json_output->object ){
$name = "{$object->title}";
$id = "{$object->id}";
print "<a href='search($id)' >$name</a>";
}
}
function search($id){
//run a search via the id provide by the clicking of that particular name link
}
?>
You can do this easily without using a framework. By default, anything that comes after a ? in a URL is a GET variable.
So for example, www.google.com/search.html?term=blah
Would go to www.google.com/search.html, and would pass the GET variable "term" with the value "blah".
Multiple variables can be separated with a &
So for example, www.google.com/search.html?term=blah&term2=cool
The GET method is independent of PHP, and is part of the HTTP specification.
PHP handles GET requests easily by automatically creating the superglobal variable $_GET[], where each array index is a GET variable name and the value of the array index is the value of the variable.
Here is some demo code to show how this works:
<?php
//check if the get variable exists
if (isset($_GET['search']))
{
search($_GET['search']);
}
function Search($res)
{
//real search code goes here
echo $res;
}
?>
Search
which will print out 15 because it is the value of search and my search dummy function just prints out any result it gets
The HTML output needs to look like
anchor text
Your function will need to output this information within that format.
No, you cannot do it directly. You can only link to a URL.
In this case, you can pass the function name and parameter in the query string and then handle it in PHP as shown below:
print "<a href='yourphpscript.php?fn=search&id=$id' >$name</a>";
And, in the PHP code :
if ($_GET['fn'] == "search")
if (!empty($_GET['id']))
search($id);
Make sure that you sanitize the GET parameters.
No, at least not directly.
You can link to a URL
You can include data in the query string of that URL (<a href="myProgram.php?foo=bar">)
That URL can be handled by a PHP program
That PHP program can call a function as the only thing it does
You can pass data from $_GET['foo'] to that function
Yes, you can do it. Example:
From your view:
<p>Edit
Where 1 is a parameter you want to send. It can be a data taken from an object too.
From your controller:
function test($id){
#code...
}
Simply do this
<?php
function sample(){
foreach ($json_output->object ){
$name = "{$object->title}";
$id = "{$object->id}";
print "<a href='?search=" . $id . "' > " . $name . "</a>";
}
}
if (isset($_REQUEST['search'])) {
search($_REQUEST['search']);
}
function search($id){
//run a search via the id provide by the clicking of that particular name link
}
?>
Also make sure that your $json_output is accessible with is the sample() function. You can do it either way
<?php
function sample(){
global $json_output;
// rest of the code
}
?>
or
<?php
function sample($json_output){
// rest of the code
}
?>
Set query string in your link's href with the value and access it with $_GET or $_REQUEST
<?php
if ( isset($_REQUEST['search']) ) {
search( $_REQUEST['search'] );
}
function Search($res) {
// search here
}
echo "<a href='?search='" . $id . "'>" . $name . "</a>";
?>
Yes, this is possible, but you need an MVC type structure, and .htaccess URL rewriting turned on as well.
Here's some reading material to get you started in understanding what MVC is all about.
http://www.phpro.org/tutorials/Model-View-Controller-MVC.html
And if you want to choose a sweet framework, instead of reinventing the MVC wheel, I highly suggest, LARAVEL 4
I keep getting an 'Undefined variable' notice when I call on an object I 'think' I have instantiated, but apparently haven't. I can't put a finger on my the error. The object is $fgmembersite, according to my error messages it doesn't exist, I'm confused about why. It maybe a simple case of me messing up my directories in the include/require portion of my scripts but I've been looking at them and can't see anything wrong. Tell me if you guys want to look at my file hierarchy.
And again thanks for the help!
I have three PHP files that are at play.
First one is login-home.php
<?PHP
require_once("./profile_settings/view.php");
if(!$fgmembersite->CheckLogin())
{
$fgmembersite->RedirectToURL("login.php");
exit;
}
?>
/*a bunch of stuff*/
<img id="profile_avatar" src="profile_settings/<?php echo fetchAvatarLocation(); ?>"></img>
/*a bunch of stuff*/
Next I have view.php which holds a function I use to generate the path-name of where I store my picture.
<?php
include("./include/membersite_config.php");
function fetchAvatarLocation()
{
$user_id = $fgmembersite->UserId();
$query = mysql_query("SELECT * FROM ddmembers WHERE id_user = '$user_id'");
if(mysql_num_rows($query)==0)
die("User not found!");
else
{
$row = mysql_fetch_assoc($query);
$location = $row['imagelocation'];
return $location;
}
}
?>
And finally I have membersite_config.php
<?PHP
include("fg_membersite.php");
$fgmembersite = new FGMembersite();
//Provide your site name here
$fgmembersite->SetWebsiteName('Mysitename.com');
//Provide the email address where you want to get notifications
$fgmembersite->SetAdminEmail('My.Email#Provider.net');
//Provide your database login details here:
//hostname, user name, password, database name and table name
//note that the script will create the table (for example, fgusers in this case)
//by itself on submitting register.php for the first time
$fgmembersite->InitDB(/*hostname*/'localhost',
/*username*/'user',
/*password*/'password',
/*database name*/'database',
/*table name*/'table');
//For better security. Get a random string from this link: http://tinyurl.com/randstr
// and put it here
$fgmembersite->SetRandomKey('**************');
?>
fg_membersite is a file that contains the class fgmembersite that stores a bunch of functions, the ones that I need it for are...
function UserId()
{
return isset($_SESSION['userid_of_user'])?$_SESSION['userid_of_user']:'';
}
function UserName()
{
return isset($_SESSION['username_of_user'])?$_SESSION['username_of_user']:'';
}
The object is not in the scope of the function, so it is undefined. You need to pass it in as a parameter:
function fetchAvatarLocation( $fgmembersite)
Then call it with the object as a parameter:
<img id="profile_avatar" src="profile_settings/<?php echo fetchAvatarLocation( $fgmembersite); ?>"></img>
An alternative is to use global variables, but I wouldn't recommend it.
I've been searching about deleting db entries in Codeigniter and I finally created a solution that I think is secure. I would really appreciate any feedback! I'm not sure if I'm doing this right..
Advantages:
Uses POST request
ID of entry to be deleted is
validated
Uses CSRF protection (automatically
generated by Codeigniter)
In my example I'm deleting user submitted links (a DB table row contains a link title, link URL, an link description).
HTML: Database entires are contained within a form. Each entry has a form button with the respective link id in the id attribute.
<?php echo form_open('profile/remove_link'); ?>
<?php echo form_hidden('link_id', ''); //value will be populated via jquery ?>
<ul id="user_links">
<?php foreach($query as $row): ?>
<li><?php echo $row->link_title; ?></li>
<li><?php echo auto_link($row->link_url, 'url', TRUE); ?></li>
<li><?php echo $row->link_description; ?></li>
<button type="submit" class="remove" id="<?php echo $row->link_id ?>" value="remove">Remove Link</button>
<?php endforeach; ?>
</ul>
</form>
JQUERY: When user clicks on the remove button, the respective link id is added to the the hidden text input named link_id.
$(document).ready(function(){
$('.remove').click(function() {
var link_to_remove = $(this).attr("id");
$("input[name=link_id]").val(link_to_remove);
});
});
Upon clicking a remove button, it sends the id of link to be removed to controller profile and function remove_link
function remove_link()
{
$this->load->model('Profile_model');
$links_data['query'] = $this->Profile_model->links_read(); //get links from db to add in view
//Validation
$this->form_validation->set_rules('link_id', 'Link ID', 'trim|required|xss_clean|max_length[11]|numeric'); //validate link id
if ($this->form_validation->run() == FALSE) //if validation rules fail
{
$this->load->view('profile/edit_links_view', $links_data);
}
else //success
{
$link_id = $this->input->post('link_id'); //get id of link to be deleted
$seg = 'user_links'; //used to redirect back to user links page
$this->Profile_model->links_delete($link_id, $seg); //send link id to model function
}
}
MODEL
function links_delete($link_id, $seg)
{
$this->db->where('user_id', $this->tank_auth->get_user_id());
$this->db->where('link_id', $link_id);
$this->db->delete('user_links');
redirect("/profile/$seg/");
}
If the ids are unique integers in your database, you could remove these rules:
trim|xss_clean|numeric
And add this one:
is_natural_no_zero
Returns FALSE if the form element contains anything other than a natural number, but not zero: 1, 2, 3, etc.
The numeric rule allows some characters you probably don't want, like decimals and negative. Here's the source (one line):
return (bool)preg_match( '/^[\-+]?[0-9]*\.?[0-9]+$/', $str);
If for some reason you are echo'ing the input back in your HTML output before validating, or are just paranoid, then by all means: xss_clean it up. Otherwise it's not really needed, as I don't think there's any possible method of XSS attacks that only use a number.
Reference:
https://www.owasp.org/index.php/Cross-site_Scripting_%28XSS%29
http://ha.ckers.org/xss.html
Also, you might want to add a LIMIT 1 clause to your query, and definitely make sure to return a value (probably TRUE/FALSE) from your model so you know whether or not the query was successful, so you can give feedback to the user instead of assuming everything went well.
The only thing that I see wrong is that you don't validate who can and can't delete records. That's the only issue you should focus on. Permissions to check if the person sending the request of deletion is allowed to perform such operations. Other than that it's just a matter of preference.
I would suggest rewriting controller and model a bit to make the flow more logical and provide better performance:
controller:
function remove_link()
{
if ($this->input->post('link_id'))
{
//Validation
$this->form_validation->set_rules('link_id', 'Link ID', 'is_natural_no_zero');
if ($this->form_validation->run())
{
$seg = 'user_links'; //do you really need to assign it to variable ??
$this->load->model('Profile_model');
if ($this->Profile_model->links_delete($this->input->post('link_id')) //send link id to model function
{
redirect('/profile/user_links'); // redirect user in controller and only when model returns true
}else{
// inform user about error somehow, eg. by setting session flashdata and redirecting back to /profile/user_links
}
}
} // else statement here was a mistake as in case of form_validation failure nothing happened
$this->load->model('Profile_model');
$links_data['query'] = $this->Profile_model->links_read(); //get links from db to add in view
$this->load->view('profile/edit_links_view', $links_data);
}
model:
function links_delete($link_id)
{
$this->db->where('user_id', $this->tank_auth->get_user_id())
->where('link_id', $link_id)
->delete('user_links'); // you can chain methods without writing always $this->db->
return $this->db->affected_rows(); // returns 1 ( == true) if successfuly deleted
}
And as a side note in your jQuery code I suggest using $('#some_id') instead of $('input[name=XXXX]') - it saves some javascript code execution thus is faster