Searching, $_POST variable - php

I have this code block in html for inputting the search.
<?php echo form_open('bookstore/_searchbook'); ?>
<table>
<tr>
<td>
<label for="searchid">Search:</label>
</td>
<td>
<input type="text" size="15" name="searchid" />
</td>
</tr>
<tr>
<td>
<label for="searchtype">Type:</label>
</td>
<td>
<select>
<option value="book_id">Id</option>
<option value="book_author">Author</option>
<option value="book_name">Title</option>
</select>
</td>
</tr>
<tr>
<input type="submit" value="Search" />
</tr>
</table>
<?php echo form_close(); ?>
And i have this on my controller,
public function booksearch()
{
if($_POST['submit'])
{
$col= $this->input->post('searchtype', TRUE);
$val= $this->input->post('searchval', TRUE);
$data['book'] = $this->books_model->showbook($col,$val);
$this->load->view('showbooks',$data);
}
}
and this would be my model
public function showbook($col, $searchid)
{
$this->db->select()->from('books')->where(array($col=>$searchid));
$query=$this->db->get();
return $query->first_row('array');
}
Further info on my view,
I have this to print the results of my search.
<table cellpadding='5'>
<th>Book ID</th>
<th>Title</th>
<th>Author</th>
<th>Released Year</th>
<th>ISBN</th>
<?php
if(isset($books)) : foreach($books as $book) :
?>
<tr>
<td><?php echo $book['book_id'] ?></td>
<td><?php echo $book['book_name'] ?></td>
<td><?php echo $book['book_author'] ?></td>
<td><?php echo $book['book_year'] ?></td>
<td><?php echo $book['book_isbn'] ?></td>
</tr>
<?php
endforeach;
?>
<?php
else :
?>
<h5>No records</h5>
<?php
endif;
?>
</table>
It returns nothing so all i see is no records. Someone direct me to the thing i did wrong.

Your form's action (view) is _searchbook while your controller function is booksearch
Your submit input needs a name attribute
in the controller function you have $data['book'] while in your view (in the foreach loop) you reference that variable as $books
Model: you need to select at least something; e.g. $this->db->select('*')->from('books')->where(array($col=>$searchid)); instead of $this->db->select()
Model: I think you need return $query->result_array(); instead of $query->first_row('array')

Because your submit button has not got any name attribute. Instead of if($_POST['submit']) write $this->input->post(null)

Try adding global $_POST; to the top of your function. In php all variables used(declaired) in a function will be private unless you tell it otherwise by adding it to the global statement in the function.
public function booksearch()
{
global $_POST;
if($_POST['submit'])
{
$col= $this->input->post('searchtype', TRUE);
$val= $this->input->post('searchval', TRUE);
return $data['book'] = $this->books_model->showbook($col,$val);
}
}

Related

Echoing nested JSON into PHP

I have a JSON feed which I am parsing via PHP. I am having issues getting some nested elements to echo which I would appreciate some assistance on.. I've looked at loads of related posts here but cant seem to get the logic to work on my specific JSON feed. Could someone advise what I am doing wrong?
JSON feed is here > https://api.lever.co/v0/postings/leverdemo?skip=1&limit=3&mode=json
The elements, I am struggling to parse are the "categories" parent and child nodes of "team", "location" and "commitment".
I was thinking this would work - but it does not...
<?php
$url = 'feed.json';
$data = file_get_contents($url);
$characters = json_decode($data, true);
?>
<table>
<tbody>
<tr>
<th>Job title</th>
<th>Team</th>
<th>Location</th>
<th>Commitment</th>
<th>DescriptionPlain</th>
<th>applyUrl</th>
</tr>
<?php foreach ($characters as $character) : ?>
<tr>
<td> <?php echo $character['text']; ?> </td>
<td> <?php echo $character['categories'][2]['team'] ?></td>
<td> <?php echo $character['categories'][2]->team ?></td>
<td> <?php echo $character['categories'][1]->location ?></td>
<td> <?php echo $character['categories'][0]->commitment ?></td>
<td> <?php echo $character['descriptionPlain']; ?> </td>
<td> <?php echo $character['applyUrl']; ?> </td>
</tr>
<?php endforeach; ?>
</tbody>
Note, its just the categories children that fail to echo? Also noticed that if I use the full url in the $url variable it all fails? But from local it works??
Any ideas??? Thanks!
It should be:
<td> <?php echo $character['categories']["team"] ?></td>
<td> <?php echo $character['categories']["location"] ?></td>
<td> <?php echo $character['categories']["commitment"] ?></td>
instead. The numeric keys are not present on the array in the data. Also "categories" is not an object, so you cannot use the arrow (->) notation.
EDIT
You get an error because you are trying to access an object, actually you have an array, here is the solution hope it helps :
<?php
$url = 'https://api.lever.co/v0/postings/leverdemo?skip=1&limit=3&mode=json';
$data = file_get_contents($url);
$characters = json_decode($data, true);
$nb = count($characters);
?>
<table>
<tbody>
<tr>
<th>Job title</th>
<th>Team</th>
<th>Location</th>
<th>Commitment</th>
<th>DescriptionPlain</th>
<th>applyUrl</th>
</tr>
<?php while($nb > 0){
$nb--;
$nb_lists = count($characters[$nb]['lists']);
?>
<tr>
<?php
while($nb_lists > 0){
$nb_lists--;
?>
<td> <?php if(isset($characters[$nb]['lists'][$nb_lists]['text'])){ echo $characters[$nb]['lists'][$nb_lists]['text'];} ?> </td>
<?php } ?>
<td> <?php if(isset($characters[$nb]['categories']['team'])){echo $characters[$nb]['categories']['team'];} ?></td>
<td> <?php if(isset($characters[$nb]['categories']['team'])){echo $characters[$nb]['categories']['team'];} ?></td>
<td> <?php if(isset($characters[$nb]['categories']['location'])) {echo $characters[$nb]['categories']['location'];} ?></td>
<td> <?php if(isset($characters[$nb]['categories']['commitment'])){ echo $characters[$nb]['categories']['commitment'];} ?></td>
<td> <?php if(isset($characters[$nb]['descriptionPlain'])){echo $characters[$nb]['descriptionPlain']; }?> </td>
<td> <?php if(isset($characters[$nb]['applyUrl'])){echo $characters[$nb]['applyUrl'];} ?> </td>
</tr>
<?php } ?>
</tbody>

I am not able to get data from model in codeigniter

Model
//returns an array having different arrays inside it with keys id ,name and thumbnail taken from the database
function m_get_thumbnails($category){
$this->db->select('id,name,thumbnail');
$this->db->where('category',$category);
$query=$this->db->get('food');
if($query->num_rows()>0)
{
$count =0;
$arr = array();
foreach ($query->result() as $row)
{
$arr[$count++] = array(
'id'=>$row->id,
'name'=>$row->name,
'thumbnail'=>$row->thumbnail
);
}
return $arr;
}
}
function in controller
After that i place the result in an array and pass the array to my view.
function index_food()
{
$data['cafe'] = $this->mlocus->m_get_thumbnails('cafe');
$this->load->view('food.php',$data);
}
View
<script>alert(<?php $cafe[1]; ?>);</script>
//this alert is coming blank.......
Controller:
function index_food()
{
$data['cafe'] = $this->mlocus->m_get_thumbnails('cafe');
$this->load->view('food',$data);
}
In Model
function m_get_thumbnails($category)
{
$this->db->select('id,name,thumbnail');
$this->db->where('category',$category);
$query=$this->db->get('food');
$result = $query->result_array();
return $result;
}
In your View
<table>
<tr>
<td>ID</td>
<td>Name</td>
<td>Thumbnail</td>
</tr>
<?php
if(!empty($cafe)) {
foreach($cafe as $c){
?>
<tr>
<td> <?php echo $c['id']?> </td>
<td> <?php echo $c['name']?> </td>
<td><img src="<?php echo $c['thumbnail']?>" /></td>
</tr>
<?php } } else { ?>
<tr><td colspan="3">No record found.</td></tr>
<?php } ?>
</table>
Simplify your function in Model
function m_get_thumbnails($category)
{
$this->db->select('id,name,thumbnail');
$this->db->where('category',$category);
$query=$this->db->get('food')->result_array();
return $query;
}
In your View
<table>
<tr>
<td>ID</td>
<td>Name</td>
<td>Thumbnail</td>
</tr>
<?php for($i=0;$i<count($cafe);$i++){?>
<tr>
<td> <?php echo $cafe[$i]['id']?> </td>
<td> <?php echo $cafe[$i]['name']?> </td>
<td> <?php echo $cafe[$i]['thumbnail']?> </td> <!-- Use <img> if you have a url -->
</tr>
<?php }?>
</table>

How to create URL link in search result using Codeigniter?

I have already created an search function in Codeigniter and its working properly. The search function shows exactly what I want but I want the result to be link to another page. I am new to Codeigniter. Can somebody please help me?
Here is my Model
public function search($searchterm)
{
$sql = "SELECT title as title, author as author
FROM `edubooks`
WHERE title LIKE '$searchterm' OR author LIKE '$searchterm'";
$q = $this->db->query($sql);
if($q->num_rows() > 0)
{
foreach($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
else
{
return 0;
}
}
/******************Handler for search******************/
public function searchterm_handler($searchterm)
{
if($searchterm)
{
$this->session->set_userdata('searchterm', $searchterm);
return $searchterm;
}
elseif($this->session->userdata('searchterm'))
{
$searchterm = $this->session->userdata('searchterm');
return $searchterm;
}
else
{
$searchterm ="";
return $searchterm;
}
}
Controller
public function search()
{
$searchterm = $this->search_model->searchterm_handler($this->input->get_post('searchterm', TRUE));
$data['results'] = $this->search_model->search($searchterm);
$data['searchterm'] = $searchterm;
$this->load->view('search',$data);
}
and my view
<h2>Library Search System</h2>
<div id="formborder">
<form action ="search" method="post" id="searchform" name="searchform">
<b> Name of book : </b><input type="text" name="searchterm" id="searchterm" value="<?=$searchterm?>" />
<input type="submit" value="search" id="submit" />
</form>
</div>
<div id="tablebody">
<table id="table" width="100%" = border>
<?php if($results == false):?>
<tr>
<td>No records found.</td>
</tr>
<?php else:?>
<tr>
<th>Title</th>
<th>Author</th>
</tr>
<?php foreach($results as $r):?>
<tr>
<td align="center"><?php echo ($r->title); ?></td>
<td align="center"><?php echo ($r->author); ?></td>
</tr>
<?php endforeach;?>
<?php endif;?>
</table>
</div>
<p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds</p>
I just want the result to go another page.
if you want a link per each result to redirect you to another pge, you have to place that new page's URL in the href of your anchor tag, just like any
HTML link. I realize you have a table, what I would do is create another column with a "learn more" link.
So in your case, change this:
<?php foreach($results as $r):?>
<tr>
<td align="center"><?php echo ($r->title); ?></td>
<td align="center"><?php echo ($r->author); ?></td>
</tr>
<?php endforeach;?>
To this:
<?php foreach($results as $r):?>
<tr>
<td align="center"><?= $r->title; ?></td>
<td align="center"><= $r->author; ?></td>
<td align="center">Learn More</td>
</tr>
<?php endforeach;?>
the anchor now looks like this:
<?= base_url()?>controller_name/controller_method/$r->id
which you would want to change to the method name of your choice, perhaps something like this:
<?= base_url()?>books/about/$r->id
^ ^ ^
| | |
| | parameter
| method
controller
it will redirect to that specific controller method passing the id of your book as a parameter. your job now is to build that method so that you can retrieve that specific book by id and parse it to a view.

Pull and update data from database in PHP CodeIgniter foreach loop

I have a view which contains the data which is displayed from the database by a foreach loop and i want is to get the data which is edited from the view and update it in the database one by one but the problem is that database will be updated if there is a where clause but in my case i don't know how to get the key(tid) from view to controller here is the controller function which displays the data
public function bulk()
{
$pid = '';
if($this->input->post('pid'))
$pid = $this->input->post('pid');
$template['menu'] = $this->shared_model->get_flightmenus();
if($pid == '')
{
if($this->uri->segment(3))
$pid = $this->uri->segment(3);
else
$pid = $template['menu'][0]['tid'];
}
$template['pid'] = $pid;
// echo $pid;
// exit();
$template['airline'] = $this->shared_model->get_records('eat_airline');
$template['terminal'] = $this->shared_model->get_records('eat_terminal');
$template['data'] = $this->shared_model->get_recordbyvalue('eat_flight','menu_tid = '.$pid);
$template['main_content'] = $this->load->view('flight/flight_bulk_view', $template, true);
$this->load->view('includes/template', $template);
}
here is the view
<h4><?php echo anchor('login/logout', 'Logout'); ?></h4>
<?php echo anchor('/home', 'Home'); ?>/Flights
<h2>Flights</h2>
<div>
<?php echo form_open('/flight/') ?>
<?php foreach($menu as $row){ $options[$row['tid']] = $row['m_name']; } ?>
<?php $js = 'name="pid" id="pid" onChange="this.form.submit();"'; ?>
<?php echo form_dropdown('pid', $options, $pid, $js); ?>
<?php echo form_close(); ?>
</div>
<?php echo anchor('/flight/display/1/0/'.$pid, 'Create'); ?>
<?php echo anchor('flight/bulk', 'Bulk Update'); ?>
<table>
<tr>
<td>
Name
</td>
<td>
Airline
</td>
<td>
From
</td>
<td>
Stopover
</td>
<td>
Destination
</td>
<td>
Price
</td>
<td>
Unit
</td>
<td>
Tax
</td>
<td>
Protection
</td>
<td>
Fare
</td>
<td>
Week Offer
</td>
<td>
Menu
</td>
<td>
Sort
</td>
<td>
Edit
</td>
<td>
Delete
</td>
</tr>
<?php foreach($data as $row){ ?>
<tr>
<td>
<?php echo $row['f_name'] ?>
</td>
<td>
<?php $options1[0] = ''; foreach($airline as $row1){ $options[$row1['tid']] = $row1['a_name']; } ?>
<?php echo $options[$row['airline_tid']]; ?>
</td>
<td>
<?php $options1[0] = ''; foreach($terminal as $row1){ $options[$row1['tid']] = $row1['t_name']; } ?>
<?php echo $options[$row['terminal_from_tid']]; ?>
</td>
<td>
<?php echo $row['t_stopover'] ?>
</td>
<td>
<?php $options1[0] = ''; foreach($terminal as $row1){ $options[$row1['tid']] = $row1['t_name']; } ?>
<?php echo $options[$row['terminal_destination_tid']]; ?>
</td>
<td>
<?php echo $row['f_price'] ?>
</td>
<td>
<?php echo $row['f_unit'] ?>
</td>
<td>
<?php if($row['f_tax']>0) echo 'Yes'; else echo 'No'; ?>
</td>
<td>
<?php echo $row['f_protection'] ?>
</td>
<td>
<?php echo $row['f_fare'] ?>
</td>
<td>
<?php if($row['f_weekoffer']>0) echo 'Yes'; else echo 'No'; ?>
</td>
<!--
<td>
<?php $options[0] = ''; foreach($menu as $row1){ $options[$row1['tid']] = $row1['m_name']; } ?>
<?php echo $options[$row['menu_tid']]; ?>
</td>
-->
<td>
<?php echo $row['sortindex'] ?>
</td>
<td>
<?php echo anchor('flight/display/2/'.$row['tid'].'/'.$pid, 'Edit'); ?>
</td>
<td>
<?php echo anchor('flight/display/3/'.$row['tid'].'/'.$pid, 'Delete'); ?>
</td>
</tr>
<?php } ?>
</table>
i am unable to come up with the logic of how it will be done
any help will be appreciated
all i can see is that you want to pass the data from your view to controller you can do that by passing your data to url and then use it from the controller for future use.
You are getting values from DB row by row. Each row in your database has a unique ID (hopefully). That is your main criteria for the WHERE clause.
I don't see any inputs in your HTML, so I don't really understand how you are saving the data, but you can either do a hidden input in each row like <input type="hidden" id="[your_row_id_from_DB]" /> or if you have multiple inputs per row - add a name with id appended to it, like <input type="text" name="flight_your_row_id" /> . That way you can parse your names and know which values are submitted.

loop through form

I have a couple of problems. I'm creating a form inside a table, from what I understand this is not a good idea. But because of the loop I want to make sure the table header is outside so it doesn't repeat. Is there a smarter way to do this?
Also more importantly I can't seem to get the delete button to remove the correct video. It seems to delete the last one in the list. Something wrong with how I'm looping over this?
<p>
<h3>Recorded Videos</h3>
<table id="webcam-table">
<thead>
<tr>
<td>Camera Name</td>
<td>Video Size</td>
<td>Date Created</td>
<td>Video Length</td>
<td>Video Options</td>
</tr>
</thead>
for($i=0;$i<$num_videos;$i++)
{
<form action="<?php htmlentities($_SERVER['PHP_SELF']);?>" method="POST">
<input type="hidden" name="video_id" value="<?php echo $result_videos[$i]["video_id"]; ?>" />
<tbody>
<tr>
<td>
<?php echo $result_videos[$i]["camera_name"]; ?>
</td>
<td>
<?php echo $result_videos[$i]["video_size"]; ?>
</td>
<td>
<?php echo $result_videos[$i]["video_datetime"]; ?>
</td>
<td>
<?php echo $result_videos[$i]["video_length"]; ?>
</td>
<td>
<input type="submit" name="delete_video" value="Delete" onClick="javascript:return confirm('Delete this video?');"/>
</td>
</tr>
</tbody>
}
echo "</table>";
echo "</form>";
echo "</p>";
}
}
if (isset($_POST['delete_video'])) {
$video_id = $_POST['video_id'];
$query_delete_video = 'DELETE FROM `#__videos` WHERE `video_id`='.$video_id;
$db->setQuery($query_delete_video);
$db->query();
header("location: " . $_SERVER['REQUEST_URI']);
In your loop you are creating the 'form' tag. However you are not closing it each time. This is causing your deleting problem.
Move
echo "</form>";
Inside the loop.
looks good to me, the only issue I see is that the tag should be outside the loop (opening before, closing after).
Revised code
<?
if (isset($_POST['delete_video']))
{
$video_id = $_POST['video_id'];
$query_delete_video = 'DELETE FROM `#__videos` WHERE `video_id`='.$video_id;
$db->setQuery($query_delete_video);
$db->query();
header("location: " . $_SERVER['REQUEST_URI']); //you should not allow things to be echoed before a header()
}
?>
<script type="text/javascript">
function onMySubmit(video_id)
{
document.myform.video_id.value = video_id;
return confirm('Delete this video?');
}
</script>
<p>
<h3>Recorded Videos</h3>
<!-- you had <?php htmlentities(...) ?>, you should have had
<?php echo htmlentities(...) ?> or <?= ... ?> -->
<form name="myform" action="<?= htmlentities($_SERVER['PHP_SELF']);?>" method="POST">
<input type="hidden" name="video_id" value="" />
<table id="webcam-table">
<thead>
<tr>
<td>Camera Name</td>
<td>Video Size</td>
<td>Date Created</td>
<td>Video Length</td>
<td>Video Options</td>
</tr>
</thead>
<tbody>
<? for($i=0;$i < $num_videos;$i++) { ?>
<tr>
<td><?= $result_videos[$i]["camera_name"]; ?></td>
<td><?= $result_videos[$i]["video_size"]; ?></td>
<td><?= $result_videos[$i]["video_datetime"]; ?></td>
<td><?= $result_videos[$i]["video_length"]; ?></td>
<td><input type="submit" name="delete_video" value="Delete" onClick="javascript:return onMySubmit(<?=$result_videos[$i]["video_id"];?>);"/></td>
</tr>
<? } ?>
</tbody>
</table>
</form>
</p>

Categories