Use CodeIgniter (MVC) to Connect Form to Database - php

My assignment is to use CodeIgniter (an MVC framework) and connect the form that's in the view to the database. I have done most of the code, and I believe most of it is correct. I finally got the view page (form) to load, but I cannot get the Register function in the controller to load. Does anyone see any errors in my code? It would help me a great deal.
form.php (view):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><?php //echo $title;?></title>
</head>
<body>
<h1>Register for a Dorm</h1>
<form method="post"
action="http://ispace.ci.fsu.edu/~trm07/assignment4/index.php/controller/register/">
<fieldset>
<label>First Name</label>
<input type="text" name="first_name"/>
<label>Last Name</label>
<input type="text" name="last_name"/>
</fieldset>
<label>Undergraduate Level:</label>
<?php
//dropdown list for level
echo '<select name="level">';
$level = array('Freshman','Sophomore', 'Junior', 'Senior');
foreach ($level as $selection) {
echo '<option value="'.$selection.'">'.$selection.'</option>';
}
echo '</select>';
?>
<label>Gender:</label>
<?php
//dropdown list for gender
echo '<select name="gender">';
$gender = array('Male','Female');
foreach ($gender as $gend_selection) {
echo '<option
value="'.$gend_selection.'">'.$gend_selection.'</option>';
}
echo '</select>';
//radio buttons for dorms
$requested_dorm = array('Landis','Salley','DeGraff','Cawthon','Reynolds');
echo("<fieldset><legend>Requested Dorm</legend>");
foreach ($requested_dorm as $dorm_names){
echo "<input type='radio' name='dorm_name' value='$dorm_names' />
$dorm_names <br />";
}
?>
<br><input type="submit" value="Register">
</body>
</html>
controller.php
<?php
class Controller extends CI_Controller {
function index()
{ //$data['title'] = "Register for a Dorm";
$this->load->view('form');
}
function show()
{
$this->load->model('model');
$dorms = $this->model->get_dorms();
foreach($dorms as $dorm){
if($dorm['dorm_name'] == $dorm_name)
$chosen_dorm = $dorm['dorm_name'];
}
}
function register()
{
$this->load->library('form_validation');
$view_data = array('message' => '');
//If the form was submitted, process it
if (count($_POST) > 0)
{ $dorm_name = $this->input->post('dorm_name');
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$level = $this->input->post('level');
$gender = $this->input->post('gender');
{
//Validate the input
$this->form_validation->set_rules('first_name', 'First Name',
'required|strip_tags|trim');
$this->form_validation->set_rules('last_name', 'Last Name',
'required|strip_tags|trim');
$val_result = $this->form_validation->run();
//Add the data to the database
if ($val_result == TRUE)
{
$this->load->model('model');
$db_result = $this->model->add_student_to_dorm($_POST['dorm_name'],
$_POST['first_name'], $_POST['last_name'], $_POST['level'], $_POST['gender']);
if ($db_result == TRUE)
{
$view_data['message'] = "Added student to the dorm!";
//$view_data['message'] = "Added" . "$_POST['first_name']" . " " .
"$_POST['last_name']". " to " . "$_POST['dorm_name']" . " hall.";
}
else
{
$view_data['message'] = "An error occured adding the student to the dorm!";
}
}
}
$this->load->view('form',$view_data);
//$this->load->model('model');
//$this->model->get_students();
}
}
}
?>
model.php:
<?php
class Model extends CI_Model {
//function to take student info posted from form, and adds to database
public function add_student_to_dorm()
{
$this->load->database($dorm_name, $first_name, $last_name, $level, $gender);
$data = array
(
'dorm_name' =>$dorm_name,
'student_fname' => $first_name,
'student_lname' => $last_name,
'student_level' => $level,
'student_gender' => $gender,
);
$result = $this->db->insert('student', $data);
return $result;
}
//get dorm table results in an array from database, return its rows
public function get_dorms()
{
$this->load->database();
$dorms = $this->db->get('dorm');
$rows = $dorms->result_array();
return $rows;
}
//get student table results in an array from database, return its rows
public function get_students()
{
$this->load->database();
$students = $this->db->get('student');
$stu_rows = $students->result_array();
return $stu_rows;
}
}
?>

Here you called add_student_to_dorm() function in the controller page with parameters but in model you doesnot take that parameters that is
$db_result = $this->newmodel->add_student_to_dorm($_POST['dorm_name'],
$_POST['first_name'], $_POST['last_name'], $_POST['level'], $_POST['gender']);
this is the function in controller but your model is only have
public function add_student_to_dorm() no variables So change
public function add_student_to_dorm() to
public function add_student_to_dorm($dorm_name, $first_name, $last_name, $level, $gender)
and also change
$this->load->database($dorm_name, $first_name, $last_name, $level, $gender); to
$this->load->database(); in model then it is working

Related

trouble in inserting record to database using PHP mysqli oops [closed]

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 6 years ago.
Improve this question
I am using PHP mysqli to access and insert record to database and also prepared statements but somewhere there is an error i couldn't figure out.. pointing out the mistake will be very much helpful
mailer.php
<?php
class Submit {
const DB = 'localhost',
USER = 'test',
PASS = '123456',
DB_NAME = 'testing';
private $mysql;
public function __construct() {
$this->mysql = new mysqli(self::DB , self::USER , self::PASS , self::DB_NAME);
if ($this->mysql->connect_errno) {
echo "Error: " . $this->mysql->connect_error;
echo "<br>";
echo "Error code: " . $this->mysql->connect_errno;
}
}
public function addRecord($record) {
$status = false;
$query = "INSERT INTO mytable (name,message) VALUES (?,?)";
$stmt = $this->mysql->prepare($query);
if ( $stmt ) {
$stmt->bind_param('ss', $record->name , $record->message);
if ($stmt->execute()) {
$status = ($stmt->affected_rows == 1) ? true : false;
$stmt->fetch_object();
$stmt->close();
}
}
return $status;
}
}
$submit = new Submit();
$result = null;
if (isset($_POST['submit']) ) {
$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$message = isset($_POST['message']) ? trim($_POST['message']) : '';
$result = $submit->addRecord($name,$message);
if ($result) {
echo "Message Saved";
}
}
Also i am using ajax call from an external file containing a form and scripts within that
index.php
<!DOCTYPE html>
<html>
<head>
<title>Contact Form | PHP, AJAX and MySQL</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<br /><br />
<div class="container" style="width:500px;">
<form id="submit_form">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="form-control" />
<br />
<label for="message">Message</label>
<textarea name="message" id="message" class="form-control"></textarea>
<br />
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
<span id="error_message" class="text-danger"></span>
<span id="success_message" class="text-success"></span>
</form>
</div>
</body>
</html>
<script>
jQuery(function($){
$('form#submit_form').submit(function(e){
e.preventDefault();
var name = $(this).find('#name').val(),
message = $(this).find('#message').val();
if(name == '' || message == '') {
$('#error_message').html("All Fields are required");
}
else {
$('#error_message').html('');
$.ajax({
url:"mailer.php",
method:"POST",
data:{
name: name,
message: message
},
success:function(data){
$("form").trigger("reset");
$('#success_message').fadeIn().html(data).fadeOut(3000);
}
});
}
});
});
</script>
You are giving 2 parameters to your addRecord() method, but it expects only 1. But, it seems it expects an object which you are not initializing so I adjusted it, so it takes the two parameters you are giving it.
public function addRecord($name, $message) {
$status = false;
$query = "INSERT INTO mytable (name,message) VALUES (?,?)";
$stmt = $this->mysql->prepare($query);
if ( $stmt ) {
$stmt->bind_param('ss', $name , $message);
if ($stmt->execute()) {
$status = $stmt->affected_rows === 1;
}
}
return $status;
}
Also I removed some unnecessary steps in the method:
$status = ($stmt->affected_rows == 1) ? true : false;
$status = $stmt->affected_rows === 1;
The comparison itself will return a boolean, so no need to use an explicit structure.
$stmt->fetch_object();
$stmt->close();
Fetching the object without ever using it is a waste.
When leaving the scope of the method, the garbage collector will unset the stmt.
Code to test the function:
class Submit {
const DB = 'localhost',
USER = 'test',
PASS = '123456',
DB_NAME = 'testing';
private $mysql;
public function __construct() {
$this->mysql = new mysqli(self::DB , self::USER , self::PASS , self::DB_NAME);
if ($this->mysql->connect_errno) {
echo "Error: " . $this->mysql->connect_error;
echo "<br>";
echo "Error code: " . $this->mysql->connect_errno;
}
}
public function addRecord($name, $message) {
$status = false;
$query = "INSERT INTO mytable (name,message) VALUES (?,?)";
$stmt = $this->mysql->prepare($query);
if ( $stmt ) {
$stmt->bind_param('ss', $name , $message);
if ($stmt->execute()) {
$status = $stmt->affected_rows === 1;
}
}
return $status;
}
}
$submit = new Submit();
$result = null;
$name = "dsfdsf";
$message = "message";
$result = $submit->addRecord($name,$message);
var_dump($result); // bool(true)

Message : Undefined Variable userid , workspaceid

I am working on a view that show's me the data from the database using joins in textbox.
Now I get the error:
Message: Undefined variable: userid
Message: Undefined variable: workspaceid
Following is my model, View and Controller
Model :-
function getMilestone($taskid, $userid,$workspaceid, $is_master_admin) {
$this->load->database();
if($is_master_admin) {
$this->db->select('user.title as usertitle, workspace.title as workspacetitle,workspace.id as workspaceid,task.title as tasktitle,task.id as taskid, milestone.*');//task.title as tasktitle,task.id as taskid,
} else {
$this->db->select('*');
}
$this->db->from(MILESTONE);
if($is_master_admin) {
$this->db->join(USER, 'milestone.userid = user.id', 'inner');
$this->db->join(WORKSPACE, 'workspace.id = milestone.workspaceid','inner');
$this->db->join(TASK, 'task.id = milestone.taskid', 'inner');
} else {
}
$this->db->where('taskid', $taskid);
if($is_master_admin) {
$this->db->order_by("userid", "asc");
} else {
$this->db->where('userid', $userid);
}
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
Controller :-
function addNew($taskid) {
if ($this->session->userdata('logged_in')) {
$session_data = $this->session->userdata('logged_in');
$id = $session_data['id'];
$username = $session_data['username'];
$is_master_admin = $session_data['master'];
$imagethumb = $session_data['imagethumb'];
$pendingbug = $this->bugmodel->getBug($id,$is_master_admin);
$pendingtask = $this->taskmodel->getTask($id,$is_master_admin);
$status_result = $this->getstatus->getEnumValues(MILESTONE,'status');
$result = $this->milestonemodel->getMilestone($taskid, $userid, $workspaceid, $is_master_admin) ;
$data='';
$data = array('username' => $username,
'is_master_admin' => $is_master_admin,
'imagethumb' => $imagethumb,
'result' => $result,
'status_result' => $status_result,
'taskid' => $taskid,
'pendingtask' => $pendingtask,
'pendingbug' => $pendingbug
);
$this->load->view('milestone/add_milestone', $data);
} else {
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
View :-
<div class="control-group">
<label class="control-label">Title<span class="required">*</span></label>
<div class="controls">
<input type="text" name="title" data-required="1" class="span6 m-wrap" readonly="readonly"value="<?php echo $result[0]->taskid; ?>"/> <p><?php echo form_error('title'); ?></p>
<input type="hidden" id="tasktype" name="tasktype" data-required="1" class="span2 m-wrap" value="<?php //echo $task_type ?>"/>
</div>
</div>
<div class="control-group">
<label class="control-label">Workspace</label>
<div class="controls">
<input type="text" readonly="readonly" value="<?php echo $result[0]->workspacetitle; ?>"></input>
</div>
</div>
In my View value is printing using taskid; ?> & workspacetitle; ?> on text box but error is printed on top of the page
Try this controller,
function addNew($taskid) {
if ($this->session->userdata('logged_in')) {
$session_data = $this->session->userdata('logged_in');
$id = $session_data['id'];
$username = $session_data['username'];
$is_master_admin = $session_data['master'];
$imagethumb = $session_data['imagethumb'];
$pendingbug = $this->bugmodel->getBug($id, $is_master_admin);
$pendingtask = $this->taskmodel->getTask($id, $is_master_admin);
$status_result = $this->getstatus->getEnumValues(MILESTONE, 'status');
$result = $this->milestonemodel->getMilestone($taskid, $username, $id, $is_master_admin);
$data = '';
$data = array('username' => $username,
'is_master_admin' => $is_master_admin,
'imagethumb' => $imagethumb,
'result' => $result,
'status_result' => $status_result,
'taskid' => $taskid,
'pendingtask' => $pendingtask,
'pendingbug' => $pendingbug
);
$this->load->view('milestone/add_milestone', $data);
} else {
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
I think $userid and $workspace are the $username and $id
There is no values assigned for the variables $userid, $workspaceid
$result = $this->milestonemodel->getMilestone($taskid, $userid, $workspaceid, $is_master_admin) ;
You need to pass the $result into the view. Add the code below :
$data['result']= $result;
before calling :
$this->load->view('milestone/add_milestone', $data);
Then in your view, reference it as :
$result->userid;

Undefined variable following a method call [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 8 years ago.
I am trying to put myself in OOP and I have a problem with variable scope.
Everything works except a session array and everything posts correctly.
My 'session table' and its elements are declared but its variables remain undefined. I get the following error messages:
Notice: Undefined variable: row
Notice: Trying to get property of non-object
What I can do to get access to $row?
This is my code for the class, including its methods:
$db = db::connect();
class auth {
protected $login;
protected $password;
protected $email;
public function setLogin($login) {
$this->login = $login;
}
public function setPassword($password) {
$this->password = $password;
}
public function login($fields, $table, $col_login, $col_password) {
$query = Db::getInstance()->prepare('SELECT ' . $fields . ' FROM ' . $table . ' WHERE ' . $col_login . ' = :login AND ' . $col_password . ' = :password');
$query->bindValue( ':login', $this->login, PDO::PARAM_STR);
$query->bindValue(':password', $this->password, PDO::PARAM_STR);
$query->execute();
if ($query->rowCount() > 0) {
$row = $query->fetch(PDO::FETCH_OBJ);
echo '<pre>';
print_r($row->u_login);
echo '</pre>';
return true;
}
else {
return false;
}
$query->closeCursor();
}
}
Here is my form code; this is from where I call the class method:
<?php
session_start();
if (isset($_POST['login_submit'])) {
if (!empty($_POST['login']) && !empty($_POST['password'])) {
$auth = new auth();
$auth->setLogin($_POST['login']);
$auth->setPassword(sha1($_POST['password']));
if ($auth->login('u_login,u_password,u_email,u_id_level', 'users', 'u_login', 'u_password')) {
$_SESSION['back_office'] = array(
'login' => $row->u_login, // Error, $row is undefined
'level' => $row->u_level,
'email' => $row->u_email
);
}
else {
message::showError('Compte non reconnu');
}
}
else {
message::showError('Veuillez remplir tous les champs');
}
}
?>
<form action="test.php" name="loginform" method="post">
<input type="text" name="login" />
<input type="password" name="password" />
<input type="submit" name="login_submit" value="Se connecter" />
</form>
In your auth function you need to return row
if($query->rowCount() > 0){
$row = $query->fetch(PDO::FETCH_OBJ);
return $row;
}else{
return false;
}
In your call assign the return value of login to $row
if (($row = $auth->login('u_login,u_password,u_email,u_id_level', 'users', 'u_login', 'u_password'))) {
You have to return $row instead of return true
$row = $query->fetch(PDO::FETCH_OBJ);
echo '<pre>';
print_r($row->u_login);
echo '</pre>';
return $row; // return true;
And you check like this
if($row = $auth->login('u_login,u_password,u_email,u_id_level',
'users', 'u_login', 'u_password') !== false)
Then you can set value of $row
$_SESSION['back_office'] = array(
'login' => $row->u_login,
'level' => $row->u_level,
'email' => $row->u_email
);
$row is not a global variable so you can't access from outside.
Between it's bad to make it global.
I will suggest you to put a variable called $authenticated_user for example.
Like that :
class auth {
// ...
protected $authenticated_user;
//...
public function login( // ... ) {
// ...
$authenticated_user = $query->fetch(PDO::FETCH_OBJ);
// ...
}
public getUser()
{ return $authenticated_user; }
}
In you Auth call part :
$row = $auth->getUser();
That's should be fine.

Need to edit and delete using DAO

I was wondering if anyone could help me with this problem i'm having.
I have a ReminderDAO class with methods to delete, edit, insert etc and a Reminder class with a constructor and get and sets.
I then have a a view reminders where it just lists all the reminders out.
I want to be able to add an edit and delete to this view page.
To use the delete and edit functions in my ReminderDAO class, i need to pass a reminder object through the function and i'm not quite sure how to do this.
If anyone could help me that would be of great help, i'm new to this language so i apologise if it's not great code.
Thank you in advance!
Reminder DAO
class ReminderDAO extends DAO {
public function __construct() {
parent::__construct();
}
public function insert($reminder) {
if (!isset($reminder)) {
throw new Exception("Reminder required");
}
$sql = "INSERT INTO Reminders(member_id, title, details, reminder_type) VALUES (?, ?, ?, ?)";
$params = array($reminder->getMember_id(), $reminder->getTitle(), $reminder->getDetails(), $reminder->getType());
$stmt = $this->link->prepare($sql);
$status = $stmt->execute($params);
if ($status != true) {
$errorInfo = $stmt->errorInfo();
throw new Exception("Could not save Reminder: " . $errorInfo[2]);
}
$sql = "SELECT LAST_INSERT_ID()";
$stmt = $this->link->prepare($sql);
$status = $stmt->execute();
if ($status != true) {
$errorInfo = $stmt->errorInfo();
throw new Exception("Could not retrieve new reminder's id: " . $errorInfo[2]);
}
$row = $stmt->fetch();
$id = $row[0];
$reminder->setId($id);
}
public function delete($reminder) {
if (!isset($reminder)) {
throw new Exception("Reminder required");
}
$id = $reminder->getId();
if ($id == null) {
throw new Exception("Reminder id required");
}
$sql = "DELETE FROM Reminders WHERE id = ?";
$params = array($reminder->getId());
$stmt = $this->link->prepare($sql);
$status = $stmt->execute($params);
if ($status != true) {
$errorInfo = $stmt->errorInfo();
throw new Exception("Could not delete reminder: " . $errorInfo[2]);
}
}
public function update($reminder) {
if (!isset($reminder)) {
throw new Exception("Reminder required");
}
$id = $reminder->getId();
if ($id == null) {
throw new Exception("Reminder id required");
}
$sql = "UPDATE Reminders SET member_id = ?, title = ?, details = ?, reminder_type = ? WHERE id = ?";
$params = array($reminder->getMember_id(), $reminder->getTitle(), $reminder->getDetails(), $reminder->getType());
$stmt = $this->link->prepare($sql);
$status = $stmt->execute($params);
if ($status != true) {
$errorInfo = $stmt->errorInfo();
throw new Exception("Could not update Reminder: " . $errorInfo[2]);
}
}
public function getReminder($id) {
$sql = "SELECT * FROM Reminders WHERE id = ?";
$params = array($id);
$stmt = $this->link->prepare($sql);
$status = $stmt->execute($params);
if ($status != true) {
$errorInfo = $stmt->errorInfo();
throw new Exception("Could not retrieve Reminder: " . $errorInfo[2]);
}
$reminder = null;
if ($stmt->rowCount == 1) {
$row = $stmt->fetch();
$id = $row['id'];
$member_id = $row['member_id'];
$title = $row['title'];
$details = $row['details'];
$type = $row['reminder_type'];
$reminder = new ReminderDAO($id, $member_id, $title, $details, $type);
}
return $reminder;
}
public function getReminders() {
$sql = "SELECT * FROM Reminders";
$stmt = $this->link->prepare($sql);
$status = $stmt->execute();
if ($status != true) {
$errorInfo = $stmt->errorInfo();
throw new Exception("Could not retrieve reminders: " . $errorInfo[2]);
}
$reminders = array();
$row = $stmt->fetch();
while ($row != null) {
$id = $row['id'];
$member_id = $row['member_id'];
$title = $row['title'];
$details = $row['details'];
$type = $row['reminder_type'];
$reminder = new Reminder($id, $member_id, $title, $details, $type);
$reminders[$id] = $reminder;
$row = $stmt->fetch();
}
return $reminders;
}
}
?>
Reminder Class
<?php
class Reminder {
private $id;
private $member_id;
private $title;
private $details;
private $reminder_type;
public function __construct($i, $m_id, $title, $det, $type) {
$this->id = $i;
$this->member_id = $m_id;
$this->title = $title;
$this->details = $det;
$this->reminder_type = $type;
}
public function getId() { return $this->id; }
public function getMember_id() { return $this->member_id; }
public function getTitle() { return $this->title; }
public function getDetails() { return $this->details; }
public function getType() { return $this->reminder_type; }
public function setId($i) { $this->id = $i; }
public function setMember_id($mID) { $this->member_id = $mID; }
public function setTitle($t) { $this->title = $t; }
public function setDetails($d) { $this->details = $d; }
public function setType($type) { $this->reminder_type = $type; }
}
?>
View Reminders
<?php
ob_start();
require_once 'includes/Member.php';
require_once 'includes/MemberDAO.php';
require_once 'includes/Reminder.php';
require_once 'includes/ReminderDAO.php';
require_once 'includes/session.php';
confirm_logged_in(); // needs to come before any html because it does a redirect
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
require 'toolbar.php';
$member = ($_SESSION['member']);
$reminderDAO = new ReminderDAO();
$reminders = $reminderDAO->getReminders();
echo "<p>Hello " . $member->getFN() . "</p>";
echo "<p>These are the current reminders: </p>";
foreach ($reminders as $rem) {
echo "<b>Title:</b> " . $rem->getTitle() . "<br />";
echo "<b>Details:</b> " . $rem->getDetails() . "<br />";
echo "<b>Type: </b>" . $rem->getType() . "<br />";
echo "</p>";
}
echo $display; ?>
Add Reminder?
</body>
</html>
<?php ob_flush(); ?>
edit_reminder_form.php class
<?php
ob_start();
require_once 'includes/session.php';
require_once 'includes/Member.php';
require_once 'includes/MemberDAO.php';
require_once 'includes/Reminder.php';
require_once 'includes/ReminderDAO.php';
require_once 'includes/session.php';
confirm_logged_in(); // needs to come before any html because it does a redirect
?>
<?php
$reminderDAO = new ReminderDAO();
$reminder = $reminderDAO->getReminder($_GET['id']);
?>
<html>
<head>
<title>Edit Reminder</title>
</head>
<body>
<table>
<tr>
<td>
<h2>Edit Reminder</h2>
<?php if (isset($_GET['errorMessage'])) echo "<p>".$_GET['errorMessage']."</p>"; ?>
<form action="edit_reminder.php" method="POST">
Title: <input type="text" name="title" value="<?php $reminder->getTitle(); ?>" /><br/>
Details: <input type="text" name="details" value="<?php $reminder->getDetails()?> " /><br/>
<select name="reminder_type" value="<?php $reminder->getType();?>">
<option value="Choose">Please choose a reminder type!</option>
<option value="Bill">Bill</option>
<option value="Shopping">Shopping</option>
<option value="Event">Event</option>
<option value="Birthday">Birthday</option>
<option value="Other">Other</option>
</select>
<br />
<input type="submit" name="reminder" value="Edit Reminder" />
</form>
<br />
Cancel
</td>
</tr>
</table>
</body>
<?php
//5.Close connection
if(isset($connection)) {
mysql_close($connection);
}
?>
</html>
<?php ob_flush(); ?>
You could send the ID of the reminder to the next page where you edit/delete a reminder.
foreach ($reminders as $rem) {
echo "<b>Title:</b> " . $rem->getTitle() . "<br />";
echo "<b>Details:</b> " . $rem->getDetails() . "<br />";
echo "<b>Type: </b>" . $rem->getType() . "<br />";
echo "[<a href='edit.php?id=" . $rem->getID() . "'>Edit</a>] ";
echo "[<a href='delete.php?id=" . $rem->getID() . "'>Delete</a>] ";
echo "</p>";
}
In edit.php you get the reminder object using the ID (e.g. $_GET['id']), load the data from the database using ReminderDAO and create a form populated with the reminder values. In that form, you should also put the reminder id, so when he submit the form to Save changes, you can identify the reminder that was edited.
After saving the changes, you can redirect him back to the list of reminders using header function.
Similar, in delete.php you can delete the reminder using the ID (e.g. $_GET['id']) and then redirect the user to the list of reminders.

Controller not acting correctly

I'm new to code igniter but I've been watching many youtube videos and I'm starting to get the hang of the basics of it however after I do a test run on my registration form it goes to a white page with The requested URL /kowmanager/user/register was not found on this server. I'm not sure why. Any ideas?
Controller:
function User()
{
parent :: __construct();
$this->view_data['base_url'] = base_url();
$this->load->model('User_model');
}
function index()
{
$this->register();
}
function register()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required|alpha_numeric|min_length[6]|xss_clean|strtolower|callback_usernameNotExists');
$this->form_validation->set_rules('password', 'Password', 'trim|required|alpha_numeric|min_length[6]|xss_clean');
$this->form_validation->set_rules('passwordConfirm', 'Confirm Password', 'trim|required|alpha_numeric|min_length[6]|xss_clean|matches[password]');
$this->form_validation->set_rules('email', 'Email', 'trim|required|min_length[6]|xss_clean|valid_email|callback_emailNotExists');
$this->form_validation->set_rules('firstName', 'First Name', 'trim|required|alpha_numeric|min_length[6]|xss_clean');
$this->form_validation->set_rules('lastName', 'Last Name', 'trim|required|alpha_numeric|min_length[6]|xss_clean');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('view_register', $this->view_data);
}
else
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$email = $this->input->post('email');
$firstName = $this->input->post('firstName');
$lastName = $this->input->post('lastName');
$registrationKey = substr(md5(mt_rand()), 0, 5);
$this->User_model->registerUser($username, $password, $email, $firstName, $lastName, $registrationKey);
}
}
function usernameNotExists($username)
{
$this->form_validation->set_message('usernameNotExists', ' That %s already exists inside the database!');
if($this->User_model->checkExistsUsername($username))
{
return false;
}
else
{
return true;
}
}
function emailNotExists($username)
{
$this->form_validation->set_message('emailNotExists', ' That %s already exists inside the database!');
if($this->User_model->checkExistsEmail($email))
{
return false;
}
else
{
return true;
}
}
}
?>
View Page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>KOW Manager Registration Form</title>
</head>
<body>
<?php
echo form_open($base_url . 'user/register');
$username = array ('name' => 'username', 'id' => 'username', 'value' => set_value('username'));
$password = array ('name' => 'password', 'id' => 'password', 'value' => '');
$passwordConfirm = array ('name' => 'passwordConfirm', 'id' => 'passwordConfirm', 'value' => '');
$email = array ('name' => 'email', 'id' => 'email', 'value' => set_value('email'));
$firstName = array ('name' => 'firstName', 'id' => 'firstName', 'value' => set_value('firstName'));
$lastName = array ('name' => 'lastName', 'id' => 'lastName', 'value' => set_value('lastName'));
?>
<?php echo form_fieldset('User Information') ?>
<dl>
<dt><label for="username">Username:</label></dt>
<dd><?php echo form_input($username); ?></dd>
</dl>
<dl>
<dt><label for="password">Password:</label></dt>
<dd><?php echo form_password($password); ?></dd>
</dl>
<dl>
<dt><label for="passwordConfirm">Confirm Password:</label></dt>
<dd><?php echo form_password($passwordConfirm); ?></dd>
</dl>
<dl>
<dt><label for="email">Email Address:</label></dt>
<dd><?php echo form_input($email); ?></dd>
</dl>
<dl>
<dt><label for="firstName">First Name:</label></dt>
<dd><?php echo form_input($firstName); ?></dd>
</dl>
<dl>
<dt><label for="lastName">Last Name:</label></dt>
<dd><?php echo form_input($lastName); ?></dd>
</dl>
<?php echo form_fieldset_close() ?>
<?php echo validation_errors() ?>
<dl class="submit">
<?php echo form_submit(array('name' => 'register'), 'Register'); ?>
</dl>
<?php echo form_close(); ?>
</body>
</html>
Edit:
Here's my new code which is still doing the same thing.
<?php
class User extends CI_Controller {
function User()
{
parent :: __construct();
$this->view_data['base_url'] = base_url();
$this->load->model('User_model');
}
function index()
{
$this->register();
}
function register()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required|alpha_numeric|min_length[6]|xss_clean|strtolower|callback_usernameNotExists');
$this->form_validation->set_rules('password', 'Password', 'trim|required|alpha_numeric|min_length[6]|xss_clean');
$this->form_validation->set_rules('passwordConfirm', 'Confirm Password', 'trim|required|alpha_numeric|min_length[6]|xss_clean|matches[password]');
$this->form_validation->set_rules('email', 'Email', 'trim|required|min_length[6]|xss_clean|valid_email|callback_emailNotExists');
$this->form_validation->set_rules('firstName', 'First Name', 'trim|required|alpha_numeric|min_length[6]|xss_clean');
$this->form_validation->set_rules('lastName', 'Last Name', 'trim|required|alpha_numeric|min_length[6]|xss_clean');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('view_register', $this->view_data);
}
else
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$email = $this->input->post('email');
$firstName = $this->input->post('firstName');
$lastName = $this->input->post('lastName');
$registrationKey = substr(md5(mt_rand()), 0, 5);
$this->User_model->registerUser($username, $password, $email, $firstName, $lastName, $registrationKey);
$this->load->library('email');
$this->email->from('kowmanagement#kansasoutlawwrestling.com', 'KOW Management');
$this->email->to($email);
$this->email->subject('KOW Manager Account Registration');
$this->email->message('Hello '.$firstName.' '.$lastName.' Welcome to our website!<br /><br />You, or someone using your email address, has completed registration at '.myDomainName().'. You can complete registration by clicking the following link:<br /><br />' . anchor('http://www.'.myDomainName().'/manager/verify.php?userID='.$userID.'&verifyHash='.$verifyHash.'", http://www.'.myDomainName().'/manager/verify.php?userID='.$userID.'&verifyHash='.$verifyHash.''));
$this->email->send();
}
}
function registerConfirm()
{
$registrationKey = $this->uri->segment(3);
if ($registrationKey == '')
{
echo 'No registration key found in URL';
exist();
}
$registrationConfirmed = $this->User_model->confirmRegistration($registrationKey);
if ($registrationConfirmed)
{
echo 'You have successfully registered!';
}
else
{
echo 'You have failed to register!';
}
}
function usernameNotExists($username)
{
$this->form_validation->set_message('usernameNotExists', ' That %s already exists inside the database!');
if($this->User_model->checkExistsUsername($username))
{
return false;
}
else
{
return true;
}
}
function emailNotExists($username)
{
$this->form_validation->set_message('emailNotExists', ' That %s already exists inside the database!');
if($this->User_model->checkExistsEmail($email))
{
return false;
}
else
{
return true;
}
}
function myDomainName()
{
$my_domain = $_SERVER['HTTP_HOST'];
$my_domain = str_replace('www.', '', $my_domain);
return $my_domain;
}
}
?>
Any other ideas?
CodeIgniter routes by default are structured like this.
http://example.com/index.php/Controller/Function
If you don't have 'index.php' in your code it isn't going to be routed correctly unless you have a mod_rewrite rule setup in Apache.
try setting up your url like this
http://domain/index.php/user/register
and see what happens.
Check this out:
http://codeigniter.com/wiki/mod_rewrite/
Bear in mind that what you are doing is this:
mysite.com/kowmanager/user/register
or
mysite.com/index.php/kowmanager/user/register
in either case
1) you are using the knownmanager Directory
2) you are using the controller user
3) you are calling the method 'register'
You can check the following things:
It looks like you are using your user method as a constructor if you are using CI 2 use
function __constructor() {
parent::__constructor();
}
as your constructor.
also you are not calling the view in this controller, are you using a different controller to call the view? I would create a new method called registration_form and call the view from there:
$data['data'] = array();
$this->load->view('view_name', $data);
In this case what you would do is use the following url
mysite.com/kowmanager/index.php/user/registration_form/
Then when the form is submitted it will call the validation method.
I'm not sure if you are loading form_validation before using it
$this->load->library('form_validation');
Good Luck!
Try setting you base_url. If you're working locally and using MAMP or XAMP, it would be something like this:
$config['base_url'] = 'http://localhost/kowmanager';

Categories