How to unset specific session in my code below:
for($i=0;$i<count($_SESSION['src']);$i++)
{
?>
<tr>
<td><?php echo $_SESSION['name'][$i]; ?></td>
<td><?php echo $_SESSION['price'][$i]; ?></td>
<td>Hapus</td>
</tr>
<?php
}
if($_GET['delPrd']);
{
unset($_SESSION['name']);
unset($_SESSION['price']);
}
Example I have 3 data with each session id. Now I want to unset session by click each delete link.
How can I do that? So I click delete then it will hide the row that I clicked before in <tr>
I came across the same issue when using the unset(), I tried to debug it to see if it would ever unset using a simple while loop.
while(isset($_SESSION['...'])):
unset($_SESSION['...']);
endwhile;
This seems to work for me and actually unset the cache, it's like it needs to know its unset before continuing which makes no logical sense but that's code for you - you spend 50% of your time trying to fix code, the only 50% wondering how the hell it worked.
Hope this helped.
EDIT: You could make this into a reusable object, something like:
class SessionRemovale
{
public function Remove($param)
{
while(isset($_SESSION[$param])) {
unset($_SESSION[$param]);
}
}
}
Then use it like:
$session_controller = new SessionRemovale();
$session_controller->Remove("....");
$session_controller->Remove("....");
Related
I'm currently making a table where the email and phone number of clients are clickable. When you click it, it will redirect to another page and execute a filter search on that page.
I wanted to send the data of client email or phone number via the URL, but it seems you can only type in the exact filter search. I wanted when the user clicks a hyperlink it will send the clicked data via URL and execute the filter search.
<?php
foreach($checked_columns as $key=>$column){
if ($column){
if ($key == 'client_email'){?>
<td>
<?= $sale['client_email']; ?>
</td>
<?php } elseif ($key == 'client_phone_number') { ?>
<td>
<?= $sale['client_phone_number']; ?>
</td>
<?php } else {?>
<td><?= $sale[$key]; ?></td>
<?php }
}
}
?>
How can I change the last part of the URL so that it can search it via variable.
Your code can be refined/refactored to utilize the variable data.
foreach ($checked_columns as $key => $column) {
if ($column) {
echo "<td>";
if (in_array($key, ['client_email', 'client_phone_number'])) {
echo "{$sale[$key]}";
} else {
echo $sale[$key];
}
echo "</td>";
}
}
The $key value doesn't look like it needs to be encoded for insertion into the url, but the email seems like a good candidate.
By "staying in" php, I think you will find the snippet easier to read.
If I understand you correctly, currently you are outputting static text:
<a href="admin/sales/browse/confirmed-sale?fc=client_phone_number&fv=60192597698" class="style1">
And you want to output variables instead. Consider that you already have an example in your code of how to output the value from a variable:
<?= $sale['client_phone_number']; ?>
Simply apply that same exact operation for your URL. The only addition would be to ensure that you URL-encode the value, in case it has non-URL-friendly characters. Something like this:
<a href="admin/sales/browse/confirmed-sale?fc=client_phone_number&fv=<?= urlencode($sale['client_phone_number']); ?>" class="style1">
There are a variety of ways you can reorganize your code, perhaps putting the HTML into strings and using echo or perhaps applying a PHP templating engine to separate content from markup. How you organize it is really up to personal preference. But at its simplest, if you want to output a value then just output the value like you already do.
My problem is that I need to save a value from the link as a variable which will then do something. Below is my main code for this problem.
<table>
<? foreach ($csv as $row) : ?>
<tr>
<td><? echo $row[0]; ?></td>
</tr>
<? endforeach; ?>
</table>
Basically, it prints the first column from my array $csv. However I want to save the '$row[0]' for each link - depending on which one is clicked.
This happens here:
<?php
if (isset($_GET['GoToProfile'])) {
}
?>
This works. E.g. when something is clicked it prints something. But I cannot find a way to save the values from each link. Depending on which one is clicked. I have tried many different methods online, but none seem to work.
I have even tried:
<? echo $row[0]; ?>
Any help would be greatly appreciated.
Thanks!
Use an ampersand (&) instead of a question mark
<? echo $row[0]; ?>
The ? indicates the beginning of the query string, which is the data sent on a GET request. In most cases it is a collection of name/value pairs, separated with & s.
A simple example of a GET request
http://example.com?first=1&second=fifty
You would get the value of the parameters in PHP with $_GET
$first = $_GET['first'];
$second = $_GET['second'];
To see what the server is receiving, you can use var_dump
var_dump($_GET)
I am new to MVC & codeigniter and want to know whether its okay to have following types of code in view files
if(strcasecmp($_SESSION['role'],'author')==0)
{
some code
}
or
if($this->session->flashdata('edition_done_by'))
{
some code
}
i.e. checking existence of a session object or flashdata in a view file
Also,I would want to know whether creating table rows dynamically in a view file using foreach loop construct(like given below) is alright as per MVC
<?php foreach($items as $item){ ?>
<tr>
<td><?php echo $item->name; ?> </td>
<td><?php echo $item->price; ?> </td>
</tr>
<?php } ?>
Its not a good practice to check session values within the view. Check it within controller and pass the relevant data to view
It goes completely against the idea of the Model-View-Controller principe.
In (really) short; the model is responsible for managing data entities, CRUD operations, how a data entity should look like, etc. The controller is responsible for any business logic. Which means; when should I update a record, should this data be available to user x, etc. The view is merely responsible for displaying data that is already available. Nothing more, nothing less.
So in your example; the Controller should check session data, flash data, whatever, and send the processed data to the view. Eg:
if( strcasecmp($_SESSION['role'],'author') === 0 )
{
$can_edit = true;
$message = 'You can edit! Go ahead';
} else {
$can_edit = false;
$message = 'You do not have sufficient rights to edit this entity';
}
Now pass these variables to the view, there you can do something like:
<?php if ( $can_edit ): ?>
<form action="POST">
<p><?php echo $message; ?></p>
<textarea name="content"><?php echo $entity->content; ?></textarea>
<button type="submit">Update</button>
</form>
<?php else: ?>
<p><?php echo $message; ?>
<?php endif; ?>
One Word Answer is Yes! No Problem
It is fine to access Session Variables in Views . Session are variable to store information.
As Long as you are not putting Business Logic Inside Your View . you can use anything in views . The Case you mentioned you are using is What I will call "Display Logic" that is used to check which / What /From Where/ How content will be shown .
From Two Code Samples you Show Following One is Correct to Use with MVC
if($this->session->flashdata('edition_done_by'))
{
some code
}
You For Loop Code is also having no problem with MVC
This question is more about "good pratices" than a real problem; I just started with php and jquery, but I would know more in details what I'm doing and why.
What I'm trying to get: catch user request (with a form), query database and then show result in a table. All using ajax call and jquery.
Now, I have my controller.php:
class Controller {
public $model;
public function __construct() {
$this->model = new Model ();
}
public function run() {
$action = isset ( $_REQUEST ["action"] ) ? $_REQUEST ["action"] : $action = "home";
switch ($action) {
case "home" :
//doing stuff
break;
case "search" :
//this function will take arguments then perform a query and return results.
$result = $this->search();
//I put $result into a $prod field of my model.
$this->model->prod = $result;
//then I would display acquired data into a table.
echo include 'view/include/result-table.php';
break;
}
}
function search() {
//query DB etc..
}
}
And this is my table (view/include/result-table.php), I would like insert this into a div in my page.
<?php
if (isset ( $this->model->prod )) {
if (count ( $this->model->prod ) == 0) {
echo "<h4 class=\"info\"> No product find";
} else {
?>
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Descr</th>
<th>Qty</th>
</tr>
</thead>
<tbody>
<?php
foreach ( $this->model->prod as $p ) {
echo "<tr><td> $p->id </td>";
echo "<td>" . ucfirst ( $p->name ) . "</td>";
echo "<td>" . ucfirst ( $p->descr ) . "</td>"
// and so on..
}
?>
</tbody>
</table>
<?php
}
}
?>
Problem 1: the "echo include "view/include/....php" seems to echoes also a 1 (a digit) at the end of the page (or the div). Why?
"Problem 2": This is working pretty well, but I'm not sure that is the correct way to do this. Are there any other solutions to query a DB and display results in a div, with only jquery/ajax request? (I don't want a page refresh every time). Maybe something that can speed up responses and/or improves security.
Thank you very much!
For problem 1: include does not require an echo. Its including the content and the echos are inside the included php file. So the echo include is actualy echoing the result of include, which is true or 1 by success.
problem 2: You are right, ajax would be a solution without refreshing the whole page. All you need to do is to make an ajax request to your php script which returns just the html content you want to replace and append this result to your html dom. jQuery has lots of functions for both making ajax calls and appending the result in your html dom.
A good practice is not to return the raw html content and just append it to your site because if something went wrong you might receive error codes from php or warnings or even mysql errors which is bad to show on your website of course. So in order to tell your ajax request that the result is the expected one just send over a status flag with value true. A good way to do this is by sending the result as json encoded string like this:
{
status : true, //shows you your call was successfull
html : "your result html to place on your site"
}
Only if your ajax call returns the correct status (true) everything went well and you can insert it in your page.
I don't know how to add a comment and keep formatting... anyway:
Thanks for your reply.
I didn't understand the last part, right now I have my ajax call:
$('#submit-btn').click(function(event) {
event.preventDefault();
$.get("index.php", {action : "search" , data : mydata }).done(function(data) {
$('#result').html(data);
});
Removing echo the 1 disappeared, but I don't understand the flag you're talking about and what I should encode. The page I want to append? Only the result of query?
After querying DB, I update my model with new values (coming from db) and then I want to show updated table, in this way will I see the modified table?
I hope my question is clear... :)
Thanks a lot!
Im trying to delete an item from a session shopping cart. I used unset(), but somehow it didn't work
Link
<td width="100"><a href="?id=<?php echo $ids;?>&action=delete">
<?php echo $ids;?></a></td>
Unset
if(isset($_GET['action'])&&($_GET['action']=="delete"))
{
$new_id=$_GET['id'];
unset($_SESSION['items'][$new_id]);
}
unset session ok look this code result array(1) { ["id"]=> int(10) }
<?php
$_SESSION['items']=
array(
"id"=>10,
"new_id"=>6
);
unset($_SESSION['items']["new_id"]);
var_dump($_SESSION['items']);
?>
Always make sure the id you are passing as a get parameter is set properly, and analyse the structure of your session variable with a var_dump($_SESSION['items']), you should make sure it matches and comment your code as well.