CodeIgniter using if to show some table - php

So i am trying to make a website for collecting data from user and classify the data as 'suspicious' or 'not suspicious'. After i collect and classify the data, i want to show and send to server ONLY 'suspicious' data.
My table has one column called 'note', where the value of the 'note' is 'suspicious' or 'not suspicious'
is it possible to show the part of table that only have 'not suspicious' value in 'note' ? if possible, can you guys give me any idea how ?
Here is my code for showing the data:
Controller:
public function success() {
$dataz['resultss'] = $this->welcome_model->dataz();
$this->load->view('success',$dataz);
}
Model
public function dataz() {
$query = $this->db->get('info');
$results = $query->result();
return $resultss;
}
View
<?php
foreach($resultss as $row) {
echo '<tr>';
echo '<td>'.$row->name.'</td>';
echo '<td>'.$row->note.'</td>';
?>
<td>
</td>
<?php
echo '</tr>';
}
?>
Any help would be appreciated!

You can achieve your objective in many ways.
For 'not suspicious' records, use this,
$query = $this->db->get_where('info', array('note' => 'not suspicious'));
For 'suspicious' records, use this,
$query = $this->db->get_where('info', array('note' => 'suspicious'));

The method #Naga suggested is better but if you want to stick to your way and do it in view;
<?php
foreach($resultss as $row) {
if($row->note == 'not suspicious') {
echo '<tr>';
echo '<td>'.$row->name.'</td>';
echo '<td>'.$row->note.'</td>';
echo '<td></td>'; // why this extra td?
echo '</tr>';
}
}
?>

Related

not displaying result in codeigniter

i tried to use print_r($list) but the result array().There is no element in the array.I want to show data form my table.there is user table, job table and industry table.Can anybody suggest me where is mistake.
This is my model function get_data_by_query used in controller
public function get_data_by_query($qry)
{
$query = $this->db->query($qry);
return $query->result();
}
This is my controller where i am verifying email, phone number.
public function Dashboard()
{
if ($this->Common_model->Is_User_Logged())
{
$condition='';
$data['email_verified']=self::IsEmailVerified();
$data['phone_verified']=self::IsPhoneVerified();
$userdata=$this->session->userdata('user_logged_in');
$data['user_email']=$userdata['email'];
//print_r($data);
$res=$this->Common_model->get_data_by_query("SELECT * FROM user WHERE user_id={$userdata['id']} limit 1");
//print_r($res);
$data['user_skills'] = $res[0]->user_skills;
//print_r($data);
$arr = array($res[0]->user_skills);
//print_r($arr[0]);
//exit;
$condition.=" and FIND_IN_SET(job_title,'$arr[0]')";
print_r($condition);
$sql_get="SELECT j.*,j.job_industry,i.industry_title
FROM job j
LEFT JOIN industry i on i.industry_id=j.job_industry
WHERE job_status=1 ".$condition." ";
//print_r($sql_get);
$data['list']=$this->Common_model->get_data_by_query($sql_get);
//print_r($data['list']);
$data['user_phone']=$res[0]->user_mobile;
$this->load->view('user/header');
$this->load->view('user/home', $data);
$this->load->view('user/footer');
}
else
{
redirect('user');
}
}
This is my view
<?php
if(!empty($list)>0)
{
foreach ($list as $row)
{
?>
<tr>
<td><?php echo $row->job_role;?></td>
<td><?php echo $row->industry_title;?></td>
<td><?php echo $row->job_vacancy;?></td>
<td><?php echo $row->job_keyword;?></td>
<!--<td><?php echo $row->job_type;?></td>-->
</tr>
<?php
} }
?>
what is the reason that $list is empty array although i have data in my table. I will be thankful for you.
After a lot of effort, i found that there is no problem in above code. The problem is in tje SQL query. I am trying to resolve that query.

Codeigniter - How to create a form with undefined number of input?

So I've been trying to create an 'add' function for a contest table that is also linked to a joining table as the contest has many sport events associated to it (and a sport events will also be included in many contests). I have managed to create it as below, however it is limited to only adding one row into the joining table based on the chosen game in a dropdown.
So now, how do I go about creating the form if I don't know how many sport events there might be? How will the website create another dropdown if one dropdown is used so that more sport events can be selected? Similarly, how does the controller know that there are x amount of dropdowns selected, and hence x amount of rows to be added to the joining table?
I'm sorry if I am using incorrect or ambiguous terms to describe my problem. I have only started learning and creating websites recently.
Thank you.
UPDATE: I may have a solution per the updated codes below. However I am now stuck on the inserting into the database page. For some reason when I click submit, the next page loads but with no error and no rows inserted. Please help :)
View
<h1>Add New Contest</h1>
<?php
echo form_open('contests/add/');
?>
<?php
echo "<br />" "<br />"
echo "Contest Name";
$data = array( 'name' => 'contest_name',
'value' => set_value('contest_name'),
);
echo form_input($data);
echo "<br />" "<br />"
echo "Game";
?>
<div class="field_wrapper">
<div>
<select name="field_name[]">
<option value="" disabled selected>Select Game</option>
<?php
foreach($events_lists->result() as $row) {
$sports_events_id = $row->sports_events_id;
$sports_events_start_date = $row->sports_events_start_date;
$sports_events_start_time = $row->sports_events_start_time;
$home_team_shorthand = $row->home_team_shorthand;
$away_team_shorthand = $row->away_team_shorthand;
?>
<option value="<?php echo $sports_events_id; ?>"><?php echo $home_team_shorthand; ?> v <?php echo $away_team_shorthand; ?> - <?php echo $sports_events_start_date; ?> <?php echo $sports_events_start_time; ?></option>
<?php } ?>
</select>
<img src="add-icon.png"/>
</div>
</div>
<?php
echo "<br />" "<br />"
$data = array( 'value' => 'Add Contest',
'name' => 'submit',
'class' => 'submit-btn',
);
echo form_submit($data);
echo form_close();
?>
Controller
function add()
{
$league_id = $this->uri->segment(3);
$this->load->module('leagues');
$data['leagues_list'] = $this->leagues->get_where($league_id);
foreach ($data['leagues_list']->result() as $row) {
$league_insert_id = $row->id;
$this->load->module('sports_events');
$data['events_lists'] = $this->sports_events->get_events_list($league_insert_id);
}
if ($this->form_validation->run() == FALSE) {
$data['view_file'] = 'add_contest';
$this->load->module('template');
$this->template->cmslayout($data);
} else {
$data1 = array(
'contest_name' => $this->input->post('contest_name')
);
if(isset($_REQUEST['submit'])) {
$data2 = $_REQUEST['field_name'];
}
if ($this->_transactions_new_contest($data1, $data2)) {
return $query;
$this->session->set_flashdata('team_phase_created', 'The team phase has been set');
redirect('/contests/');
}
}
}
Model
function _transactions_new_contest($data1, $data2){
$this->db->trans_start();
$this->db->insert('contests', $data1);
$contest_id = $this->db->query('SELECT contests.id FROM contests ORDER BY contests.id DESC limit 1');
foreach ($contest_id->result() as $row) {
$contest_result_id = $row->id;
foreach($data2 as $value){
$this->db->query('INSERT INTO contests_has_sports_events (contests_id, sports_events_id) VALUES (' . $contest_result_id . ', ' . $value . ')');
} }
$this->db->trans_complete();
}

Instead of submit get data on entering page php

I use this snippet to get vehicle data from a external database:
<form method="post" action="<?php echo $_SERVER['REQUEST_URI'] ?>" class="vwe-kenteken-widget">
<p><input type="text" name="open_data_rdw_kenteken" value="<?php echo $_POST['open_data_rdw_kenteken'] ?>" maxlength="8"></p>
<p><input name="submit" type="submit" id="submit" value="<?php _e('Kenteken opzoeken', 'open_data_rdw') ?>"></p>
</form>
<?php if($data): ?>
<h3><?php _e('Voertuiggegevens', 'open_data_rdw') ?></h3>
<table>
<?php
$categories = array();
foreach ($data as $d) {
if( !is_array($fields) || in_array($d['name'], $fields) ) {
if( !in_array($d['category'], $categories) ) {
$categories[] = $d['category'];
echo '<tr class="open-rdw-header">';
echo '<td colspan="2" style="font-weight: bold;">';
echo ''.$d['category'].'';
echo '</td>';
echo '</tr>';
}
echo '<tr style="display:none">';
echo '<td>'.$d['label'].'</td>';
echo '<td>'.$d['value'].'</td>';
echo '</tr>';
}
}
?>
</table>
<?php endif; ?>
What i want to accomplish is that the data is loaded without the user have to enter a value and hit the submit button. The input value will get loaded based on the product page the user is viewing.
EDIT:
The data is loaded based on:
public function get_json() {
if ( isset( $_POST['kenteken'] ) ) {
$data = $this->rdw->get_formatted($_POST['kenteken']);
foreach ($data as $row) {
$json['result'][$row['name']] = $row['value'];
}
if ($_POST['kenteken']) {
if ($data[0]['value'] == '') {
$json['errors'] = __( 'No license plates found', 'open_data_rdw' );
}
else {
$json['errors'] = false;
}
}
else {
$json['errors'] = __( 'No license plate entered', 'open_data_rdw' );
}
header('Content-type: application/json');
echo json_encode($json);
die();
}
}
So instead of a $_POST action just get the data based on a pre-declared value that is different on each page.
Hard to answer - but I'll try to use my crystal ball.
$data comes from a database query, right?
I assume further, that the query takes the value from the open_data_rdw_kenteken form field to gather $data.
To have the table rendered, you have to fill $data with the right data. That implies that you must have a kind of default value for open_data_rdw_kenteken to get the data out of the DB. The default can be "all" which should reflect on your SQL Query or as your wrote "defined by product page".
Pseudo Code
$data = getData('BT-VP-41');
function getData($open_data_rdw_kenteken="")
{
$where = "";
if(!empty($open_data_rdw_kenteken)) {
$where = 'WHERE rdw_kenteken = "'.mysqli_real_escape_string($open_data_rdw_kenteken)';
}
$data = myslqi->query("SELECT * FROM dbTbl ".$where)
return $data;
}
As I wrote - this is pseudo code and will not run out of the box. You'll have to adapt that to your environment.
TL;DR: The line
<?php if($data): ?>
keeps you from rendering the table. To render you need $data filled with the right data.
Hope that will get you in the right direction.

CakePHP pagination not working beyond 1st page

I have a view in my site that has two divs. one houses a search box and the other is where the result of the search is shown. by default, nothing is loaded on the result div. only when there is a search via post request, the result div is populated. However, this is causing problem with the pagination functionality as the second time the page loads, it doesnt have the data to go around with listing the rest of the results. How can i modify my controller/view to meet this need?
My action in the controller:
public function search(){
if($this->request->is('post')){
if($this->request->data['User']['search']!=null){
$search_name=$this->request->data['User']['search'];
$this->Paginator->settings = array(
'conditions'=>array('User.name LIKE'=>'%'.$search_name.'%'),
'order' => array('User.datetime' => 'desc'),
'limit' => 10
);
$feed = $this->Paginator->paginate('User');
$this->set('search_result',$feed);
}
else{
$this->Session->setFlash(__("Cant make an empty search"));
return $this->redirect(array('action'=>'search'));
}
}
}
My View:
<?php
include 'header.ctp';
echo '<div id="feed">';
echo $this->Form->create(null, array('url' => array('controller' => 'users', 'action' => 'search')));
echo $this->Form->input('search');
echo $this->Form->end('Search');
echo 'search by name';
echo '</div>';
if(isset($search_result)){
echo '<div id="tweet_records">';
if(!empty($search_result)){
foreach ($search_result as $user) :
$formatted_text;
$latest_tweet_time;
$formatted_time;
if(!empty($user['Tweet'])){
$formatted_text=$this->Text->autoLinkUrls($user['Tweet']['0']['tweet']);
$latest_tweet_time=$user['Tweet']['0']['datetime'];
$formatted_time;
if(strlen($latest_tweet_time)!=0){
$formatted_time='Tweeted at '.$latest_tweet_time;
}
else{
$formatted_time='No tweets yet';
}
}
else if(empty($user['Tweet'])){
$formatted_text='No tweets yet';
$formatted_time='';
}
echo '<table id="t01">';
echo'<tr>';
echo '<td>'.
$user['User']['name'].'#'.$this->HTML->link($user['User']['username'], array('controller'=>'tweets','action'=>'profile',$user['User']['id'])).'<br>'.$formatted_text.' '.'<br>'.'<font color="blue">'.$formatted_time.'</font>';
echo '<div id="delete">';
$selector='true';
foreach ($user['Follower'] as $follower) :
if($follower['follower_user_id']==AuthComponent::user('id')){
$selector='false';
echo $this->Form->postlink('Unfollow',array('controller'=>'followers','action'=>'unfollow',$user['User']['id']),array('confirm'=>'Do you really want to unfollow this person?'));
}
endforeach;
if($selector=='true' & $user['User']['id']!=AuthComponent::user('id')){
echo $this->Form->postlink('Follow',array('controller'=>'followers','action'=>'follow',$user['User']['id']));
}
echo '</div>';
echo '</td>';
echo '</tr>';
endforeach;
echo'</table>';
echo 'Pages: ';
echo $this->Paginator->prev(
' < ',
array(),
null,
array('class' => 'prev disabled')
);
echo $this->Paginator->numbers();
echo $this->Paginator->next(
' > ' ,
array(),
null,
array('class' => 'next disabled')
);
}
else{
echo '<font color="red"> No results found </font>';
}
echo '</div>';
}
You are searching for results only on post request. But when you press the next button you are making a get request. So the first if statement doen't return true so you are not passing any data to your view.
Even if you remove the first if statement for post you'll still won't see any data because the next button doesn't post any data to make true the second statement.
PS:
On CakePHP include is not a preferable thing to do. Also you haven't mentioned the version you are using.

Getting multiple values out of a database using html/php multiple selector

I am trying to extract multiple values from a row in a table in a mysql database. I want the selector to show the description only, and after the form is submitted, I want to be able to access additional information from that row. I am able to get all of the item_types out into an array, but I am not sure how to add the item_id. I don't want item_id to show up in the html selector.
I tried a few things like array_push. The only way I can think of getting this done is by making one big string in "value" and extracting the parts after the form is submitted.
Here is the function so far:
function createDropdown() {
echo '<select multiple name="items[]">';
try {
$items = mysql_query("SELECT item_id,item_type FROM items");
while ($row = mysql_fetch_assoc($items)) {
echo '<option value="'.$row['item_type'].'"';
echo '>'. $row['item_type'] . '</option>'."\n";
}
}
catch(PDOException $e) {
echo 'No results';
}
echo '</select>';
}
Hmm you can try to generate a lookup table whenever you create a drop-down list:
function createDropdown(&$ddlLookup) {
echo '<select multiple name="items[]">';
try {
$items = mysql_query("SELECT item_id,item_type FROM items");
while ($row = mysql_fetch_assoc($items)) {
echo '<option value="'.$row['item_type'].'"';
echo '>'. $row['item_type'] . '</option>'."\n";
$ddlLookup[$item_type] = $item_id;
}
}
catch(PDOException $e) {
echo 'No results';
}
echo '</select>';
}
Then whenever you need the id for a given description you use that table(array) to get it:
$mainDropdownLUT = array();
createDropdown($mainDropdownLUT);
var_dump($mainDropdownLUT['testCow']);
-> 734
Also, if you need to pass it to another page it can be serialized and added to a hidden field.
$mainDropdownLUT = serialize($mainDropdownLUT);
"<input type="hidden" value =\"$mainDropdownLUT\">"
-------------------------**OTHER PAGE **--------------
$mainDropdownLUT = unserialize($mainDropdownLUT);

Categories