This question already has answers here:
How to Inserting Form values into mysql database using codeigniter [closed]
(3 answers)
Closed 6 years ago.
I have a contact list on my mySQL database. The columns on my database are name, email and phone_number. Using codeigniter. I know the code I need to insert the data from the form into the database but I can't figure out where to put it into the code. I had the code below in a separate document called form.php but that just kept giving me errors anytime I hit submit. Hence why form.php is in the view.php form.
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone_number'];
$sql = "INSERT INTO data (name, email, phone_number) VALUES ('$name', '$email', '$phone')";
controller.php:
<?php
class controller extends CI_Controller
{
public function index()
{
$this->load->model('model');
$data['info'] = $this->model->getData();
$this->load->view('view', $data);
}
}
?>
model.php:
<?php
class model extends CI_Model
{
public function getData()
{
$query = $this->db->get('data');
return $query->result();
}
}
?>
view.php:
<!DOCTYPE html>
<html>
<head>
<title>Contact List</title>
</head>
<body>
<form action="form.php" method="post">
<p>Name: <input type="text" name="name"></p>
<p>Email: <input type="text" name="email"></p>
<p>Phone Number: <input type="text" name="phone_number"></p>
<input type="submit" value="Submit"><br><br>
<input type="button" onClick="history.go(0)" value="Refresh">
</form>
<br>
<?php
foreach ($records as $rec) {
echo "Name: ".$rec->name."<br>";
echo "Email: ".$rec->email."<br>";
echo "Phone Number:".$rec->phone_number."<br><br>";
}
?>
</body>
</html>
Any help would be appreciated.
Your main problem is bad understanding of MVC arhitecture. If you are new, take time and explore it.
-View
<!DOCTYPE html>
<html>
<head>
<title>Contact List</title>
</head>
<body>
<?php echo form_open('controller/insert');?>
<p>Name: <input type="text" name="name"></p>
<p>Email: <input type="text" name="email"></p>
<p>Phone Number: <input type="text" name="phone_number"></p>
<input type="submit" value="Submit"><br><br>
<input type="button" onClick="history.go(0)" value="Refresh">
<?php echo form_close();?>
<br>
<?php
foreach ($info as $rec) {
echo "Name: ".$rec->name."<br>";
echo "Email: ".$rec->email."<br>";
echo "Phone Number:".$rec->phone_number."<br><br>";
}
?>
</body>
</html>
CONTROLLER
<?php
class controller extends CI_Controller
{
function __CONSTRUCT(){
parent::_CONSTRUCT();
$this->load->helper('file');
$this->load->helper('form');
$this->load->helper('url');
$this->load->model('model');
}
public function index()
{
$this->load->model('model');
$data['info'] = $this->model->getData();
$this->load->view('view', $data);
}
public function insert() {
$data = array (
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'phone_number' => $this->input->post('phone_number')
);
$this->model->insert_data($data);
$this->load->view('view');
}
}
?>
MODEL
<?php
class model extends CI_Model
{
function __CONSTRUCT(){
parent::__CONSTRUCT();
$this->load->database('your_databse_name');
$this->load->library('db'); // optionali you could set it on autoload
}
public function getData()
{
$query = $this->db->get('data');
return $query->result();
}
public function insert_data($data){
$this->db->insert('your_data_table', $data);
}
}
?>
I think this should help you.
If I understand your question correctly, you're trying to submit a form. But you're submitting it to form.php which does not exist.
To elaborate further: In traditional PHP you would submit your form to a new page or the same page and check for $_POST values in that page. Since Codigniter is an MVC framework, you would post your data back to a controller. Which controller doesn't matter.
In your controller you load a model where you create a function to write or get data from or to the database. However, the model is less used nowadays. I'm not sure why because it keeps things organized.
After the controller has processed the data, a new view is loaded. In your case you would create a new view named form.php and load the view via the controller method.
The correct way to do this would be something like this:
<!DOCTYPE html>
<html>
<head>
<title>Contact List</title>
</head>
<body>
<form action="controller/form" method="post">
<p>Name: <input type="text" name="name"></p>
<p>Email: <input type="text" name="email"></p>
<p>Phone Number: <input type="text" name="phone_number"></p>
<input type="submit" value="Submit"><br><br>
<input type="button" onClick="history.go(0)" value="Refresh">
</form>
<br>
<?php
foreach ($records as $rec) {
echo "Name: ".$rec->name."<br>";
echo "Email: ".$rec->email."<br>";
echo "Phone Number:".$rec->phone_number."<br><br>";
}
?>
</body>
</html>
Your controller should like this:
<?php
class controller extends CI_Controller
{
public function index()
{
$this->load->model('model');
$data['info'] = $this->model->getData();
$this->load->view('view', $data);
}
public function form() {
$this->load->model('model');
$data = array(
'name' => $_POST['name'],
'email' => $_POST['email'],
'phone_number' => $_POST['phone_number'] // should be exact table column name for this to work
);
$this->model->insertData($data);
$this->load->view('view', $data);
}
}
?>
And in your model:
<?php
class model extends CI_Model
{
public function getData()
{
$query = $this->db->get('data');
return $query->result();
}
public function insertData($data)
{
return $this->db->insert('data', $data);
}
}
?>
**After you copied my answer, you supplied invalid argument into foreach statement.
Should be:
foreach ($info as $rec) {
Instead of yours
foreach ($records as $rec) {
Create method in model public function insert($data)
public function insert($data){
$sql = "INSERT INTO data (name, email, phone_number) VALUES ('$data['name']', '$data['email']', '$data['phone_number']')";
$this->db->query($sql);
}
Related
I am a new student and I am learning Codeigniter. I have a form view and I want to submit name, email, sdt to add.php to check but I can't connect to add.php.
This is my form
<!DOCTYPE html>
<html>
<body>
<h2>Form Dang Ky</h2>
<form name="submitbd" action="add.php/check" method="POST">
Name<br>
<input type="text" name="name" value="">
<br>
Email:<br>
<input type="text" name="email" value="">
<br>
SDT<br>
<input type="text" name="sdt" value="">
<br>
<br>
<input type="submit" value="Submit">
<br>
</form>
</body>
</html>
and I try to call file add.php in controller, but I got **
404 error
Add.php file in controller
<?php
class Add extends IC_Controller{
$data = array(
'$_name' => $this->input->post('name'),
'$email' => $this->input->post('email'),
'$sdt'=>$this ->input-> post('sdt')
);
public function _contruct(){
parent::_contruct();
}
public function check(){
$this->load->database();
$a=$this->db->query("select email from info where
email=.$array($email)");
if($a==""){
echo "ok";
}
echo "not ok";
}
}
?>
Hope this will help you
Your form tag should be like this :
<form name="submitbd" action="<?=site_url('add/check');?>" method="POST">
..........
</form>
Your Controller Add.php should be like this :
class Add extends CI_Controller
{
public function _contruct(){
parent::_contruct();
$this->load->database();
$this->load->helper('url');
}
public function check()
{
$_name = $this->input->post('name');
$email = $this->input->post('email');
$sdt = $this->input->post('sdt');
$sql = "select email from info where email='{$email}'";
$query = $this->db->query($sql);
if($query->num_rows() > 0)
{
echo "ok";
}
else
{
echo "not ok";
}
}
}
See for more: https://www.codeigniter.com/user_guide/general/index.html
I am new one to codeigniter. I need to insert the data in the database for that i create a controller on the name Home.php, below is that code;While i am running i am getting the error like Message: Undefined property: Home::$Yes.Kindly help please,thank in advance
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller{
public function index()
{
$this->load->database();
$this->load->model('yes');
}
public function savedata()
{
$this->load->view('demo');
if($this->input->post('submit'))
{
$name=$this->input->post('name');
$email=$this->input->post('email');
$content=$this->input->post('content');
$this->Yes->saverecords($name,$email,$content);
echo "Records Saved Successfully";
}
}
}
Here the view pahe at name - demo.php
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action="" enctype="multipart/form-data"
id="User">
<h2 align="center">Student Marks</h2>
<h3>Name:</h3>
<input type="text" name="name" />
<h3>Email ID</h3>
<input type="text" name="email" />
<h3>Content </h3>
<input type="text" name="content" />
<button type="submit" value="submit" name="submit" >Submit</button>
<button type="reset" value="Reset" >Reset</button>
</form>
</body>
</html>
here is the model page at Yes.php
<?php
class Yes extends CI_Models
{
function saverecords($name,$email,$content)
{
$query="insert into news values('$name','$email','$mobile')";
$this->db->query($query);
}
}
first of all you have to load model in your controller.
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller{
function __construct() {
parent::__construct();
$this->load->model('Yes');
}
public function savedata()
{
if($this->input->post('submit'))
{
insert_array=array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'content' => $this->input->post('content')
);
$data_id = $this->Yes->saverecords($insert_array);
if($data_id >0){
echo "Records Saved Successfully";
}
}
}
}
In Model
function saverecords($insert_array) {
if ($this->db->insert('news', $insert_array)) {
return $this->db->insert_id();
}
return 0;
}
Hope this will help you
In controller load database and model in __construct like this , your are adding it to only index method
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->model('yes');
}
public function index()
{
}
public function savedata()
{
if($this->input->post('submit'))
{
$name = $this->input->post('name');
$email = $this->input->post('email');
$content = $this->input->post('content');
$data = ['name' => $name,'email' => $email,'content' => $content];
$insert_id = $this->yes->saverecords($data);
if ($insert_id)
{
echo "Records Saved Successfully";
}
}
$this->load->view('demo');
}
Second
Is $this->load->view('demo'); your form in savedata() method then the form url is ok but if not
Form action should redirect to savedata method because you are accessing post value to in it
<form method="post" action="<?=base_url('home/savedata');?>" enctype="multipart/form-data">
Third Your Model should be like this:
<?php
class Yes extends CI_Models
{
function saverecords($data)
{
$this->db->insert('table_name', $data);
return $this->db->insert_id();
}
}
I want to display current user info from database after login.
Here is my code.
Controller 1 (Welcome)
public function getValues() {
$this->load->model('display_model');
$result=$this->display_model->authenticateUser();
if($result){
$this->session->set_userdata('id', $result['id']);
redirect('/member/home/');
}
else
redirect('/welcome/');
Controller 2 (member)
public function __construct()
{
// Call the CI_Model constructor
parent::__construct();
if($this->session->userdata('id')==NULL)
{
redirect('/welcome/');
}
}
public function home() {
$this->load->view('member_home');
}
Model
public function authenticateUser(){
$name =$_POST['name'];
$password=$_POST['password'];
$where=array('name'=>$name,
'password'=>$password);
return $this->db->select('name, password, id')
->from('member')
->where($where)
->get()->row_array();
View 1 (login_view)
<h1>Member Login Form</h1>
<?php echo validation_errors(); ?>
<?php echo form_open('Welcome/getValues'); ?>
Username: <br/>
<input type="text" name="name" /> <br>
Password: <br>
<input type="password" name="password" /> <br>
<input type="submit" value="Login" name="submit"/>
</form>
View 2: After login view (member_home)
<?php
foreach($result as $row){
?>
<li><?php echo $row['first_name'].' '.$row['last_name'];?>
<br/><strong>Email: </strong><?php echo $row['email'];?>
</li>
Now error shows
Message: Undefined variable: result
How to solve it Need Help.. Thanks in Advance
You are not passing the $result value to your home view update the code as follows:
Controller 1:
public function getValues() {
$this->load->model('display_model');
$result=$this->display_model->authenticateUser();
if($result){
$this->session->set_userdata('id', $result['id']);
redirect(member/home/$result['id']);
}
else
redirect('/welcome/');
Controller 2:
public function __construct()
{
// Call the CI_Model constructor
parent::__construct();
if($this->session->userdata('id')==NULL)
{
redirect('/welcome/');
}
}
public function home($id = '') {
$data['id'] = $id;
$this->load->view('member_home',$data);
}
NOTE:
you must change the query result from row_array() to result_array() as you are using foreach on the view
I am stuck with writing View for my code igniter search form which need to use get..
I currently have this
Controller
<?php
class Search extends CI_Controller {
function __construct(){
parent::__construct();
}
public function index(){
$this->load->view('Search');
}
public function doSearch()
{
$this->load->model("Messages_model");
if ($this->input->get('search') !== FALSE) {
$data ['results'] = $this->Messages_model->searchMessages($this->input->get('search'));
} else {
$data['results'] = array();
}
$this->load->view("Search", $data);
}
Model
class Messages_model extends CI_Model{
function searchMessages($string){
$this->load->database();
$query = $this->db->query("SELECT * FROM messages WHERE text LIKE '%$string%'");
return $query->result();
}
View
<!DOCTYPE html>
<html>
<style>
</style>
<head>
<title></title>
</head>
<body>
<form action="<?php echo site_url('Search/doSearch');?>" method = "get">
<input type="text" name = "keyword"/>
<input type="submit" value = "Search" />
</form>
</div>
</body>
</html>
Can anyone help me out in getting search string displayed
Firstly, go to application/config/config.php and find $config['allow_get_array'] and make sure it's set to TRUE.
Then in your controller you would have something like this:
public function search()
{
$this->load->model("Messages_model");
if ($this->input->get('search') !== FALSE) {
$data ['results'] = $this->Messages_model->searchMessages($this->input->get('search'));
} else {
$data['results'] = array();
}
$this->load->view("Search", $data);
}
Please note that there isn't any validation happening on the string here so you will need to add your own.
Hope this helps!
EDIT
View file:
<!DOCTYPE html>
<html>
<style>
</style>
<head>
<title></title>
</head>
<body>
<form action="<?php echo site_url('search/doSearch'); ?>" method = "get">
<input type="text" name="keyword" value="<?php echo isset($search_value) ? $search_value : ''?>"/>
<input type="submit" value="Search" />
</form>
<?php
if ($search_passed && !empty($results)) {
foreach ($results as $result) {
//Code for displaying results
}
} elseif ($search_passed && empty($results)) {
echo 'No results found!';
}
?>
</div>
</body>
</html>
Controller Method:
public function doSearch()
{
$this->load->model("Messages_model");
if ($this->input->get('keyword') !== FALSE) {
$data ['results'] = $this->Messages_model->searchMessages($this->input->get('keyword'));
//Uncomment the line below to test
// echo '<pre>'; print_r($data['results']);die('</pre>');
$data['search_passed'] = TRUE;
$data['search_value'] = $this->input->get('keyword');
} else {
$data['search_passed'] = FALSE;
$data['results'] = array();
}
$this->load->view("Search", $data);
}
I'm new to CodeIgniter.
At the moment I have a register.php(VIEW) and a register.php(CONTROLLER). The register.php(VIEW) contains a simple form and from this form I am trying to pass data to the controller in order to insert it to the database. Simple.
Whenever I load the view all I seem to be getting is different error messages in relation to the variables and functions, also errors on the line which I try to load the view.
I'm simply asking:
Is this the correct way to be using controllers and views together?
How can I fix this current problem?
Below are the two files:
register.php (VIEW)
<htmL>
<body>
<form method="post" action="controllers/register.php">
<input type="text" name="email">
<input type="text" name="name">
<input type="password" name="password">
<select id="userLevel" name="userLevel">
<option value="2">Job Seeker</option>
<option value="3">Employer</option>
</select>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</htmL>
register.php (CONTROLLER)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users extends CI_Controller{
public function __construct(){
public $email;
public $name;
public $password;
public $userLevel;
$this->email = $_POST['email'];
$this->name = $_POST['name'];
$this->password = $_POST['password'];
$this->userLevel = $_POST['userLevel'];
}
public function createuser() {
if( filter_var($this->email, FILTER_VALIDATE_EMAIL) ) {
$this->db->set('email', $this->email);
$this->db->set('name', $this->name);
$this->db->set('password', $this->password);
$this->db->set('userLevel', $this->userLevel);
$this->db->insert('users');
}
}
$this->load->view('register');
}
?>
Your controller should look like this:
class Users extends CI_Controller{
public function __construct(){
parent::__construct();
}
public function createuser() {
if($this->input->post(null)){
$data = array();
$data['email'] = $this->input->post('email');
$data['name'] = $this->input->post('name');
$data['password'] = $this->input->post('password');
$data['userLevel'] = $this->input->post('userLevel');
$this->db->insert('users', $data);
}
$this->load->view('register');
}
}
Instead of writing <form method="post" action="controllers/register.php"> write <?=form_open('user/createuser')?>
You need to do like this. It is MVC and more clear
VIEW
<htmL>
<body>
<?php echo form_open('controllers/createuser'); ?>
<input type="text" name="email">
<input type="text" name="name">
<input type="password" name="password">
<select id="userLevel" name="userLevel">
<option value="2">Job Seeker</option>
<option value="3">Employer</option>
</select>
<input type="submit" name="submit" value="Submit">
<?php echo form_close(); ?>
</body>
</htmL>
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users extends CI_Controller{
public function __construct(){
$this->load->helper('form');
}
public function createuser() {
$data['email'] = $this->input->post['email'];
$data['name'] = $this->input->post['name'];
$data['password'] = $this->input->post['password'];
$data['userLevel'] = $this->input->post['userLevel'];
if($this->input->post('submit')) {
// Here you can validate data if you want
$this->user_model->insert($data);
redirect('users/success');
}
$this->load->view('register');
}
function success() {
echo "You add user";
}
}
?>
Model
class User_model extends CI_model {
public function __construct() {
parent:: __construct();
}
function add($data) {
$this->db->insert('users', $data); // table name users
}
}