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);
}
Related
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();
}
}
There is an error while redirecting the page from login to index(i.e server error // error 500). I used redirect_to function to call function.php from login.php file and i have included header function in function.php file. unfortunately, there is server error.I tried to solve it but i could not.i have posted my all four file.
login.php
<?php
require_once("../../includes/function.php");
require_once("../../includes/database.php");
require_once("../../includes/session.php");
require_once("../../includes/user.php");
if($session->is_logged_in()){
redirect_to("index.php");
}
//remember to give your form's submit tag a name= "submit" attribute
if(isset($_POST['submit'])){
$username = trim($_POST['username']);
$password = trim($_POST['password']);
//check database to see if username/password exit.
$found_user = User::authenticate($username,$password);
if($found_user){
$session->login($found_user);
redirect_to("index.php");
}else{
//username/password combo was not found in the database
$message ="Username/password incorrect.";
echo $message;
}
}
else{//form has not been submitted
$username = "";
$password = "";
}
?>
<?php if(isset($database)) {
$database->close_connection();
}
?>
<html>
<head>
<title>Photo Gallery</title>
<link href="boot/css/bootstrap.css" media="all" rel ="stylesheet" type
="text/css"/>
</head>
<body>
<div id="header">
<h1>Photo Gallery</h1>
</div>
<div id ="main">
<h2>staff login</h2>
</div>
<form action="login.php" method="post">
<table>
<tr>
<td>Username:</td>
<td>
<input type = "text" name = "username" maxlength="30" value="<?php echo
htmlentities($username);?>"/>
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type = "password" name= "password" maxlength = "30" value ="
<?php echo htmlentities($password);?>"/>
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit" value = "login"/>
</td>
</tr>
</table>
</form>
</body>
</html>
index.php
<?php
require_once('../../includes/function.php');
require_once('../../includes/session.php');
if(!$session->is_logged_in()) {
redirect_to("login.php");
}
?>
<html>
<head>
<title>Photo Gallery</title>
<link href="boot/css/bootstrap.css" media="all" rel ="stylesheet" type
="text/css"/>
</head>
<body>
<div id="header">
<h1>Photo Gallery</h1>
</div>
<div id ="main">
<h2>staff login</h2>
</div>
<div id = "footer">Copyright<?php echo date("Y", time());?>,prayash
bhari</div>
</body>
</html>
function.php
<?php
ob_start();
function strip_zeros_from_data($marked_string =""){
//first remove the marked zeros
$no_zeros = str_replace('*0','',$marked_string);
//then remove any remaining marks
$cleaned_string = str_replace('*','', no_zeors);
return $cleaned_string;
}
function redirect_to($location = NULL){
if ($location != NULL){
header("Location : {$location}");
exit;
}
}
function output_message($message = ""){
if($empty($message)){
return "<p class = \"message\">{$message}</p>";
}
else{
return "";
}
}
function __autoload($class_name){
$class_name = strtolower($class_name);
$path = "../includes/{$class_name}.php";
if(file_exists($path)){
require_once($path);
}else{
die("the file {$class_name}.php could not found.");
}
}
ob_end_flush();
?>
sesssion.php
<?php
// A class to help work with Sessions
//In our case, primarily to mange logging users in and out
//keep in mind when working with sessions that it is generally
//inadvisable to store DB-relate objects in sessions
class Session{
private $logged_in = false;
public $user_id;
function __construct(){
session_start();
$this->check_login();
if($this->logged_in){
//actions to take right away if user is logged in
}else{
//actions to take right away if user is not logged in
}
}
public function is_logged_in(){
return $this->logged_in;
}
public function login($user){
//database should find user based on username/password
if($user){
$this->user_id = $_SESSION['user_id'] = $user -> id;
$this->logged_in = true;
}
}
public function logout(){
unset($_SESSION['user_id']);
unset($this->user_id);
$this->logged_in = false;
}
private function check_login(){
if(isset($_SESSION['user_id'])){
$this->user_id = $_SESSION['user_id'];
$this->logged_id = true;
}else{
unset($this->user_id);
$this->logged_in = false;
}
}
}
$session = new Session()
?>
error message
remove {} and put".." in
header("Location : {$location}");
instead of
header("Location:".$location);
You have to redirect to full URL so Try this,
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
redirect_to($url."index.php");
As Gyandeep Mentioned above change your function,too.
function redirect_to($location){
header('Location:'.$location);
exit();
}
Hope this helps.
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);
}
file index.php
<html>
<head>
<title>Guset Book</title>
</head>
<body>
<h3>Guest book</h3>
<a href="/addNew.php">
<p><input type="button" value="Add in book" ></p>
</a>
<a href="/readAll.php">
<p><input type="button" value="Read all"></p>
</a>
</body>
file addNew.php
<html>
<head>
<title>Guset Book</title>
</head>
<body>
<h3>New</h3>
<form name='formAddNew' method='post' action="ControllerAdd.php">
<p>Author: <input type="text" name="nameAuthor"></p>
<p>Comment:</p>
<p><textarea rows="5" cols="40" name="commentAuthor" style="resize: none;"></textarea></p>
<p><input type="submit" name="submitAuthor" value="Submit"></p>
</form>
</body>
file Model.php
<?php
class GuestBook
{
private $author;
private $comment;
function __construct($author, $commment)
{
$this->author = $author;
$this->comment = $commment;
}
public function getAuthor()
{
return $this->author;
}
public function getComment()
{
return $this->comment;
}
}
$guestBookList = new ArrayObject();
$guestBookList[] = new GuestBook("Author", "Comment");
function addInList($author, $comment)
{
$guestBookList[] = new GuestBook($author, $comment);
}
?>
file ControllerAdd.php
<html>
<head>
<title>Add</title>
</head>
<body>
<?php
require_once "Model.php";
addInList($_POST["nameAuthor"], $_POST["commentAuthor"]);
?>
<h3>Succes</h3>
<input type="button" value="On main">
</body>
file readAll.php
<html>
<head>
<title></title>
</head>
<body>
<?php
require_once "Model.php";
foreach($guestBookList as $value)
{
echo("<br>-----------<br>");
echo($value->getAuthor());
echo("<br>");
echo($value->getComment());
}
?>
</body>
The problem is that complier don't throws a mistakes, but don't write the code into array from textboxes. It read in right way the info from textboxes, but don't write into array Plz help.
I suggest in your particular case you need to change behaviour of your Model, something like this:
it's only an example, and must not be used as is
I guess, this code don't crash OP source
<?php
class GuestBook {
private $source;
private $book;
function __construct($filename) {
$this->book = array();
$this->source = $filename;
$this->restore();
}
function getBook() {
return $this->book;
}
function restore() {
if (file_exists($this->source)) {
$records = file($this->source);
if (is_array($records)) {
while (count($records)) {
$line = trim(array_shift($records));
list($author, $comment) = explode(':splitter:',$line);
$this->book[] = new GuestBookRecord($author, $comment);
}
}
}
}
function save() {
$fd = fopen($this->source, 'w');
foreach ($this->book as $record) {
fwrite($fd, $record->getAuthor().':splitter:'.$record->getComment().PHP_EOL);
}
fclose($fd);
}
function addComment($author, $comment) {
$this->book[] = new GuestBookRecord($author, $comment);
$this->save();
}
}
class GuestBookRecord {
private $author;
private $comment;
function __construct($author, $commment) {
$this->author = $author;
$this->comment = $commment;
}
public function getAuthor() {
return $this->author;
}
public function getComment() {
return $this->comment;
}
}
$guestBook = new GuestBook('sample.txt');
// compatibility with OP source
$guestBookList = $guestBook->getBook();
// compatibility with OP source
function addInList($author, $comment) {
global $guestBook;
$guestBook->addComment($author, $comment);
}
But it's not so good. Here is minimum 2 problems, first - the code reads all of the records into memory, second - concurrent accessing. It's just an example.
Session are best way to pass variables in this case
if i understand properly then you want to pass text filds value from two page and use them in 3rd page in array.
Use this as reference
index.php
<?php
session_start();
if(isset($_POST['submit'])){
if(!empty($_POST['tex1'])){
$_SESSION['tex1'] = $_POST['tex1'];
header('location:form.php');
}
}
?>
<form method="POST">
<input type="text" name="tex1">
<input type="submit" name="submit" value="submit">
</form>
form.php
<?php
session_start();
if(isset($_POST['submit'])){
if(!empty($_POST['tex2'])){
$_SESSION['tex2'] = $_POST['tex2'];
header('location:final_page.php');
}
}
?>
<form method="POST">
<input type="text" name="tex2">
<input type="submit" name="submit" value="submit">
</form>
final_page.php
<?php
session_start();
print_r($_SESSION);
$_SESSION is global variable of php.
To read more about session. Please read http://php.net/manual/en/reserved.variables.session.php
file1.php
<form action="file2.php" method="POST">
<textarea rows="4" cols="50" name="data[]"> </textarea>
<input type="submit" value="Submit">
</form>
file2.php
<?php
session_start();
$formData = $_POST['data'];
//echo '<pre>'; print_r($formData); die;
$_SESSION['formData'] = $formData;
echo 'Open File 3 to check submitted data.'
?>
file3.php
<?php
session_start();
if(isset($_SESSION['formData']) && $_SESSION['formData'] != ''){
print_r($_SESSION['formData']);
} else {
echo 'Submit form first.';
}
session_destroy();
?>
I am trying to display a list of comments from a MySql database in PHP.
The foreach loop works as it displays the necessary html for each comment in the database, but no actual content from the database is being pulled through.
Comment class
class Comment {
protected $_id;
protected $_user;
protected $_commentText;
protected $_dateTimePosted;
public function __construct()
{
$this->_dateTimePosted = new DateTime();
$this->_dateTimePosted->format(DATE_RFC3339);
}
public function get_id()
{
return $this->_id;
}
public function set_id($value)
{
$this->_id = $value;
}
public function get_user()
{
return $this->_user;
}
public function set_user($value)
{
$this->_user = $value;
}
public function get_commentText()
{
return $this->_commentText;
}
public function set_commentText($value)
{
$this->_commentText = $value;
}
public function get_dateTimePosted()
{
return $this->_dateTimePosted;
}
public function set_dateTimePosted($value)
{
$this->_dateTimePosted = $value;
}
}
CommentFunctions.php
include 'dbConnect.php';
class CommentFunctions {
protected $conn;
public function __construct()
{
$this->conn = dbConnect();
}
public function get_comments()
{
$sql = "SELECT * FROM comments";
$stmt = $this->conn->stmt_init();
$stmt->prepare($sql);
$stmt->execute();
$stmt->store_result();
$comments = array();
while ($row = $stmt->fetch())
{
$comment = new Comment();
$comment->set_id($row['id']);
$comment->set_user($row['user']);
$comment->set_commentText($row['comment_text']);
$comment->set_dateTimePosted($row['datetime_posted']);
$comments[] = $comment;
}
return $comments;
}
}
Index.php
<?php
include './includes/Comment.php';
include './includes/CommentFunctions.php';
$comments_func = new CommentFunctions();
$all_comments = $comments_func->get_comments();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Comments</title>
<link rel="stylesheet" type="text/css" href="./css/Master.css" />
<link rel="stylesheet" type="text/css" href="./css/Site.css" />
</head>
<body>
<div id="Container">
<h2>Comments</h2>
<a class="reload-comments" href="/">Refresh</a>
<div id="Comments">
<?php if (!$all_comments) {
echo 'No comments yet.';
} ?>
<?php foreach ($all_comments as $c) { ?>
<div class="comment">
<input class="id" type="hidden" value="<?php echo $c->get_id(); ?>" />
<div class="author">Posted by <?php echo $c->get_user(); ?></div>
<div class="comment-text">
Posted <?php echo $c->get_dateTimePosted(); ?>
<p><?php echo $c->get_commentText(); ?></p>
</div>
</div>
<?php } ?>
</div>
<div id="AddComment">
<form name="add_comment_form" id="add_comment_form" action="index.php" method="post">
<label for="user">Your Name:</label>
<input name="user" id="user" type="text" /><br />
<label for="comment_text">Comment:</label>
<textarea name="comment_text" id="comment_text" rows="5" cols="10"></textarea><br />
<input name="submit" id="submit" type="submit" value="Submit" />
<input id="reset" type="reset" class="hidden" />
</form>
</div>
<div class="loader"></div>
<div class="response"></div>
</div>
</body>
Comments can be added, the data is stored fine in the database, and the loop runs the correct number of times, but the code such as echo $c->get_commentText(); is not displaying a value.
Appreciate any help.
Looks like you're using mysqli.
You're forgetting a key step: binding your result variables.
See http://www.php.net/manual/en/mysqli-stmt.bind-result.php and the examples there for more info on how to get actual values back.
try a
var_dump($all_comments)
after you fetch it, to prove that there is actually something in the array
next step would be to check that the sql worked. I am not sure what database layer you are using so i'm not sure what the check to do that would be.
i would assume that this method should have a return value you can check
$stmt->execute();