Currently I have a permissions table where the user can use a checkbox to give access or revert access for a URL link to a user with a particular role. So for this I've made it so that when a checkbox is pressed, the id of that checkbox and the role of the user are inserted in my database, but I'm unable to insert it in the database for some reason. I've tried the following code:
Controller Class:
public function permission()
{
if ($this->form_validation->run() == FALSE)
{
$main['permissions']=$this->users_model->get_permission_array();
$main['roles']=$this->users_model->get_roles_array();
foreach($main['roles'] as $key => $val):
$main['access'][$val['roles_id']]=$this->users_model->get_access_array(array('roles_id'=>$val['roles_id']));
endforeach;
$main['page'] = 'crm/users/permission';
$this->load->view('crm/index', $main);
}
if($this->input->post())
{
$loginid=false;
foreach($main['roles'] as $key => $val):
if(isset($_POST['roleid'.$val['roles_id']])){
$this->users_model->clear_access(array('roles_id'=>$val['roles_id']));
foreach($_POST['roleid'.$val['roles_id']] as $id => $access):
$data=array('roles_id'=>$val['roles_id'],'permissions_id'=>$access);
$loginid=$this->users_model->permission_access($data);
endforeach;
}
endforeach;
if($loginid){
$this->session->set_flashdata('message', '<p>Permission updated Successfully.</p>');
redirect('users/permission');
} else {
$this->session->set_flashdata('message', '<p>Error!! - Permission not updated.</p>');
redirect('users/permission');
}
}
}
Model Class:
function get_permission_array()
{
$query = $this->db->get("crm_client_permissions");
return $query->result_array();
}
function get_access_array($cond)
{
$this->db->select("permissions_id");
$this->db->where($cond);
$query = $this->db->get("crm_client_role_access");
return $query->result_array();
}
function clear_access($cond)
{
return $this->db->delete("crm_clients_access",$cond);
}
function permission_access($data)
{
return $this->db->insert("crm_clients_access",$data);
}
function get_roles_array($cond='')
{
if($cond !='') $this->db->where($cond);
$query = $this->db->get("crm_client_roles");
return $query->result_array();
}
View Class:
<div <?php echo form_open_multipart('users/permission'); ?>>
<table>
<?php if($permissions) $i=0;foreach($permissions as $key => $permission): ?>
<tr>
<td class="align-center"><?php echo ++$i; ?></td>
<td><?php echo $permission['page']; ?></td>
<td><?php echo $permission['url']; ?></td>
<?php foreach($roles as $rolekey => $role):
if($role['roles_id'] == 1)$checked = 'checked';
if(in_array($permission['permissions_id'],array_map('current',$access[$role['roles_id']])))
$checked = 'checked';
else
$checked = ''; ?>
<td align="center"><div class="checkbox checkbox-success m-t-0"><input type="checkbox" class="accessbox"
id="role<?php echo $rolekey ?>-<?php echo $key ?>" name="roleid<?php echo $role['roles_id']; ?>[]"
<?php echo $checked?> <?php echo ($role['roles_id'] == 1) ? 'disabled="disabled"' : '' ?> value="<?php echo $permission['permissions_id']; ?>" />
<label for="role<?php echo $rolekey ?>-<?php echo $key ?>"></label></div></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
<div class="text-center">
<button type="submit" class="btn btn-info">Save Permission</button> Cancel
</div>
<?php echo form_close(); ?> </div>
But here I always get Error!! - Permission not updated. in my view class which means it jumps to the else part of my controller. I'm not sure where I'm going wrong here
It seems problem is here $loginid=$this->users_model->permission_access($data); and here return $this->db->insert("crm_clients_access",$data);.
My advise is to:
use XDebug to debug your code and see what insert function returns and why.
Also you may look for php log to see if there is any database errors. To use error logs you need to find php.ini config file and enable line 'error_log = /path/to/fige.log'.
Also you may to lookup the database data to determine if insert function makes new row in table crm_clients_access, if it doesn't? you need to check your connection config to database host:port, so database process must be available at theese host:port.
Related
I know how to show all data from db using foreach but do not know how to show only 1 record that I select.
My code:
public function go($id)//controller
{
$data["log"] = $this->product_model->getAll();
$data['id']=$id;
$this->load->view("admin/kampus/list1",$data);
}
public function getById($id)//modal
{
return $this->db->get_where($this->_table, ["ID" => $id])->row();
}
//view
<?php foreach ($log as $product): ?>
<tr>
<td>
<?php echo $product->ID ?>
</td>
<td>
<?php echo $product->TGL_MULAI ?>
</td>
<td>
<?php echo $product->KETERANGAN ?>
</td>
</tr>
<?php endforeach; ?>
Please help me to show one record using foreach.
All you have to do is remove the foreach.
Or, change row() to result().
You should remove foreach and do this
return $this->db->get_where($this->_table, ["ID" => $id])->row_Array();
than you can use this
<tr>
<td>
<?php echo $product['id'] ?>
</td>
<td>
<?php echo $product->['tg_mulai'] ?>
</td>
<td>
<?php echo $product->['keterangan'] ?>
</td>
</tr>
you can use foreach() for only multiple rows
foreach operate on arrays and to show single record you should send it to view as array of objects. To do this just replace $data["log"] with $data["log"][] when you get single record from db. Check below code
public function go($id)//controller
{
$data["log"][] = $this->product_model->getById($id);
$data['id']=$id;
$this->load->view("admin/kampus/list1",$data);
}
public function getById($id)//modal
{
return $this->db->get_where($this->_table, ["ID" => $id])->row();
}
//view
<?php foreach ($log as $product): ?>
<tr>
<td>
<?php echo $product->ID ?>
</td>
<td>
<?php echo $product->TGL_MULAI ?>
</td>
<td>
<?php echo $product->KETERANGAN ?>
</td>
</tr>
First view, where you click to see selected data
<?php foreach ($log as $product): ?>
<a href="<?= base_url('controller/function/').$product->id; ?>"
class="btn btn-info">Edit</a>
<?php endforeach; ?>
Then Controller will receive the id like
public function edit_product($id){
$data['datas'] = $this->your_model->model_function($id);
$this->load->view('your_view', $data);
Model
public function model_function($id){
$this->db->select('*');
$this->db->where('id', $id);
$this->db->from('table_name');
$query = $this->db->get();
return $query->result();
}
Single Data View
<?php foreach($datas as $data): ?>
<?php echo $data->id; ?>
<?php echo $data->name; ?>
<?php endforeach; ?>
Let me know if it's ok
I am unable to display data from a table from a MYSQL database using PHP OOP. However, I'm not sure if I'm unable to display the data because I'm not actually fetching the data in the first place.
I've tried fetching and displaying the data using only a PHP array and no HTML in my method and I figured this wouldn't be working because I wasn't using HTML list tags to format the data from the database. I've considered using a HTML table but I have seen displays from databases using lists work a few times before and I want to know why this doesn't work how it should.
I've tested for MYSQL connection and it does exist.
* M_PRODUCTS.PHP *
<?php
class Products
{
private $Conn;
private $db_table = "toys";
function __construct() {
// here we're making sure that the connection from $conn in "init.php" is transferred
// into our own private $conn property for usage in this object
global $Conn;
$this->Conn = $Conn;
}
// fetches and displays all products from db
public function fetch_all_products($id = NULL)
{
if ($id == NULL)
{
$data = [];
if ($result = $this->Conn->query("SELECT * FROM " . $this->db_table . " ORDER BY name"))
{
if ($result->num_rows > 0)
{
while ($row = $result->fetch_array())
{
$data = array(
"id" => $row["product_id"],
"name" => $row["name"],
"price" => $row["price"],
"image" => $row["image"]
);
}
return $data;
}
else
{
return "<h1>Oops... Something went wrong!</h1>";
}
}
}
}
}
* INDEX.PHP *
<?php include("init.php");
include("models/m_products.php");
?>
<body>
<div id="whitespace">
<?php
$products = fetch_all_products();
?>
<?php foreach($products as $row) { ?>
<tr>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->price; ?></td>
<td><img src="<?php echo $row->image_path(); ?>" alt="<?php echo $row->name; ?>" width="100" /></td>
</tr>
<?php } ?>
</div>
</body>
I expect the images of my products to be displaying in my index.html file. However, nothing appears.
I also get this error message in the JavaScript console: Failed to load resource: the server responded with a status of 404 (Not Found). This would explain a lot but as I said I tested my database connection and it works. I'm not sure how or why this message is coming from the JavaScript console if I'm not using JavaScript. I thought it would be worth mentioning anyway.
According to your code the function returns some data, but the thing is that you have not printed it, so instead of return in the function you can use echo or just put
echo $Products->fetch_all_products();
Strange code, I would do something like that.
1. First the function find all()
2. index.php echo - output
<?php
$products = find_all_products();
?>
<?php foreach($products as $row) { ?>
<tr>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->price; ?></td>
<td><img src="<?php echo $row->image_path(); ?>" width="200" /></td>
</tr>
<?php } ?>
There are 2 major issues I can see in your code
1) you need to update your comparison operator from
if ($id = NULL)
to
if ($id == NULL)
2) you need to update your code in index.php from
<body>
<div id="whitespace">
<h1><?php echo shop_name ?></h1>
<?php
echo $Products->fetch_all_products();
?>
</div>
</body>
to
<body>
<div id="whitespace">
<?php
$products = find_all_products();
?>
<?php foreach($products as $row) { ?>
<tr>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->price; ?></td>
<td><img src="<?php echo $row->image_path(); ?>" alt="<?php echo $row->name; ?>" width="100" /></td>
</tr>
<?php } ?>
</div>
</body>
I hope it will sort out your issue
Correct your comparison operator it should be.
if ($id == NULL)
instead of
if ($id = NULL)
in your function fetch_all_products().
correct the code in index.php to print an array use print_r() or loop through the result array.
I have small problem with my PHP code. I must insert to database multiple values but I dont have any idea how I can do this.
My View:
<?php foreach($myKidsGroupID as $row): ?>
<label><input type="checkbox" name="user_my_group_msg" value="<?php echo $row->id; ?>" class="my_group_msg pull-right"><?php echo $row->firstname; ?> <?php echo $row->lastname; ?></label><br>
<?php endforeach; ?>
And my Model looks like this:
...
elseif($checked_my_group == 1) {
foreach ( ?? ) {
$new_mail = array(
'to_user' => $this->input->post('user_my_group_msg'),
);
$this->db->insert('mailbox', $new_mail);
}
}
...rest code....
Inside my View I display all users as checkbox but If I select two persons I must INSERT two query to database. Anyone can help me?
simple thing is
use serialize function don't use foreach
serialize $this->input->post('user_my_group_msg')
try it once it will help you your View code will look as like
<?php foreach($myKidsGroupID as $row): ?>
<label><input type="checkbox" name="user_my_group_msg" value="<?php echo $row->id; ?>" class="my_group_msg pull-right"><?php echo $row->firstname; ?> <?php echo $row->lastname; ?></label><br>
<?php endforeach; ?>
Model will be corrected like this
<?php
elseif(sizeof($this->input->post('user_my_group_msg'))>=1) {
foreach ( $this->input->post('user_my_group_msg') as $value ) {
$new_mail = array(
'to_user' => $value,
);
$this->db->insert('mailbox', $new_mail);
}
}
.....rest code
?>
In a table I've 3 columns nota1, nota2, nota3 of table Notas.
I want to calc the average of nota1, nota2, nota3
Then I want to save using beforeSave() method the average result on nota_final field
This is my code in the model Notas.php:
public function getAvg()
{
$avg = Yii::app()->db->createCommand()
->select('(nota1 + nota2 + nota3)/3 as NotaFinal')
->from('notas')
->queryRow();
return $avg;
}
protected function afterSave()
{
if($this->isNewRecord){
$this->nota_final->Avg();
$this->isNewRecord= false;
$this->nota_final->saveAttributes($_POST['nota_final']);
if($model->save() == false) var_dump($model->errors);
}
return parent::afterSave();
}
It's not saving the avg value and it's not display any error.
What's wrong?
my View/notas/_form.php
tr>
<td><div class="row2">
<?php echo $form->labelEx($model,'nota1'); ?>
<?php echo $form->textField($model, 'nota1', array('maxlength'=>'3')); ?>
<?php echo $form->error($model,'nota1'); ?>
</div></td>
<td>
<div class="row2">
<?php echo $form->labelEx($model,'nota2'); ?>
<?php echo $form->textField($model,'nota2', array('maxlength'=>'3', 'input'=>'20px')); ?>
<?php echo $form->error($model,'nota2'); ?>
</div>
</td>
<td>
<div class="row2">
<?php echo $form->labelEx($model,'nota3'); ?>
<?php echo $form->textField($model,'nota3', array('maxlength'=>'3')); ?>
<?php echo $form->error($model,'nota3'); ?>
</div>
<td>
<div class="row2">
<?php echo $form->labelEx($model,'nota_final'); ?>
<?php echo $form->textField($model, 'nota_final', array('readOnly'=>true)); ?>
<?php echo $form->error($model,'nota_final'); ?>
</div>
public function getAvg() // remove this method
{
}
protected function beforeSave() // change to beforeSave()
{
if($this->isNewRecord) {
// Copy attributes from $_POST
$this->nota_final->saveAttributes($_POST['nota_final']);
// Calculate average
$this->nota_final->avg =
($this->nota_final->nota1 + $this->nota_final->nota2 +
$this->nota_final->nota3) / 3;
// DO NOT NEED TO CALL ->save() here, it will result in loop.
// Do it in your controller, and this beforeSave method will be triggered
}
return parent::beforeSave(); // change to beforeSave
}
I've read all the posts I could find about this issue, but, to date, none of the solutions have worked for me. Obviously, I'm overlooking something important. I also don't know how to debug sessions. I read one article, PHP session Debugging, but it was over my head.
So, much like the other issues, when I navigate to another page in my app, whether through a link or a form submit, my session disappears. I have no idea why my session vanishes. If someone has the time to help me investigate, it would be greatly appreciated.
These are my php.ini settings
; Name of the session (used as cookie name).
session.name = PHPSESSID
; The path for which the cookie is valid.
session.cookie_path = /
This is the first view to display
<?php
session_start();
if (!isset($_SESSION['session_id'])) {
$_SESSION['session_id'] = session_id();
}
if (!isset($_SESSION['invoices'])) {
$_SESSION['invoices'] = $invoices;
}
if (isset($_SESSION['session_id'])) {
print_r($_SESSION['session_id'] . " in invoiceList.<br />");
} else {
echo 'No session ID set in invoiceList <br />';
}
?>
<div>
<table>
<tr>
<th>Customer Name</th>
<th>Invoice Date</th>
<th>Invoice Number</th>
</tr>
<tr>
<?php
include_once 'form/editInvoice.php';
if (isset($invoices)) {
foreach ($invoices as $invoice) {
?>
<tr>
<td><?php echo $invoice['customer_name'] ?></td>
<td><?php echo $invoice['invoice_date'] ?></td>
<td><?php echo $invoice['invoice_number'] ?></td>
<td><a href='<?php echo $_SERVER['SCRIPT_NAME']; ?>/retrieve?class=InvoiceLineItems&id=<?php echo $invoice['invoice_id']; ?>'><?php echo $invoice['invoice_id']; ?></a></td>
</tr>
<?php
}
} else {
echo 'No invoices retrieved.';
}
?>
</tr>
</table>
</div>
Here is the included form:
<?php
session_start();
if (isset($_SESSION['session_id'])) {
print_r($_SESSION['session_id'] . "in editForm<br />");
} else {
echo 'No session ID set in editForm <br />';
}
if (!$_POST) {
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<fieldset>
<legend>Enter Updated PO Number</legend>
<li>PO Number: <input type="text" name="po_number"/></li>
</fieldset>
<input type="submit" value="Submit" />
<input type="button" onclick="alert('Changes Canceled.')" value="Cancel"/>
</form>
<?php }
?>
And finally, the detail page for when the user clicks a link in the main page.
<?php
session_start();
if (isset($_SESSION['session_id'])) {
print_r($_SESSION['session_id'] . "<br />");
} else {
echo 'No session ID set invoice<br />';
}
?>
<h1>Invoice Detail</h1>
<div>
<?php
foreach ($partnerInfo as $info) {
switch ($info['role_indicator']) {
case 'remit_to':
?>
<div id="remit">
<ul>
<li>PLEASE REMIT TO:</li>
<li><?php echo $info['partner_name']; ?></li>
<li><?php echo $info['street_name']; ?></li>
<li><?php echo $info['city_name']; ?>, <?php echo $info['state']; ?> <?php echo $info['postal_code']; ?></li>
</ul>
</div>
<?php break; ?>
<?php case 'seller': ?>
<div id = "seller" >
<ul>
<li>Service Site:</li>
<li><?php echo $info['partner_name']; ?></li>
<?php
if ($info['partner_aux_info'] !== NULL) {
?><li><?php echo $info['partner_aux_info']; ?>
<?php }
?>
</li>
<li><?php echo $info['street_name']; ?></li>
<li><?php echo $info['city_name']; ?>, <?php echo $info['state']; ?> <?php echo $info['postal_code']; ?></li>
<li>(405)677-0221</li>
</ul>
</div>
<?php break; ?>
<?php case 'sold_to': ?>
<div id="buyer">
<ul>
<li>Bill To: </li>
<li><?php echo $info['partner_name']; ?></li>
<li><?php echo $info['street_name']; ?></li>
<?php
if ($info['suite_info'] !== NULL) {
?><li><?php echo $info['suite_info']; ?>
<?php }
?>
</li>
<li><?php echo $info['city_name']; ?>, <?php echo $info['state']; ?> <?php echo $info['postal_code']; ?></li>
</ul>
</div>
<?php break; ?>
<?php
}
}
?>
<h1>Line Items</h1>
<table>
<th>PO Number</th>
<th>PO Issued Date</th>
<th>Description</th>
<th>Service Start Date</th>
<th>Service End Date</th>
<th>Shipped Date</th>
<?php foreach ($invoiceLineItems as $lineItem) { ?>
<tr>
<td><?php echo $lineItem['po_number']; ?></td>
<td><?php echo $lineItem['po_issued_date']; ?></td>
<td><?php echo $lineItem['line_item_name']; ?></td>
<td><?php echo $lineItem['service_period_start']; ?></td>
<td><?php echo $lineItem['service_period_end']; ?></td>
<td><?php echo $lineItem['request_for_delivery']; ?></td>
</tr>
<?php
}
?>
</table>
</div>
Edit: I've removed the session checks and updated the code sample. I've added session_start() before my <head> tag in index.php. I've verified that I can write to the session temp folder.
When i execute this code in my controller to update the invoices with the new PO number, I reach the model's function, but the session is gone.
//If form is posted, update line items with PO number and date.
if (isset($_POST['po_number'])) {
$this->invoice->update();
}
By the time I reach the session variable assignment, I have no session data:
public function update() {
$con = $this->_getLocalConn();
$invoices = $_SESSION['invoices'];
try {
$sqlUpdate = $con->prepare("UPDATE invoices
SET po_number = ?, po_issued_date = ?
WHERE invoice_id = ?");
foreach ($invoices as $record) {
$sqlUpdate->execute(array(
$_POST['po_number'],
getdate(),
$record['invoice_id']
));
}
} catch (PDOException $e) {
print $e->getMessage();
}
//get the PO number being used to update the records
//perform db update where po_number = input
//notify user of success and display updated records.
}
Each PHP file should start with session_start(); regardless of $_SESSION being set or not. This function will create a new session OR take up the existing one.
No $_SESSION is started to begin with when you check it with your first if. Therefore, it will always FAIL. You must call session_start() PRIOR to doing anything with a $_SESSION variable. Correct your code.
First page:
<?php
session_start();
/* Don't need this unless you really need the debugging
Previously you where assigning variables that did not
exist to the the $_SESSION variables. Not what you want
I imagine.
if (!isset($_SESSION)) {
var_dump($_SESSION);
}
*/
...
Include form:
<?php
session_start();
if (isset($_SESSION['session_id'])) {
print_r($_SESSION['session_id'] . "in editForm<br />");
} else {
echo 'No session ID set in editForm <br />';
}
...
Detail page:
<?php
session_start(); //Notice a pattern here??
if (isset($_SESSION['session_id'])) {
print_r($_SESSION['session_id'] . "<br />");
} else {
echo 'No session ID set invoice<br />';
}
?>
All of your code that needs the session information should start with session_start(). session_start() needs to happen before any headers or other output would be written.
Setup and teardown are then handled for you.
I do this:
session_start();
$s = &$_SESSION;
Then you can use read/write $s just like it was $_SESSION
If you are doing self referencing image downloads or other code that may end up wanting to execute in parallel, NOT starting a session or closing it as soon as possible with session_write_close() will give you a significant performance boost.
Without this, sessions essentially make your code run single threaded.
Edit: Saying single threaded was perhaps a bad choice of words.
Lets say you had a page with three iframes in it, each one loading a different (or the same) php script. If you are using sessions, the result would be the iframes loading one at a time instead of all at once. Each one would get a lock on the session and the others would wait at session_start() until the session was available again.