Search data from database - php

I want to display data from database. I created a search form but there is an error to display the result. Attached screenshot of the error.
In the database, consist of staff name and branch. The branch dropdown list, I get it from the database. Example of branch is Faculty Computer Science and Mathematics.
I think the error is in the model.
Can someone help me to fix my code
CONTROLLER
function filter_directory()
{
$search_term = $this->input->post('search_term');
$search_branch = $this->input->post('search_branch');
$data['search_term'] = $search_term;
$data['search_branch'] = $search_branch;
$data['branch_name'] = $this->direktori_model->get_branch_list();
$data['search_term'] = $this->input->get('search_term');
$data['search_branch'] =$this->input->get('search_branch');
$data['results'] = $this->direktori_model->get_directory_results($data['search_term'], $data['search_branch'], $config['per_page'], $page);
$this->load->view('directory/directory_list', $data);
}
MODEL
function get_directory_results($search_term, $search_branch, $limit=10, $offset=0)
{
$sql = "SELECT * FROM Staff_Profile
WHERE Name LIKE '%$search_term%'
AND Branch = {$search_branch}
AND Enabled = 'Y'
AND Lang ='BM'
ORDER BY ID ASC
OFFSET {$offset} ROWS
FETCH NEXT {$limit} ROWS ONlY";
$query = $this->db->query($sql);
return $query->result();
}
VIEW
<?php echo validation_errors();?>
<?php echo form_open("direktori/filter_directory", array('method' => 'get'));?>
<div class="row collapse">
<div class="medium-4 columns ">
<?php echo form_input(array('name' => 'search_term', 'id' => 'search-box', 'value' => $search_term)); ?>
</div>
<div class="medium-4 columns ">
<?php echo form_dropdown("search_branch", $branch_name, "", 'id="branch_id"');?>
</div>
<div class="medium-4 columns ">
<?php echo form_submit('search', 'SEARCH', 'class="button expand"'); ?>
</div>
</div>
<?php echo form_close(); ?>

In your query you must add quote after BRANCH
Your query:
SELECT * FROM staff_profile
where name Like '%anuar%'
and branch = BAHAGIAN KEWAIGAN & PENGURUSAN <-- ERROR
and enabled = 'Y' and lang = 'BM'
order by id asc offset o rows fetch next 10 rows only
Fixed query:
SELECT * FROM staff_profile
where name Like '%anuar%'
and branch = 'BAHAGIAN KEWAIGAN & PENGURUSAN'
and enabled = 'Y' and lang = 'BM'
order by id asc offset o rows fetch next 10 rows only

Error come in near branch. please put branch inside quotes.
$sql = "SELECT * FROM Staff_Profile
WHERE Name LIKE '%$search_term%'
AND Branch = '$search_branch'
AND Enabled = 'Y'
AND Lang ='BM'
ORDER BY ID ASC
OFFSET {$offset} ROWS
FETCH NEXT {$limit} ROWS ONlY";

use codeigniter syntax in the model
function get_directory_results($search_term, $search_branch, $limit=10, $offset=0){
$this->db->order_by('ID','ASC');
$this->db->like('Name',$search_term);
$this->db->where('Lang','BM');
$this->db->where('Enabled','Y');
$this->db->where('Branch',$search_term);
$query=$this->db->get('Staff_Profile',$limit,$offset);
return $query->result();
}
in this format you could port to any other BD and show you more easy the troubles that you have.

Related

How to Show row number for every row fetched from mysql

I want to show row number for every row fetched from database. can someone help me to do this.
My Code to fetch rows is:
$query="
select id
, title
, description
, url,votes
from posts
order
by votes desc
";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$arr = array();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$arr[] = $row;
}
}
# JSON-encode the response
$json_response = json_encode($arr);
// # Return the response
echo $json_response;
My code displays post, title, post votes and post controls (Vote up or Down).
I want to show row number for every row fetched.
My Code to Display posts is:
<ul class="thumbnails" ng-controller="votingCtrl">
<li ng-repeat="post in posts" class="clearfix">
<div class="col-md-1 voting well">
<div class="votingButton" ng-click="upVote(post);">
<i class="glyphicon glyphicon-chevron-up"></i>
</div>
<div class="badge badge-inverse">
<div>{{post.votes}}</div>
</div>
<div class="votingButton" ng-click="downVote(post);">
<i class="glyphicon glyphicon-chevron-down"></i>
</div>
</div>
<div class="well col-md-11">
<h4>{{post.title}}</h4>
<p>{{post.description}}</p>
</div>
</li>
</ul>
Thanks
try to use ROW_NUMBER() mysql function
select id,title,description,url,votes, ROW_NUMBER() OVER (ORDER BY votes DESC) as row_num from posts order by votes desc
With the current logic, row number can be displayed using {{post.id}} as the SELECT query fetches id along with votes as fields.
In the loop itself, we can display a custom counter like:
$arr = array();
$cntr = 0;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
++$cntr;
$row['cntr'] = $cntr;
$arr[] = $row;
}
}
And in view template, you can use {{post.cntr}}.
SELECT
(#row_number:=#row_number + 1) AS num,
id,
title
FROM
Test,
(SELECT #row_number:=0) AS t
LIMIT 5;
Please try above its tested it will work, only need to replace your query with that.

Getting linked data from multiple tables into seperate bootstrap cards

I very recently (as in, this week) started learning PHP and am doing a practice task.
(Therefore, apologies in advance, if I sound like I don't know what I'm talking about, that is true)
Here is a crude schematic of my tables:
I have a main table products, and there are 3 planned product types (book, disc, furniture), and each type has a special attribute, with their own tables. (size for discs, weight for books etc.)
So far through testing, I've managed to query out the object from my products table each into their separate bootstrap card components. What I am trying to accomplish now is to add the special attributes to their respective object cards.
This is where i've reached a dead end. The idea I have is to first create a seperate array $printtocard, then call all the products table records by type, then run a foreach through all the found records, and then run a switch inside the foreach where i check the product types and run cases based on type, which create new objects based on the linked table data, and add each of them to the $printtocard array.
Afterwards the plan is to call the array in the code that later outputs the objects.
Here is my code so far:
Main php code
class products {
var $arrayy;
var $sql;
var $typepr;
protected function get_prod($conn1){
$printtocard = array();
$call_type = 'SELECT type FROM products ORDER BY id';
$type_res = mysqli_query($conn1, $call_type);
$type_arr = mysqli_fetch_all($type_res, MYSQLI_ASSOC);
$this->typepr = $type_arr;
return $this->typepr;
foreach($typepr as $xxx){
switch($xxx){
case "disc":
/* $disc_ */$sql = 'SELECT p.sku, p.name, p.price, a.value FROM products AS p INNER JOIN attr_size AS a ON p.id = a.product_id;';
$val_res = mysqli_query($conn1, $sql);
$val_arr = mysqli_fetch_all($val_res, MYSQLI_ASSOC);
$printtocard[] = $val_arr;
return $this->printtocard;
break;
case "book":
/* $book_ */$sql = 'SELECT p.sku, p.name, p.price, a.value FROM products AS p INNER JOIN attr_weight AS a ON p.id = a.product_id;';
$val_res = mysqli_query($conn1, $sql);
$val_arr = mysqli_fetch_all($val_res, MYSQLI_ASSOC);
$printtocard[] = $val_arr;
return $this->printtocard;
break;
case "furniture":
/* $furniture_ */$sql = 'SELECT p.sku, p.name, p.price, a.height, a.width, a.length, FROM products AS p INNER JOIN attr_dims AS a ON p.id = a.product_id';
$val_res = mysqli_query($conn1, $sql);
$val_arr = mysqli_fetch_all($val_res, MYSQLI_ASSOC);
$printtocard[] = $val_arr;
return $this->printtocard;
break;
}
}
//$sql = 'SELECT p.sku, p.name, p.price, a.value FROM products AS p INNER JOIN attr_size AS a ON p.id = a.product_id;';
//$call2 = 'SELECT sku, name, price FROM products ORDER BY id';
//$val_res = mysqli_query($conn1, $sql);
//$val_arr = mysqli_fetch_all($val_res, MYSQLI_ASSOC);
$this->arrayy = $printtocard;
return $this->arrayy;
}
public function get_prod2($conn1)
{
$this->get_prod($conn1);
}
}
$fff= new products;
$fff->get_prod2($conn);
$sss= $fff->arrayy;
Snippet of the webpage code where I autogenerate the cards:
<div class="container">
<div class="row">
<?php
foreach($sss as $value){ ?>
<div class="col s6 md2">
<div class="card cardstyle z-depth-0">
<div class="card-content center">
<?php echo htmlspecialchars($value['sku']); ?>
<div>
<?php echo htmlspecialchars($value['name']); ?>
</div>
<div>
<?php echo htmlspecialchars($value['price']); ?>
</div>
<div>
<?php echo htmlspecialchars($value['value']); ?>
</div>
</div>
<div class="card-action right-align">
<a class="brand-text" href="#"> more info </a>
</div>
</div>
</div>
<?php } ?>
</div>
</div>
The error message I currently get:
Warning
: Invalid argument supplied for foreach() in
C:\xampp\htdocs\uzdevumi\scandi_uzdevumi_kristianskonters\productlist\productlist.php
on line
108
A number of pointers
1. Its better to define your variables at the top depending on your intentions later (protected, private or public)
protected $arrayy;
protected $sql;
protected $typepr;
The return just before your "foreach" loop renders your loop pointless because it stops your function there and returns what you have.
return $this->typepr;
In connection to my previous point, you seem to think that "return" does some concatenation for you as shown by each "case" you have in your switch. No it does not it exits your function back to the calling scope.
return $this->printtocard;
The warning you have at the end means what it says, you are providing the "foreach" loop with an invalid argument. In other words it does not exist, thankfully its php (dynamically typed). But the problem is its undefined (has not value). Maybe its a typo and you wanted to loop through the array variable you got from sql calls.
foreach($typepr as $xxx)
Cross check typos and I did not get to check your html.

How to print list in opposite direction?

My question is by default list print in top to bottom direction but I want to print in bottom to top direction which means first value should be at bottom and last value on top.
<?php
$query="select name from plant ";
$q=mysqli_query($con,$query)or die("Could Not Perform the Query");
$hh = '';
while ($row = $q->fetch_assoc())
{
$hh .= '<li>' . $row['name'] . '</li>';
}
?>
<ul id="myUL">
<?php echo $hh; ?>
</ul>
By default it will print:-
Mango
Apple
Grape
But I want:-
Grape
Apple
Mango
If you want to customize the order of results by select query you must create an additional field on the table where you define the order of the single element, after that you can use the select statement and order them by new field.
For example, you have theese columns on the table:
id, name, order_column, created_at
and you have 3 records on this table:
1, pippo, 1, 2019-02-10
2, pluto, 5, 2019-02-10
3, topolino, 3, 2019-02-10
where the third column is the order of element on the column, if you want to order by its you should use a query like this
select name from table_name order by order_column ASC
or
select name from table_name order by order_column DESC
that's it!
You should handle sorting with SQL query but you can also achieve this in PHP. Save the result into an array and reverse the order of rendering.
<?php
$plants = array();
while( $row = $q->fetch_assoc() ) {
$plants = $row['name'];
}
$index = count( $plants );
?>
<ul id="myUL">
<?php while( $index ) { ?>
<li><?php echo $plants[--$index]; ?></li>
<?php } ?>
</ul>
You can also try array_reverse.
This is quite simple. Sort your query results in descending order:
select name from plant order by name desc

Php grouping select query

So I have persons associated with publications
My current query is this:
$query = "SELECT confAuth.personid, publicationconf.title FROM confAuth INNER JOIN publicationconf ON publicationconf.conferenceid = confAuth.conferenceid GROUP BY publicationconf.conferenceid";
It does group by conference id but only one person id is diplayed for each entry. Obviously, what I need is to display all person id's
Thanks in advance.
As a classmate just noted, this is our print statement and it is probably wrong. Any input to this.
$result = $conn->query($query);
$rows = $result->num_rows;
if ($rows > 0)
{
for($i=0; $i<$rows; $i++)
{
if($row = $result->fetch_assoc())
{
?>
<div class="row">
<div class="col-md-10">
<p><?php echo $row["personid"] . ", " . $row["title"]?></p>
Use group_concat(confAuth.personid) to get a comma delimited list of all values in the grouped set.
However, since you are wanting one line item per personid/title combo, add the personid and the title to the group by clause.
Also, consider table aliases for readability.
$query = "SELECT ca.personid, pc.title
FROM confAuth ca
INNER JOIN publicationconf pc ON pc.conferenceid = ca.conferenceid
GROUP BY pc.conferenceid, ca.personid, pc.title";

numbering an output in order

i have made a image slider(or what ever you want to call it) and it displays the 6 latest images. Under the current bigger image you have all 6 of the most recent images , and the process works all fine but when you click the smaller image, it doesn't bring up the big image straight away. Because the very latest image is first its 'active' and has its own <a href="#1> and so the href="#1" is entered as i can manipulate the a tag as it is there. But as i used a foreach to bring up the next 5 images from 2nd to 6th in descending order from date submitted, i cant give each individual result there own href"#number" so they can link up with the bigger images, is there a way to assign each result a number by taking what position it sits within the query then adding 1or2 to the answer which would then give the corresponding number in the href so when clicked, the larger image which is linked to the href number too, it will make the larger image appear straight away.
the code from the tutorial that i have amended looks like this ..
<?php
$latest_headlines = get_latest_headlines();
foreach ($latest_headlines as $latest_headline) {
?>
<img src="img/<?php echo $latest_headline['img_title'].'.'.$latest_headline['img_ext']; ?>" class="nav-thumb" alt="<?php echo $latest_headline['title']; ?>" />
<?php
}
?>
<div id="movers-row">
<?php
$recent_headlines = get_recent_headlines();
foreach ($recent_headlines as $recent_headline) {
?>
<div><img src="img/<?php echo $recent_headline['img_title'].'.'.$recent_headline['img_ext']; ?>" class="nav-thumb" alt="<?php echo $recent_headline['title']; ?>" /></div>
<?php
}
?>
</div>
And here are my two functions to get the results, and before people start picking at all the problems ive done, just want to say this is the way ive learnt it im new, it maybe all wrong but its what stuck in my head to do things this way and its worked(ish) so far....
function get_recent_headlines() {
$sql = "SELECT *
FROM `story`
ORDER BY `submit_date` DESC
LIMIT 1, 5 ";
$result = mysql_query($sql) or die(mysql_error());
$recent_headlines = array();
while (($row = mysql_fetch_array($result)) !== false) {
$recent_headlines[] = array(
'title' => $row['title'],
'img_title' => $row['img_title'],
'img_ext' => $row['image_ext']
);
}
return $recent_headlines;
}
function get_latest_headlines() {
$sql = "SELECT *
FROM `story`
ORDER BY `submit_date` DESC
LIMIT 1 ";
$result = mysql_query($sql) or die(mysql_error());
$lastest_headlines = array();
while (($row = mysql_fetch_array($result)) !== false) {
$latest_headlines[] = array(
'title' => $row['title'],
'img_title' => $row['img_title'],
'img_ext' => $row['image_ext']
);
}
return $latest_headlines;
}
change your query of your function get_recent_headlines()
it uses a variable, and increment it in the SELECT statement:
`$sql = "SELECT *,(#row:=#row+1) AS rowno
FROM `story` inner join (SELECT #row:=0) AS row_count
ORDER BY `submit_date` DESC
LIMIT 1, 5 ";`
You can use a user variable to get a sequence number within MySQL.:-
SELECT Sub1.*,#aCount:=#aCount+1 AS aSequence
FROM (SELECT *
FROM `story`
ORDER BY `submit_date` DESC) Sub1
CROSS JOIN (SELECT #aCount := 0) Sub2
LIMIT 1, 5

Categories