Pass a parameter to a method using PHP custom MVC - php

Im using a custom MVC in PHP
I have two tables.
Controles and professors
professors table contains an id of course --> id_professor
controles table contains a field called --> id_professors in which I store a list of profs ids this way ==> 1;2;5;9
In my datatable Im retrieving a list of controles from controles table
for the Model, Im using this class
public function fetchControlesListe(){
stmt = $this->db->prepare("SELECT * FROM controles ");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
return $stmt->fetchAll();
}
Controller
liste_controles.php
class Liste_Controles extends Controller {
function __construct(){
parent::__construct();
}
$this->view->fetchCtrlListe= $this->model->fetchControlesListe();
$this->view->render('liste_controles/index');
}
VIEW
<table>
<thead>
<tr>
<th>N°</th>
<th>Module</th>
<th>Salle</th>
<th>Surveillants</th>
</tr>
</thead>
<tbody>
<?php foreach($this->fetchCtrlListe AS $key=>$value): ?>
<tr>
<td><?php echo $controle['id_controle']; ?></td>
<td><?php echo $controle['intitule_module']; ?></td> <
<td><?php echo $controle['intitule_salle'];?></td>
<td>
<?php foreach($this->prof as $profs): ?>
HERE, I would like to retrieve the list of profs from professors
table and the field id_profs in professors table stores an
array, as i said before, containing a list of ids (Ex: 1;2;3;4;5)
I would like to loop through that array and retrieve the name of
professor from professors table if the id_professor Exists in that array
. I know I have to create another METHOD but The PROBLEM is i don't know how to pass parameters in the method and call it from the controller to pass it to the view . and the param would be $controle['id_professor']
<?php endforeach; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
The result would be like this:
EDIT:
I know that is not a good idea to store lots of ids as an array, but
my question I just want to know how to do a foreach loop inside
another foreach loop using another method with a paramater that will
be passed from the first loop

There isn't one solution but what you can do is, because you know that id_professors is a string composed of ids separated by commas, you can retrieve an array of identifiers this way :
$ids = explode(",", $profs[id_professors']);
and then
<?php foreach($this->prof as $profs): ?>
<?php $ids = explode(",", $profs['id_professors']); ?>
<?php foreach($ids as $id): ?>
//DO STUFF with $id
<?php endforeach; ?>
<?php endforeach; ?>
Notice that the entire thing is not very beautiful because of opening/closing php tags constantly but I hope you'll make a wonderful templates system for your MVC framework :)
From there, it would not be that nice to access the database directly from the view so a better (not perfect) solution would be to provide the view an array made of professors like this one :
$this->view->profs_list = array(
1 => "Prof 1",
2 => "Prof 2",
//etc.
);
with the key of the array being the profs' identifier.
Then you can retrieve their name through the loop :
<?php foreach($this->prof as $profs): ?>
<?php $ids = explode(",", $profs['id_professors']); ?>
<?php foreach($ids as $id): ?>
<span><?php echo $this->profs_list[$id]; ?></span><br />
<?php endforeach; ?>
<?php endforeach; ?>

Related

Foreach table output rows near each other

I have json html table in php, now i can't get it work that the output in the table will be near each other.
I am already few days busy with this, hope some one can help me.
<?php foreach($data2 as $row): ?>
<tr>
<td><?=$row['model'];?></td>
<td><?=$row['model2'];?></td>
</tr>
<?php endforeach;?>
My json output:
It looks like the JSON is not formatted for what you are trying to do. Every object has either modal or modal2, so the one that is not filled is undefined.
You should get the length of the longest list and use a normal for loop.
<?php ($index = 0; $index <= $lengthOfLongestList; $index++): ?>
<tr>
<td><?=$data2[index]['model'];?></td>
<td><?=$data2[index]['model2'];?></td>
</tr>
<?php endforeach;?>

How can I run PHP code in an specific html section

I have a section in my .html page where I want to run some PHP code, which reads data from a database and 'echoes' the table filled up with that information. I kinda did it object-oriented so I'm trying to keep that along the project.
I have this exact function or method in the Class (Class Servicio):
public static function listaServicios(){
$servicios = array();
$query = "";
$db = Database::getInstance();
$query = "SELECT descripcion, precio FROM servicio";
$resultado = $db->conn()->query($query);
foreach($resultado as $item){
$servicio = new Servicio();
$servicio->setDescripcion($item['descripcion']);
$servicio->setPrecio($item['precio']);
array_push($servicios,$servicio);
}
return $servicios;
}
As you can see, the function just returns an array filled up with as many objects as rows there is in the table. The PHP page would call this method, and then print the table with the selected data inside (there is no problem with this).
The thing is how can I print it in the specific section (div with id='datos') previously mentioned, which simply is:
<section class="principal">
<div id="datos">
</div>
</section>
I kinda of have an idea but I really don't know to implement it. Maybe using a document.ready function in jQuery calling the PHP code? I would really like to use this language even if it is a very tiny function in order to learn.
You can use jquery's load function to load content via a remote file into the div. But you will need to update your listaServicios to return html instead of the array.
jquery:
$(document).ready(function(){
$('#datos').load('phpfile.php');
});
phpfile.php
<?php
$serv = new Servicio();
echo $serv->listaServicios();
?>
Correct answer to your question depends on the interface of your future application you want to reach.
If you want some kind of SPA, then you should make AJAX-requests using JavaScript (jQuery or something else) and create a separate controller to response with data.
But I think in your particular case you can do everything on server side.
First of all you should add new method to your class, name f.e. render:
public static function render(){
$services = static::listaServicios();
include 'path/to/your/template.php';
}
Then inside your template.php write next:
<section class="principal">
<div id="datos">
<?php
foreach($services as $service) {
// echo your $service here as you wish
}
?>
</div>
</section>
So after calling render() PHP will render that part of template.
To access the properties of Servicio is better you construct your table in php:
<?php $servicios = Servicio::listaServicios(); ?>
<section class="principal">
<div id="datos">
<table style="width:100%">
<tr>
<th>Descripcion</th>
<th>Precio</th>
</tr>
<?php foreach ($servicios as $servicio): ?>
<tr>
<td><?= $servicio->getDescripcion() ?></td>
<td><?= $servicio->getPrecio() ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>
</section>

Nested php loop only runs once when connecting to sql

I'm trying to learn php and I have this exercise I'm working on. I have an SQL db with two tables: categories and items. I want to loop through categories and create an html table for each category. I can do that part fine. Then for every category, I want to loop through every item and check to see if it belongs to that category. If it does, then it gets passed into the table. However, for some reason the second loop only gets run for the first category.
I've tried using a foreach loop on the items but then nothing shows up.
<?php while($category = mysqli_fetch_assoc($category_result)) : ?>
<button class="collapsible"><?= $category[Name]; ?></button>
<div class="link-data">
<table class="link-table">
<?php while($item = mysqli_fetch_assoc($items_result)) : ?>
<?php if (item[category_id] = category[id] ) : ?>
<tr>
<td><?= $item[name]; ?></td>
<td><?= $item[price]; ?></td>
<td><?= $item[description]; ?></td>
</tr>
<?php endwhile; ?>
<?php endif; ?>
</table>
</div>
<?php endwhile; ?>
I then expect a result like this for example:
Phones :
- Samsung
Toys :
- Rubber ball
Books :
- Harry Potter
Instead I'm getting this:
Phones :
- Samsung
- Rubber ball
- Harry Potter
Toys :
Books :
for the inside loop after first time, item_result pointer goes to end and you have to reset it if you wanna loop again.
so before the inside while add this line
mysqli_data_seek($items_result, 0);
this line set the item_result pointer to first row

Code Igniter: Adding built in CI functions to a table

I am attempting to add some styling to a table in Code Igniter, I realize CI has a built in table library to help achieve this. I'm unsure how to implement this in my specific implementation however. I'm looking to incorporate these inbuilt functions:
$this->load->library('table');
$this->table->set_heading(array('Name', 'Color', 'Size'));
How can I add those functions in my specific implementation?
I have the following controller:
public function ecomma(){
$this->load->model('report_model');
$data ['query'] = $this->report_model->generate_ecomm_data_report();
$this->load->view('report_view', $data);
}
My view:
<table>
<tbody>
<?php foreach($query as $row): ?>
<tr>
<td><?php echo $row->no_skus; ?></td>
<td><?php echo $row->brand; ?></td>
<td><?php echo $row->unique_models; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Using the Table library is quite easy. This example requires that generate_ecomm_data_report()returns the results of a query. For example:
return $this->db->query('YOUR QUERY HERE');
Controller:
public function ecomma(){
$this->load->library('table');
$this->load->model('report_model');
$query = $this->report_model->generate_ecomm_data_report();
One advantage to the Table library is that styling is quite easy using the template scheme of the class. For instance to add a CSS class to the header and to rows.
controller continues:
$my_styles = array(
"thead_open" => "<thead class='my_style'>",
"row_start' => '<tr class='my-row-style'>");
$this->table->set_template($my_styles);
$this->table->set_heading(array('Name', 'Color', 'Size'));
$data[table] = $this->table->generate($query);
$this->load->view('report_view', $data);
}
View:
<?php echo isset($table) ? $table : "No Data"; ?>
The result will be a table structure like the one you create in the foreach loop - only this one has style.

PHP Symfony Convert Propel Choice to String

I am using a propel form to allow a user to create an account, the form has two parts; the entering and then the preview.
On my preview page I declare the values of the form as usual and these are provided by the previous form
public function configure() {
//Preview page no fields are displayed anyway xD
$this->useFields(array('email', 'user_gender_id', 'search_gender_id', 'content', 'age', 'location'));
But instead of outputting the fields I am trying to render the values on the page:
<?php echo $form->renderHiddenFields(); ?>
<?php foreach($form as $field): ?>
<?php if(!$field->isHidden()): ?>
<tr>
<th><?php echo $field->renderLabel() ?></th>
<td><?php echo $field->getValue(); ?></td>
</tr>
<?php endif; ?>
<?php endforeach; ?>
<?php else: ?>
<?php echo $form; ?>
<?php endif; ?>
Unfortunately for my sfWidgetFormPropelChoice / sfWidgetFormChoice fields it just outputs the chosen ID rather than a string representation of it.
Is there a proper way in Symfony to output the text representation of a widget's value? Or do I have to hack something together? (any ideas?)
Many thanks,
Pez,
Try:
$obj = $form->getObject();
to have the values of your object. Then:
echo $obj[$field->getName()];
this can work in most cases. But, if it won't, you'll have to write all the preview fields by hand and display them using the $obj above.
I got around this problem by doing the following:
<td><?php if(method_exists($field->getWidget(), "getChoices")) {
$choices = $field->getWidget()->getChoices();
echo $choices[$field->getValue()];
} else
echo $field->getValue();
?></td>
I hope this is of use to someone as it has been driving me crazy!

Categories