I am new to CodeIgniter and the HMVC framework and I am creating a sample test image dropdown in order to get a blueprint on how to solve the big project that I have on due this week. My question is, how can I able to search and display the filtered database values in a table format by using a dropdown list? For example, If I select on one of the values in the dropdown list and click search, all of the retrieved values will be filtered and will display according to the value selected in the dropdown list. Here is the code for the sample test code for the image dropdown:
Here is the code in my model:
class Image_model extends CI_Model{
function __construct(){
parent::__construct();
}
/*Sample test model function for the image dropdown list*/
//display the images table
public function displayTableImages()
{
$query = $this->db->select('main_image, main_image_url');
$query = $this->db->from('product_master');
$query = $this->db->get();
return $query->result();
}
//dropdown search list for images
public function searchDropdownImages($type)
{
switch ($type) {
case 'all':
{
$query = $this->db->where("main_image != '', 'main_image_url != ''");
}
case 'with-image':
{
$query = $this->db->where("'main_image != '', 'main_image_url != ''");
}
break;
case 'no-image':
{
$query = $this->db->where("'main_image = ''", "'main_image_url = ''");
}
break;
default:
$query = $this->db->select('main_image', 'main_image_url');
$query = $this->db->from('product_master');
break;
if ($query->num_rows()) {
return $query->result();
}
}
}
/*End sample test function*/
}
Here is the code for my controller:
if(! defined('BASEPATH')) exit('No direct script access allowed');
class Sample_image_dropdown extends MX_Controller{
public function __construct()
{
parent::__construct();
}
public function index()
{
$data['main_view'] = 'sample_view/image_dropdown_view';
$this->display_table_images();
}
public function display_table_images()
{
$this->load->model('Sample_model/image_model');
$data['images'] = $this->image_model->displayTableImages();
$data['main_view'] = 'sample_view/image_dropdown_view';
$this->load->view('sample_view/image_dropdown_view', $data);
}
public function search_dropdown_images($type)
{
$this->load->model('Sample_model/image_model');
$type['dropdown_images'] = $this->input->post('type');
switch ($type) {
case 'all':
$data['images'] = $this->image_model->get('all');
break;
case 'with-image':
$data['images'] = $this->image_model->get('with-image');
break;
case 'no-image':
$data['images'] = $this->image_model->get('no-image');
break;
default:
echo 'There are no images to be returned';
break;
}
$this->load->view('sample_view/image_dropdown_view', $type);
}
}
Here is the code in my view:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div>
<div>
<?php echo "<select name='type' id='type'>
<option value='all'>All Image</option>
<option value='with-image'>With Image</option>
<option value='no-image'>Without Image</option>
</select>" ?>
<?php echo "<input type='submit' value='Search'>"; ?>
</div>
<div>
<h3>Images</h3>
</div>
<div>
<?php if (isset($images)): ?>
<?php foreach($images as $image): ?>
<table border="1">
<tr>
<td><?php echo "$image->main_image"; ?></td>
<td><?php echo "$image->main_image_url"; ?></td>
</tr>
</table>
<?php endforeach; ?>
<?php endif; ?>
</div>
</div>
</body>
</html>
I will gladly appreciate any help/suggestion you can provide with regards to my question.
You should use AJAX for this.
First, you have to send a Query from ajax to call controller then Use the controller to load data from the database and Send it as an HTML block to the view and display it.
And also make an OnChange event to the drop-down linked to the ajax
Hope this one could help you
Use pagination library and get method to filter your data...
get method will help you to create base_url.
All you need to do is use your get data in for where statement. the problem you face is when you go to another page you lost your selected option.
in controller
after writing hole thing just change base_url for configure pagination and set it to
if(isset($_GET))
{
$config['first_url'] = $config['base_url'].'/1'.'?'.http_build_query($_GET, '', "&");
}
it will help to generate proper link
and at your view side .. get the selected value for the selected options..
<select name='type' id='type'>
<option value='all' <?php echo (isset($_get['type']) && $_get['type'] == 'with-image')?'selected':''; ?> >
All Image
</option>
<option value='with-image' <?php echo (isset($_get['type']) && $_get['type'] == 'with-image')?'selected':''; ?> >
With Image
</option>
<option value='no-image' <?php echo (isset($_get['type']) && $_get['type'] == 'no-image')?'selected':''; ?> >
Without Image
</option>
</select>
So im fairly new in coding HTML CSS and PHP and now im focusing PHP.
Our professor asked us to incorporate PHP codes in our website (no database) and im trying to print a an array using a for loop and echo.
the problem is that the echo doesn't show in the webpage and I am now lost
below is my codes:
<html>
<head>
<title>PHP Loops and Sorts</title>
<body>
<h1>PHP Loops and Sorts</h1>
<div class="container">
<?php
$dogs=Array("Labrador Retriever","German Shepherd","Bulldog","Golden Retriever","Poodle","Beagle","Rottweiler","Yorkshire Terrier","Siberian Husky","Dachshund","Chihuahua","Pug","Great Dane","Dobermann","Shih Tzu");
$cats=Array("Persian","Siamese","Maine Coon","Ragdoll","Sphynx","British Shorthair","Abyssinian","Bengal","Scottish Fold","Himalayan","Russian Blue","Siberian","Munchkin");
$birds=Array("Canaries","Budgies","Finches","Cockatiels","Quaker Parakeets","Pionus Parrots","Poicephalus Parrots","Amazon Parrots","Pyrrhura Conures","Peach-Faced Lovebirds");
$fishes=Array("Koi","Fantail","Oranda","Comet","Black Telescope","Butterfly Tail","Ryukin","Goldfish","Lionhead","Mirror Carp");
function countsize($array,$size){
$size = count($array);
return $size;
}
if(isset($_POST['btnShow']) )
{
$arraypick=$_POST['formAnimal'];
$arrsize = countsize($arraypick,$size);
for(&x = 0,$x<$arrsize,$x++){
echo $arraypick[$x] . "<br>";
}
}
?>
Breeds of different kinds of animals. Select what animal's breed to be shown:<br>
<select name="formAnimal">
<option value="">Choose animal</option>
<option value="dogs">Dog</option>
<option value="cats">Cat</option>
<option value="birds">Bird</option>
<option value="fishes">Fish</option>
</select><br><br>
<div style="margin:auto,text-align:center;text-align:center">
<INPUT TYPE = "Submit" Name = "btnShow" VALUE = "Show List">
<INPUT TYPE = "Submit" Name = "btnAsc" VALUE = "Show Ascending">
<INPUT TYPE = "Submit" Name = "btnDes" VALUE = "Show Descending">
</div>
<?php
echo $size
?>
</div>
</body>
</html>
You need to close your head tag before your body tag.
You also don't need to pass in size to your method count size.
function countsize (&array) {
return count(&array);
}
if(isset($_POST['btnShow']) ) are you sure it is set ?
From what we have in your code you can't even POST, you are missing your form tags
Try wrapping your inputs with :
<form method="POST">
<!--inputs-->
</form>
Your syntax for the for loop is incorrect. Check out the php documentation
Also the $size variable is never declared in the scope you are using it.
Didn't get how you're using $arrsize but you used &x instead of $x while initializing loop.
for($x = 0,$x<$arrsize,$x++){
echo $arraypick[$x] . "<br>";
}
change this lines of code:
$dogs=Array("Labrador Retriever","German Shepherd","Bulldog","Golden Retriever","Poodle","Beagle","Rottweiler","Yorkshire Terrier","Siberian Husky","Dachshund","Chihuahua","Pug","Great Dane","Dobermann","Shih Tzu");
$cats=Array("Persian","Siamese","Maine Coon","Ragdoll","Sphynx","British Shorthair","Abyssinian","Bengal","Scottish Fold","Himalayan","Russian Blue","Siberian","Munchkin");
$birds=Array("Canaries","Budgies","Finches","Cockatiels","Quaker Parakeets","Pionus Parrots","Poicephalus Parrots","Amazon Parrots","Pyrrhura Conures","Peach-Faced Lovebirds");
$fishes=Array("Koi","Fantail","Oranda","Comet","Black Telescope","Butterfly Tail","Ryukin","Goldfish","Lionhead","Mirror Carp");
function countsize($array,$size){
$size = count($array);
return $size;
}
$arraypick=$_POST['formAnimal'];
$arrsize = countsize($arraypick,$size);
for(&x = 0,$x<$arrsize,$x++){
echo $arraypick[$x] . "<br>";
}
To :
$animalArray['dogs']=Array("Labrador Retriever","German Shepherd","Bulldog","Golden Retriever","Poodle","Beagle","Rottweiler","Yorkshire Terrier","Siberian Husky","Dachshund","Chihuahua","Pug","Great Dane","Dobermann","Shih Tzu");
$animalArray['cats']=Array("Persian","Siamese","Maine Coon","Ragdoll","Sphynx","British Shorthair","Abyssinian","Bengal","Scottish Fold","Himalayan","Russian Blue","Siberian","Munchkin");
$animalArray['birds']=Array("Canaries","Budgies","Finches","Cockatiels","Quaker Parakeets","Pionus Parrots","Poicephalus Parrots","Amazon Parrots","Pyrrhura Conures","Peach-Faced Lovebirds");
$animalArray['fishes']=Array("Koi","Fantail","Oranda","Comet","Black Telescope","Butterfly Tail","Ryukin","Goldfish","Lionhead","Mirror Carp");
function countsize($index){
return count($animalArray[$index]);
}
$arraypick=$_POST['formAnimal'];
$arrsize = countsize($arraypick);
for($x = 0;$x<$arrsize;$x++){
echo $animalArray[$arraypick][$x] . "<br>";
}
In the phtml file shows all my database in a table including price, id etc , and then in the php file Details when the user try to press rent it takes the Id of the item and store it in the shop using the method add I keep getting this error
Fatal error: Function name must be a string.
The reason why I store the id of the item from the database so when the user check out I ll retrieve all the information using the id of the item been selected by the user. and also I am using array list to store more then one item, another thing to mention they way of getting the id of the item is by the local variable $tem = $_POST(['$dvdDetails->getDvdId()']); in the adding cart file but i am not really sure if its store the right value as there is a foreach loop and The duration of the variable will be distorted by the end of the method so how can i get the the id of the item been selected.
<?php
require_once('Models/Product.php');
class Shop {
private $_products = array();
public function getProducts()
{ return $this->_products;}
public function addProduct(Product $product)
{ $this->_products[] = $product;
return $this;
}
}
?>
<?php
class Option {
private $_optionKey;
private $_optionValue;
public function getKey()
{ return $this->_optionKey; }
public function getVlue()
{
return $this->_optionValue;
}
public function setOption($key, $value)
{
$this->_optionKey = $key;
$this->_optionValue = $value;
return $this;
}
}
?>
<?php
require_once('Models/Option.php');
class Product {
private $_options = array();
public function getOptions()
{ return $this->_options; }
public function addOption(Option $option)
{ $this->_options[] = $option;
return $this;
}
}
?>
//SHow all
<?php require('template/header.phtml') ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table class="datatable">
<tbody>
<?php foreach ($view->dd as $dvdDetails) {
echo '<tr> <td>'
.'<img src="images/'. $dvdDetails->getPhotoDetails() .'"alt="no picture" height="240" width="820" />' .'<br><br>'.'<font size="3" color="#2E2E2E"><center>'. $dvdDetails->getDvdPhoto(). '</center></font>'.
'<br><br><br>'. '<font size="2" color="blue"><strong>Genre: </strong></font>'. $dvdDetails->getDvdGenre() .
'<br><br>'. '<font size="2" color="blue"><strong>Director: </strong></font>'. $dvdDetails->getDvdDirector() . '<br><br>' .'<font size="2" color="blue"><strong>Ritels: </strong></font>'. $dvdDetails->getDvdRitels() .
'<br><br>' . '<font size="2" color="blue"><strong>Price for rent: </strong></font>'. $dvdDetails->getDvdId()) .
'<br><br>' .
'<div class="ghassar">' .
'<div id="op"> <label>Number of days </label> <select name="days" > <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option>
</select>
<br><br><br><br>
</div>
<div>
<input type="submit" value="Add to the basket" name="rent" id="buttom1" />
</div> ' . '<br><br>' .
'<br><br>' .'<div>'.
'</td> </td> </tr>';
} ?>
</tbody>
</table>
<?php require('template/footer.phtml') ?>
// adding to the cart
<?php
require_once('Models/Dvd_sql.php');
require_once('Models/Shop.php');
$view = new stdClass();
$view->dd = 'SQL';
$dvd_sql = new Dvd_sql();
$view->dd = $dvd_sql->fetchAllStudents(); //->fetchAllStudents();
if (isset($_POST['rent']))
{
$tem = $_POST(['$dvdDetails->getDvdId()']);
$shop = new Shop(); $shop->addProduct($tem);
}
require_once('Views/dvdDetails.phtml');
I think what you're trying to do is get the ID of the DVD from the form page into the form processing page. Assuming that's it, there are a couple of problems with the way you're going about that.
First, $_POST['$dvdDetails->getDvdId()'] is looking in the post data for a string key literally matching the string '$dvdDetails->getDvdId()'. Strings in single quotes aren't interpolated by PHP, and even with double-quotes you really want to stick with simple variables and/or use {$brackets}.
Second, it seems to me that the object $dvdDetails does not even exist in the form processing script. I only see it in the form display code, and that does not automatically transfer it over to the processing script. You'll need to explicitly pass the data you need in the form. For that, you can do something like this:
In the form (following your string concatenation style)
'<input type="hidden" name="item_id" value="' . $dvdDetails->getDvdId() . '">' .
in the processing script
$item_id = $_POST['item_id'];
Edit
The first time around, I missed the fact that you're looping over many DVD items. In that case, my advice would lead to many item_id inputs and only one (the last, I think) will be seen by the processing script. Your "days" selector will suffer from the same problem. In this case, I think simplest solution would be to create a separate form for each DVD and use my advice above. That way only one copy of "days" and "item_id" get sent when you submit the form for a particular DVD.
So I am trying to make this clip submission form interactive in the following way:
I want the second Select list choices to change according to which city is selected in the first select list.
Here is my script function code:
<script>
function spotListChange(s1, s2) {
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if(s1.value == ""){
var optionArray = ["|"];
}
<?php
while ($cityList = $cityListDB->fetch()) {
$city = $cityList['city'];
$spotList = $db->query("SELECT * FROM spots WHERE city='$city' ORDER BY name");
?>
else if(s1.value == "<?php echo $city; ?>"){
var optionArray = ["|"
<?php
while ($spot = $spotList->fetch()) {
echo ", \"" . $spot['city'] . "|" . $spot['city'] . "\"";
}
?>
];
}
<?php
}
?>
for(var option in optionArray){
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
}
</script>
Here is the part of the form with the two select lists. (I'll get rid of most city options available just to make the code shorter)
<select id="city" name="city" style="margin-left: 135px;" onChange="spotListChange('city', 'spotSelectList')" required>
<option value="" selected="selected">Ville...</option>
<option value="Albanel">Albanel</option>
<option value="Alma">Alma</option>
<option value="La Doré">La Doré</option>
<option value="Saint-Félicien">Saint-Félicien</option>
<option value="Mashteuiatsh">Mashteuiatsh</option>
</select><br />
<select id="spotSelectList" name="spot" style="margin-left: 135px;">
</select>
If I change the PHP inside the else if by fix/text values, it works fine, so the issue must be there, but I don't get where the issue is.
Do yourself a favor and use jquery for it, it makes your code more simple and is a plenty of tutorial out there.
I recomend you make a json response from php to an ajax call from jquery (javascript).
Can you see this as reference:http://simpleweb.github.io/jquery-dependent-selects/
also this:http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html
Hope this helps you.
I am trying to fillup two select boxes using the result of a mysql select query. I run the query once and use the output variable to loop and set options of select tag accordingly. The problem is, first select box gets populated as expected but the second one does not. It remains empty whatsoever. Heres my code
<?php
$con = mysql_connect('localhost','root','') or die('Could Not Connect'.mysql_error());
mysql_select_db('irctc', $con)or die('Could Not Select'.mysql_error());;
$result = mysql_query("select * from stationcodes", $con)or die('Could not select'.mysql_error());
?>
<html>
<head>
</head>
<body>
<table>
<tr>
<td>Source</td>
<td>:-</td>
<td><select id='src'>
<option value=''>Select Source Station</option>
<?php while($row = mysql_fetch_array($result))
{ ?>
<option value='<?php echo $row['StationCode']; ?>'><?php echo $row['StationName']; ?></option>
<?php } ?>
</select>
</td>
</tr>
<tr>
<td>Destination</td>
<td>:-</td>
<td><select id='dst'>
<option value=''>Select Destination Station</option>
<?php while($row = mysql_fetch_array($result))
{ ?>
<option value='<?php echo $row['StationCode']; ?>'><?php echo $row['StationName']; ?></option>
<?php } ?>
</select>
</td>
</tr>
</table>
</body>
</html>
You need to "rewind" data pointer back to the beginning before starting to iterate over the results again. Use mysql_data_seek(0); to do that, before building your "Destination":
<td><select id='dst'>
<option value=''>Select Destination Station</option>
<?php mysql_data_seek(0); // reset data pointer to 1st row
while($row = mysql_fetch_array($result))
{ ?>
<option value='<?php echo $row['StationCode']; ?>'><?php echo $row['StationName']; ?></option>
<?php } ?>
</select>
</td>
Also do not use mysql_. Switch to mysqli_ or PDO. and it would help you to separate code from view and use any type of template engine (like Smarty)
You need to either rerun the query before the second select box is rendered or to cache its results in an array first. Once you use mysql_fetch_* it has been read and you need to rewind the cursor or just start again/
In addition, stay away from mysql_* and use PDO or mysqli instead.
When you get to the second select box, all records are already fetched, so nothing will happen there.
What you should do is fetch al records into a array before you start the html code.
Then in the html code use a foreach statement to loop over the array.
Store your database result in an array so that you can use it multiple times:
$records = array();
while ($row = mysql_fetch_array($result)) $records[] = $row;
And to avoid writing the same algorithm multiple times, define a function that you call instead, for example:
function select($attrs, $options, $selected=null) {
$ret = '<select';
if (is_array($attrs)) {
foreach ($attrs as $name => $val) {
$ret .= ' '.htmlspecialchars($name).'="'.htmlspecialchars($value);
}
}
$ret .= '>';
foreach ($options as $option) {
$ret .= '<option';
if (isset($option['value'])) {
$ret .= ' value="'.htmlspecialchars($option['value']).'"';
if ($selected === $option['value']) {
$ret .= ' selected="selected"';
}
}
$ret .= '>';
if (isset($option['label'])) {
$ret .= htmlspecialchars($option['label']);
}
$ret .= '</option>';
}
$ret .= '</select>';
return $ret;
}
Then all you need to do is call this function with different parameters:
$options = array();
while ($row = mysql_fetch_array($result)) {
$options[] = array(
'value' => $row['StationCode'],
'label' => $row['StationName']
}
}
$srcOptions = array_merge(array(array('label'=>'Select Source Station')), $options);
echo select(array('id'=>'src'), $srcOptions);
$dstOptions = array_merge(array(array('label'=>'Select Destination Station')), $options);
echo select(array('id'=>'dst'), $dstOptions);