Call a function from a "html table" in drupal 7 - php

I need to call the FUNCTION when the BUTTON is clicked. How I can do this?
(I know that the code I wrote is wrong, it's just to make it clear)
function gh_view_categories(){
$a='<table>';
$a.='<tr>';
$a.='<td><strong>'.'Categoria:'.'</strong></td>';
$a.='<td><strong>'.'Soglia minima:'.'</strong></td>';
$a.='<td><strong>'.'Tot attuale:'.'</strong></td>';
$a.='<td><strong>'.'Crea ordine'.'</strong></td>';
$a.='</tr>';
$query = db_select('uc_product_classes', 'u')
->fields('u', array('name','soglia', 'totattuale'));
$result = $query->execute();
while ($record = $result->fetchAssoc()) {
$idUser=gh_get_user_id($record['name']);
$a.='<tr>';
$a.='<td>'.$record['name'].'</td>';
$a.='<td>'.$record['soglia'].'</td>';
$a.='<td>'.$record['totattuale'].'</td>';
$a.='<td>'.l('BUTTON', FUNCTION($idUser)')).'</td>';
$a.='</tr>';
}
$a.='</table>';
return $a;
}

You need to add this in your html button tag:
<button onClick="yourFunction()">

Related

Efficient way to reuse the same call to the same sql table

So I search for this title hoping someone would have already answered it however, I came across similar topics on other languages but not PHP so maybe this will help others.
I am constantly using this following script to call on the database but how can I create it so that I can make it just once at the top of the class for example and use it in every method on the class page that needs it. Example: An single page may not have all of the data it needs from the same table but if the table contains 50% of the data or more for that page, how can I modify this so that I can just say it once and let the rest of the following scripts display the data it extracted in the first place by calling it all just once?
Here's what I have now.
<?php
if($res = $dbConn->query("SELECT Column FROM Table")){
while($d = $res->fetch_assoc()){
printf("Enter HTML here with proper %s", $d['Column']);
}
}
?>
I want to call on this without the printf(" "); collect and store the data so that I can then call the results while printing or echoing the results with the HTML in other methods. What os the most efficient way? I don't want to make the same call over and over and over... well, you get the point.
Should I use fetch_array or can I still do it with fetch_assoc?
not very sure if it's the answer you want.
you can use include/include_once/require/require_once at the top of the page you want to use the function
for example:
general_function.php:
-----
function generate_form( $dbConn, $sql ) {
if($res = $dbConn->query("SELECT Column FROM Table")) {
while($d = $res->fetch_assoc()) {
printf("Enter HTML here with proper %s", $d['Column']);
}
}
}
and for those pages you want to use the function, just put
include "$PATH/general_function.php";
and call generate_form
Try this:
class QueryStorage {
public static $dbConn = null;
public static $results = [];
public static function setConnection($dbConn) {
self::$dbConn = $dbConn;
}
public static function query($query, $cache = true) {
$result = (array_key_exists($query, self::$results))?
self::$results[$query] : self::$dbConn->query($query);
if($cache) {
self::$results[$query] = $result;
}
return $result;
}
public static function delete($query) {
unset(self::$results[$query]);
}
public function clean() {
self::$results = [];
}
}
usage:
at top somewhere pass connection to class:
QueryStorage::setConnection($dbConn);
query and store it:
$result = QueryStorage::query("SELECT Column FROM Table", true);
if($result){
while($d = $result->fetch_assoc()){
printf("Enter HTML here with proper %s", $d['Column']);
}
}
reuse it everywhere:
$result = QueryStorage::query("SELECT Column FROM Table", true); // it will return same result without querying db second time
Remember: it's runtime cache and will not store result for second script run. for this purposes You can modify current class to make it
work with memcache, redis, apc and etc.
If I understood you correctly, then the trick is to make an associative array and access with its 'key' down the code.
$dataArray = array();
// Add extra column in select query for maintaining uniqness. 'id' or it can be any unique value like username.
if($res = $dbConn->query("SELECT Column,id FROM Table")){
while($d = $res->fetch_assoc()){
$dataArray[$d['id']] = $d['Column'];
}
}
//you have value in the array use like this:
echo $dataArray['requireValueId'];
//or , use 'for-loop' if you want to echo all the values
You need a function which takes in the query as a parameter and returns the result.
Like this:
public function generate_query($sql) {
if($res = $dbConn->query($sql)){
while($d = $res->fetch_assoc()){
printf("Enter HTML here with proper %s", $d['Column']);
}
}
}

Check and/or set button state mvc php

I am new to php/mvc and experimenting with a small website.
I would like to change to state of a button depending on a select query. It's a simple 'favourite' toggle button. The query will look to the 'favourite' table of my db for the 'isFav' field (0 or 1).
I would like the button colour to be green (btn-success) if the query finds a result (1), and the colour to be default (btn-default) if not (0).
Should be simply but I can't seem to get it. I think I am getting confused regarding passing of the variables between my view and model.
My books_model.php code is as follows
class BooksModel
{
public function isFav()
{
$book_id = $_GET['id']; // from url
$user_id=$_SESSION['user_id'];
$sql = "SELECT isFav FROM favourite WHERE book_id = :book_id AND user_id = :user_id AND isFav = 1";
$query = $this->db->prepare($sql);
$query->bindParam(':book_id', $book_id);
$query->bindParam(':user_id', $user_id);
$query->execute();
if ($query->rowCount() == 1) {
$css = 'btn-success';
echo $css; //for testing
} else {
$css = 'btn-default';
echo $css; // for testing
}
}
}
My books.php controller is as follows;
class Books extends Controller
{
function itemView()
{
$itemView_model = $this->loadModel('Books');
$this->view->books = $itemView_model->itemView();
$this->view->render('books/itemView');
$itemView_model->isFav();
}
}
My itemView.php html button code is as follows;
echo '<button class="btn '.$css.'"></button>';
The only thing printed on the page is a btn-success or btn-default (top left). This toggles whenever I click the button. Therefore I assume my query is working.
Apologies for the code I am a newbie and I do appreciate any help offered, even a point in the right direction.
Try this:
public function isFav() {
(...)
if ($query->rowCount() == 1) {
$css = 'btn-success';
echo $css; //for testing
} else {
$css = 'btn-default';
echo $css; // for testing
}
return $css;
}
And in your View:
echo "<button class=\"btn ".$itemView_model->isFav()."\"></button>";
The reason: Your Variable $css in your isFav() method is not known in your view (the scope of the variable is the isFav() method).
This line:
$itemView_model->isFav();
Requests the return value of this function, so, clearly, the value bust be returned in order to be available.
The reason you see the seemingly correct answer printed is that the echo call is in the same scope as the $css variable.

CodeIgniter Dropdown menu

I have a view (myView) in which there is a form. The form action is myController/myFunction1 which is used to validate the input variables in the form and insert it to the database by calling a model function. This works perfectly fine.
Now, I need a dropdown box inside the form, for which the values will be fetched from a table (called business) in the db.
This is the code I wrote in my model to fetch the values
public function get_dropdown_list() {
$this -> db -> select('business_name');
$result = $this -> db -> get('business');
if ($result -> num_rows() > 0) {
foreach ($result->result_array() as $row) {
$new_row['value'] = htmlentities(stripslashes($row['business_name']));
$row_set[] = $new_row;
}
}
return $row_set;
}
I'm not entirely sure if this is correct.
What I need to know is, if this is correct, what should be the code inside the controller and the view to display the result as a dropdown in the form in the myView.
And if this model itself is wrong, how do I get it working?
P.S. : I'm new to CodeIgniter. I have been going through S.O and various other sites to get this thing working for quite a bit of time now. This might seem to be a repeated question for which I'm really sorry, because I could not find a solution from the already available discussions dealing with the same issue. Any help is very much appreciated.
try Model :-
public function get_dropdown_list() {
$this -> db -> select('business_name');
$result = $this -> db -> get('business');
if ($result -> num_rows() > 0) {
return $result->result_array();
}
else {
return false;
}
}
Controller :-
1. include model in your controller
2. call the function and send data to view.
$this->load->model('model_name');
$this->data['dropdown'] = $this->model_name->get_dropdown_list();
$this->load->view('yourview', $this->data);
get value in view:-
print_r($dropdown)
Loop your data and make a dropdown
<select name="dropdown">
<?php foreach($dropdown as $d) {?>
<option value="<?php echo $d;?>"><?php echo $d;?></option>
<?php }?>
</select>
Call This function in controller for getting your records from DB
$data['records'] = $this->my_model->get_data();
In my_model.php
function get_data()
{
$query = "select * from my_tab";
$res = $this->db->query($query);
if ( $res->num_rows )
{
return $res->row_array();
}
return false;
}
In view.php
<select>
<?for($i=0;$i<count($records);$i++)
{
?>
<option>$records[$i]->name</option>
<?php } ?>
</select>

Catching the returned value

this may be a stupid question, but every source on the web seems not able to fully explain the logic to my complex brain
There's an edit page getting a $_GET['id'] from a link.
I got a function on my class elaborating this one to create an array of values from the database which must fill the form fields to edit datas. The short part of this code:
public function prel() {
$this->id= $_GET['id'];
}
public function EditDb () {
$connetti = new connessionedb();
$dbc = $connetti->Connessione();
$query = "SELECT * from anammi.anagrafica WHERE id = '$this->id'";
$mysqli = mysqli_query($dbc, $query);
if ($mysqli) {
$fetch = mysqli_fetch_assoc($mysqli);
return $fetch;
}
}
This array (which i tried to print) is perfectly ready to do what i'd like.
My pain starts when i need to pass it to the following function in the same class, which perhaps calls a parent method to print the form:
public function Associa() {
$a = $this->EditDb();
$this->old_id = $a['old_id'];
$this->cognome = $a['cognome'];
$this->nome = $a['nome'];
$this->sesso = $a['sesso'];
$this->tipo_socio_id = $a['tipo_socio_id'];
$this->titolo = $a['titolo']; }
public function Body() {
parent::Body();
}
How do i have to pass this $fetch?
My implementation:
<?php
require_once '/classes/class.ConnessioneDb.php';
require_once '/classes/class.editForm';
$edit = new EditForm();
$edit->prel();
if ($edit->EditDb()) {
$edit->Associa();
$edit->Body();
if (if ($edit->EditDb()) {
$edit->Associa();
$edit->Body();) {
$edit->Associa();
$edit->Body();
your Editdb method is returning a string and you are checking for a boolean condition in if statement. this is one problem.
using fetch-
$fetch=$edit->EditDb();
$edit->Associa();
$edit->Body($fetch);
Posting the full code of it:
public function prel() {
$this->id= $_GET['id'];
}
public function EditDb () {
$connetti = new connessionedb();
$dbc = $connetti->Connessione();
$query = "SELECT * from table WHERE id = '$this->id'";
$mysqli = mysqli_query($dbc, $query);
if ($mysqli) {
$fetch = mysqli_fetch_assoc($mysqli);
return $fetch;
}
}
public function Associa($fetch) {
$this->old_id = $fetch['old_id'];
$this->cognome = $fetch['cognome'];
$this->nome = $fetch['nome'];
$this->sesso = $fetch['sesso']; //it goes on from there with many similar lines
}
public function Body() {
$body = form::Body();
return $body;
}
Implementation
$edit = new EditForm();
$edit->prel();
$fetch=$edit->EditDb();
$edit->Associa($fetch);
$print = $edit->Body();
echo $print;
Being an edit form base on a parent insert form, i added an if in the parent form that sees if is set an $_GET['id] and prints the right form header with the right form action. This was tricky but really satisfying.

Php Display While Loop From Function

I have a question regarding displaying the contents of a function, this function displaying a while loop.
Here is a function within my model:
function get_results($id)
{
$stmt = "select * where ... "
$stmt = $this->BEAR->Database->query($stmt);
$result = '';
while($row = mysqli_fetch_array($stmt))
{
$result .= '<div>';
$result .= $row['name'];
$result .= '</div>';
}
$this->BEAR->Template->setData('loop', $result, FALSE);
}
This is my Controller:
$BEAR->Webprofile->get_results(Template->getData('id'));
And this is my view:
<?php echo $this->getData('loop');?>
This displays the Loop within my view with no problem. But what I wish for is not to have any HTMl within my Model, Is there anyway of doing this (As this can cause a large amount of HTML in my Model). Maybe a way I can set the data within the Model and then get the data within my view.
I tried setting within the Model functions while loop individually like the following:
while($row = mysqli_fetch_array($stmt))
{
$this->BEAR->Template->setData('name', $row['name']);
$this->BEAR->Template->setData('name', $row['age']);
}
Then call the function in the Controller and call each setData, but this only displayed the first result not the full while loop of contents.
Therefore I wish to display all the contents of my while loop in my view (with HTML) but wish my function to just be getting and setting the Data. Can this be done? Any thoughts or guidance would be appreciated.
You need to apply some discipline to your MVC. Your models need to return raw data. It should return only objects or arrays of data. The key is consistency.
Your views need to include all the code to add your html formatting. Having a view that simply calls a model function you wrote that spits out a div or an ordered list, makes the entire concept of the view useless. Your views should provide all the HTML code.
Since you're using PHP, you can easily drop in and out of HTML.
Start with something like this in your model:
function get_results($id)
{
$stmt = "select * where ... "
$stmt = $this->BEAR->Database->query($stmt);
$results = array();
while($row = mysqli_fetch_array($stmt))
{
$results[] = $row['name'];
}
return results;
}
From there, you should be able to figure out that your controller should call this function, and pass the $results into your view/template along with the specific view file for rendering.
function get_results($id)
{
$stmt = "select * where ... "
$stmt = $this->BEAR->Database->query($stmt);
$result = '';
$result = mysqli_fetch_array($stmt);
return $result;
}
Then in your controller:
$this->BEAR->Template->setData('loop', $model->get_results($id), FALSE);
Then in your template
foreach($rows as $row){
....do something with each row
}
full example of how to get the data from the model and then pass to the template
class MyController {
function controller_showResults(){
$model = new Model();
$results = $model->get_results($_GET['id']);
$this->BEAR->Template->setData('loop', $results, FALSE);
}
}
Now the view assuming that the first argument to setData in template is a variable passed to the view and that variable is $results
<?php foreach($loop as $l): ?>
<div><?php echo $l['name'] ?></div>
<?php endforeach; ?>

Categories