Dynamically changing a session variable in php? - php

I have tried searching the site before posting and not finding anything about this. Forgive me if I am mistaken. What I am doing is making a calendar system. Each day is populating with the proper events and time, and I have a link in the <td> pointing to another php page for a longer description of the event. I have a foreach loop in a function that creates the calendar after getting the query from the database. I am assigning the long description row to a session variable and then printing it in the description.php page. My issue is the session variable is not changing during each iteration of the loop. Is this possible to do it this way? Was hoping I could just reference one variable to display the information, but I am doing something wrong. Any advice is appreciated!
Code in calendar.php
if(isset($events[$event_day])) {
foreach($events[$event_day] as $event) {
$calendar.= '<div class="event">'.$event['title'].'<br>'.$event['time'].'<br>'.$event['shortDesc'].'<br>More</div>';
$_SESSION['desc']= $event['longDesc'];
}
}
Code in description.php
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
include ('../dbinfo.php');
session_start();
$db=mysqli_connect($dbhostname,$dbuser,$dbpass,$dbname[0]);
print($_SESSION['desc']);
//print("<br><br>");
//print("Time:");
mysqli_close($db);//Close the DB Connection
?>
If any more code is needed to see what I am trying to accomplish I will edit this post! And yes, I have session_start() on the calendar page. The session is printing but not updating for each different event_date.

Try this:
<?php
if (isset($events[$event_day])) {
$_SESSION['desc'] = [];
foreach ($events[$event_day] as $event) {
$calendar .= '<div class="event">' . $event['title'] . '<br>' . $event['time'] . '<br>' . $event['shortDesc'] . '<br>More</div>';
$_SESSION['desc'][] = $event['longDesc'];
}
}
What the code does here is to assign an empty array to $_SESSION['desc'] before adding elements to the array. The error you got saying "operator not supported for strings" is because $_SESSION['desc'] was not an array.

Related

How to update an array in another PHP file?

I have index.php file and it contains:
1.class eachObject
class eachObject
{
function outPut()
{
echo '<td> </td>';
}
}
2.class wall
class wall extends eachObject
{
function outPut()
{
echo '<td class="wall"> </td>';
}
}
3.class blank
class blank extends eachObject
{
function outPut()
{
echo '<td class="blank"> </td>';
}
}
I got instances from them:
$wall = new wall();
$blank = new blank();
and I have an array called room including wall and blank:
$room = array();
$room[0] = array($wall, $wall, $blank, $wall, $blank);
and then I will use it in a table to show walls and blanked areas:
<html>
<body>
<?php
echo '<table>';
foreach ($room as $row) {
echo '<tr>';
foreach ($row as $tool) {
$tool->outPut();
}
echo '</tr>';
}
echo '</table>';
?>
</body>
</html>
The question is: how can I change this array in another php file called test.php to have:
$room[0] = array($wall, $wall, $wall, $wall, $blank);
As you can see, the third value changed from $blank to $wall.
and then when I refresh the div which contains the table, I will have a wall instead of blank area.
Since test.php is included/required to index.php, $rooms can be modified there using
$rooms[0][3] = $wall;
but note that this is only possible if both $rooms and $wall are reachable. If you declare them as globals before you include/require test.php and after you include/require index.php you do some changes for $room[0], then it should work and you should have a new value. From your description it seems that you either included/required test.php before $rooms and/or $wall is defined, or the variables are out of context, for instance, inside a function. You will need to make sure that the variables are reachable in the other file and when the other file starts to use them, they are already declared. However, you might want to rethink the way your code is structured and use some ideas like MVC. If this answer is not enough for you to solve your problem, then you will need to add more details about your code.
Create a functional construct (class with methods, function, ...) that first deletes your old test.php file, then creates a new one, adding line by line the content you wanted to add. (See the Php filesystem functions for such an application)
That is a way that works, but it is not a way I would recommend. (But I do not know your project, I might not see the whole image) Better would be a way using a serialised array. So you serialise your new array, save that string to your file and each time you want to use your array, just deserialise the string in your file. And last method: use a database, if possible.
you can change the value per
$room[0][3] = $wall;

Data wasn't able to retrieve from the previous page (PHP and MYSQL)

I researched here in stackoverflow trying to find whether someone is also encountering the same problem. I know it's kind of easy and even I really don't know what's the error because there's no problem with my query.
On the previous page, here's my code to retrieve the ID Number so I'll be able to select the data with that ID number:
<?php echo $row['place_name'];?>
I tried first to print the value of the place id and it works fine.
But when it was being called to the Package page, the data I want to show weren't displayed.
I look at the URL and it shows this after the package.php
place_id=
I don't know why it is blank, please check my code if there's missing or just wrong.
In my package page, here's the PHP code:
<?php
include("common/connect.php");
$place_id = $_GET['place_id'];
$result = mysql_query("SELECT * FROM package_items WHERE place_id = '$place_id'");
$row1 = mysql_fetch_array(mysql_query("SELECT place_name FROM packages WHERE place_id = '$place_id'"));
if($result === FALSE) {
die(mysql_error()); // for better error handling
}
?>
In HTML Code:
<h1><?php echo $row1['place_name'];?></h1>
<?php while($row=mysql_fetch_array($result)) {?>
<?php echo $row['item_title'];?>
<br>
Back
<?php } ?>
Please check my codes. Thanks.
You are not printing it.
Change
<?php $row['place_id'];?> // It will output nothing as no echo or print.
To
<?php echo $row['place_id'];?>
Rest of the code looks fine.
Three suggestions:
1)
$place_id = $_GET['place_id'];
Change to
$place_id = ! empty($_GET['place_id']) ? $_GET['place_id'] : ''; // To avoid any warning.
2) Don't feed variable from $_GET or $_POST to any SQL.
3) Don't use mysql_ functions as they are deprecated and will be remove in future versions of PHP.

The best way to convert the name of a PHP array to a string [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
I have an HTML table, linked to PHP $_SESSION data, to which I wish to add a Delete button to every row that deletes not only that row from the HTML table, but also from the $_SESSION variable.
This is the code that populates my table:
tableData.php
// echo the table headings
echo <<<HERE
<tr>
<th>CityID</th>
<th>State</th>
<th>City</th>
<th></th>
</tr>
HERE;
if (isset($_SESSION['cityData']))
{
foreach($_SESSION['cityData'] as $city)
{
echo "<tr>";
// print each row of data
foreach($city as $data)
{
echo "<td>" . $data . "</td>";
}
//echo '<td><button action="<?php unset(' . $_SESSION['cityData'][key($_SESSION['cityData'])] . ')?>">Delete Row</button></td>';
echo "</tr>";
}
}
The line that I commented out,
echo '<td><button action="<?php unset(' . $_SESSION['cityData'][key($_SESSION['cityData'])] . ')?>">Delete Row</button></td>';
is the line that creates the button that I am trying to create, to do what I am wanting it to do. I am trying to figure out the best way to name the array that I want gone.
P.S. I know, I should have it invoke some other function that does both tasks, it is just, if I pass the array in like I did, it will complain of " Array to string conversion ". Is there a way to do what I am trying to do, cleanly?
It's just not that simple. You need to get your buttons to submit to a link, and then have the PHP unset the content.
foreach($_SESSION['cityData'] as $index => $city) //added $index =>
{
echo "<tr>";
// print each row of data
foreach($city as $data)
{
echo "<td>" . $data . "</td>";
}
echo '<td><form method="post" action=""><input type="hidden" name="delete" value="' . $index . '"><input type="submit" value="Delete Row"></form></td>';
echo "</tr>";
}
So I added a form that a button that will submit to data that indicates the row number, so when your client clicks on the button, it will submit them and the row number will be passed as a POST variable.
At the top of tableData.php, you can then have logic handling the delete. Simply check if the delete is set, and then attempt to unset from there.
if (isset($_POST['delete']))
unset($_SESSION['cityData'][$_POST['delete']]);
You will want to have further validation that checks if POST delete within the bounds of $_SESSION['cityData'], but the basic idea is there.
You're mixing client-side and server-side code the wrong way here :(
The "client" is something like a user's browser. When a user clicks that button on their browser, it will run client-side code (i.e. JavaScript) - your PHP won't exist anymore at that stage so you don't have access to that array.
PHP is executed when a page has been requested from your server. That's when you can perform whatever computation you need and then deliver a textual response (via echo for example) back to the user's browser or whatever the client may be.
That button should make another request to your server so you can use PHP to delete the row. Then your PHP server should echo a response back to the requesting browser so users can know if it worked or not.
The link on the button will need to be provided some additional details, like the index of the row that the user wants to delete, so the PHP script doesn't delete the wrong one. See Dave Chen's answer below for some example code.

HREF to call a PHP function and pass a variable?

Is it possible to create an HREF link that calls a PHP function and passes a variable along with it?
<?php
function sample(){
foreach ($json_output->object ){
$name = "{$object->title}";
$id = "{$object->id}";
print "<a href='search($id)' >$name</a>";
}
}
function search($id){
//run a search via the id provide by the clicking of that particular name link
}
?>
You can do this easily without using a framework. By default, anything that comes after a ? in a URL is a GET variable.
So for example, www.google.com/search.html?term=blah
Would go to www.google.com/search.html, and would pass the GET variable "term" with the value "blah".
Multiple variables can be separated with a &
So for example, www.google.com/search.html?term=blah&term2=cool
The GET method is independent of PHP, and is part of the HTTP specification.
PHP handles GET requests easily by automatically creating the superglobal variable $_GET[], where each array index is a GET variable name and the value of the array index is the value of the variable.
Here is some demo code to show how this works:
<?php
//check if the get variable exists
if (isset($_GET['search']))
{
search($_GET['search']);
}
function Search($res)
{
//real search code goes here
echo $res;
}
?>
Search
which will print out 15 because it is the value of search and my search dummy function just prints out any result it gets
The HTML output needs to look like
anchor text
Your function will need to output this information within that format.
No, you cannot do it directly. You can only link to a URL.
In this case, you can pass the function name and parameter in the query string and then handle it in PHP as shown below:
print "<a href='yourphpscript.php?fn=search&id=$id' >$name</a>";
And, in the PHP code :
if ($_GET['fn'] == "search")
if (!empty($_GET['id']))
search($id);
Make sure that you sanitize the GET parameters.
No, at least not directly.
You can link to a URL
You can include data in the query string of that URL (<a href="myProgram.php?foo=bar">)
That URL can be handled by a PHP program
That PHP program can call a function as the only thing it does
You can pass data from $_GET['foo'] to that function
Yes, you can do it. Example:
From your view:
<p>Edit
Where 1 is a parameter you want to send. It can be a data taken from an object too.
From your controller:
function test($id){
#code...
}
Simply do this
<?php
function sample(){
foreach ($json_output->object ){
$name = "{$object->title}";
$id = "{$object->id}";
print "<a href='?search=" . $id . "' > " . $name . "</a>";
}
}
if (isset($_REQUEST['search'])) {
search($_REQUEST['search']);
}
function search($id){
//run a search via the id provide by the clicking of that particular name link
}
?>
Also make sure that your $json_output is accessible with is the sample() function. You can do it either way
<?php
function sample(){
global $json_output;
// rest of the code
}
?>
or
<?php
function sample($json_output){
// rest of the code
}
?>
Set query string in your link's href with the value and access it with $_GET or $_REQUEST
<?php
if ( isset($_REQUEST['search']) ) {
search( $_REQUEST['search'] );
}
function Search($res) {
// search here
}
echo "<a href='?search='" . $id . "'>" . $name . "</a>";
?>
Yes, this is possible, but you need an MVC type structure, and .htaccess URL rewriting turned on as well.
Here's some reading material to get you started in understanding what MVC is all about.
http://www.phpro.org/tutorials/Model-View-Controller-MVC.html
And if you want to choose a sweet framework, instead of reinventing the MVC wheel, I highly suggest, LARAVEL 4

Using PHP function to create a dynamic dropdown menu using arrays: dropdown doesn't populate

I am trying to dynamically build a drop down menu using PHP. The idea is: the elements are formed from a loop which calls and array. If the array element matches the data held in session then it adds the "selected" attribute to the tag, meaning that the page displays the previously selected option.
I have tried to include one complete set of code here, all the way from defining the variables from session data to echoing the HTML for the form element.
It doesn't currently work - the drop down menu appears, but is blank, and has no options. I've debugged it with ideone and it seemed to run successfully, and I can't see where I am going wrong, however this is my first PHP function! So I'm sure I've screwed it up somehow :)
Any help much appreciated.
<?php
session_start();
//if the session data has been set, then the variable $sv_02 is defined
//as the data held in the session under that name, otherwise it is blank
if (isset($_SESSION['sv_02'])) {$sv_02=$_SESSION['sv_02'];} else {$sv_02="";}
//define the array
$dm_sv_02 = array('-Year','-2012','-2011','-2010','-2009');
//create the function
function dropdown($dropdownoptions, $session_data)
{
foreach($dropdownoptions as $dropdownoption){
if($session_data == $dropdownoption){
echo '<option value="' . $dropdownoption . '" selected>' . $dropdownoption . '</option>';
} else {
echo '<option value="' . $dropdownoption . '">' . $dropdownoption . '</option>';
}
}
}
//echo the HTML needed to create a drop down, and populate it with
//the function which should create the <option> elements
echo '<select name="sv_02">';
dropdown($dm_sv_02, $sv_02);
echo '</select>';
?>
Try this:
foreach ($dropdownoptions as $dropdownoption) {
echo ($dropdownoption == $sv_02) ? "<option selected=\"selected\" value=\"$dropdownoption\">$dropdownoption</option>" : "<option value=\"$dropdownoption\">$dropdownoption</option>";}
This turned out to be a result of the fact I was using {smarty} tags to build my php, the code was as written but only worked when it was all included in one smarty tag, I'm not sure I understand why that should be the case but in any regard it was fixed by including it all in one tag.

Categories