I'm calling a specific function, either getTaskList0, getTaskList1, or getTaskList2, each the same as below, with the number after task referring to the getTaskList number (in TaskManagerDAO):
function getTaskList0(){
$lst=array();
$con=$this->getDBConnection();
$result = $con->query("SELECT name, score FROM task0 ORDER BY score DESC");
$i = 0;
$counter=0;
while (($row =$result->fetch_row()) && ($counter<5)) {
$rec = new Task($row[0],$row[1]);
$lst[$i++]=$rec;
$counter++;
}
return $lst;
}
Task:
<?php
class Task{
public $name;
public $score;
function __construct($name,$score) {
$this->name = $name;
$this->score = $score;
}
}
The function is called in here:
<?php
session_start();
if(!class_exists('Action')){
include_once 'Action.php';
}
if(!class_exists('TaskManagerDAO')){
include_once 'TaskManagerDAO.php';
}
class Action_DisplayList implements Action{
public function execute($request){
if(!isset($_SESSION['functCount']))
$_SESSION['functCount']=0;
$functCount=$_SESSION['functCount'];
$functionName="getTaskList{$functCount}";
echo $functionName;
$dao = new TaskManagerDAO();
$names = $dao->$functionName();
$_SESSION['names'] = $names;
$last = sizeof($names);
$start = 0;
$_SESSION['start'] = $start;
$_SESSION['last'] =$last;
header("Location: tasklist.php");
}
}
?>
I'm trying to call the function by putting a variable at the end of the function name as a string and then calling the function. This works as I don't get any errors, but the list does not show up in the table, which is what this code is supposed to do:
<?php
if(isset($_POST['Add']) && ($_POST['name']!=="") &&!empty($_POST['Add'])){
include 'Action_Add.php';
Action_Add::execute();
}
$functCount=0;
$_SESSION['functCount']=0;
$names = $_SESSION['names'];
$start=$_SESSION['start'];
$last = $_SESSION['last'];
for($count = $start; $count < $last; $count++){
$name=$names[$count];
echo "<tr>";
echo "<td>".($count+1)."</td>";
echo "<td>".$name->name."</td>";
echo "<td>".$name->score."</td>";
echo "</tr>";
}
?>
EDIT:
I restarted my computer and everything and for the first run load of the page it worked perfectly. After that though, it stopped working though.
Use session_start(); before start using $_SESSION. So in your case, try something like
<?php
session_start();
if(isset($_POST['Add']) && ($_POST['name']!=="") &&!empty($_POST['Add'])){
//.... remaining code here
Note: To use cookie-based sessions, session_start() must be called before outputing anything to the browser.
Related
I'm trying to add 1 to a number each time a function is called, but for some reason, the total number is always same.
Here is my current code:
<?php
$total;
function draw_card() {
global $total;
$total=$total+1;
echo $total;
}
draw_card();
draw_card();
?>
Personally, I would not use globals, but if I was forced at gunpoint I would handle state within the function, so outside variables did not pollute the value. I would also make an arbitrary long key name which I would not use anywhere else.
<?php
function draw_card($initial = 0) {
$GLOBALS['draw_card_total'] = (
isset($GLOBALS['draw_card_total']) ? $GLOBALS['draw_card_total']+1 : $initial
);
return $GLOBALS['draw_card_total'];
}
// optionally set your start value
echo draw_card(1); // 1
echo draw_card(); // 2
https://3v4l.org/pinSi
But I would more likely go with a class, which holds state by default, plus its more verbose as to whats happening.
<?php
class cards {
public $total = 0;
public function __construct($initial = 0)
{
$this->total = $initial;
}
public function draw()
{
return ++$this->total;
}
public function getTotal()
{
return $this->total;
}
}
$cards = new cards();
echo $cards->draw(); // 1
echo $cards->draw(); // 2
echo $cards->getTotal(); // 2
https://3v4l.org/lfbcL
Since it is global already, you can use it outside the function.
<?php
$total;
function draw_card() {
global $total;
$total=$total+1;
//echo $total;
}
draw_card();
draw_card();
draw_card();
echo "Current Count :", $total;
?>
Result :
Current Count :3
This will increment the number of times you call the function.
Since you echoed the result/total each time without a delimiter, you might have considered the output to be 12(Assumption)
Functions have a scope.. you just need to bring $total into the scope of the function... best to not do it globally but as an argument.
$total = 0;
function draw_card($total) {
return $total + 1;
}
$total = draw_card($total);
//Expected Output = 1
$total = draw_card($total);
//Expected Output = 2
I am trying to get dynamic $_SESSION[$id] on the second page shown below, but its not working (as per the printout):
First page url
https://example.com/test.php?id=1548393
First page code
<?php
session_start();
$id = $_GET['id'];
$_SESSION[$id] = "mysecretstringline";
?>
Second page url
https://example.com/test2.php?id=1548393
Second page code
<?php
session_start();
$id = $_GET['id'];
if(isset($_SESSION[$id])){
echo "working";
}else{
echo "not working";
}
?>
i found problem we can not use numeric index for $_SESSION
but we can use number in $_SESSION by convert number to roman numerals
first page url
https://example.com/test.php?id=1548393
first page code
<?php
session_start();
$roman_id = romanic_number($_GET['id']);
$_SESSION[$roman_id] = "mysecretstringline";
function romanic_number($integer, $upcase = true)
{
$table = array('M'=>1000, 'CM'=>900, 'D'=>500, 'CD'=>400, 'C'=>100, 'XC'=>90, 'L'=>50, 'XL'=>40, 'X'=>10, 'IX'=>9, 'V'=>5, 'IV'=>4, 'I'=>1);
$return = '';
while($integer > 0)
{
foreach($table as $rom=>$arb)
{
if($integer >= $arb)
{
$integer -= $arb;
$return .= $rom;
break;
}
}
}
return $return;
}
?>
second page url
https://example.com/test2.php?id=1548393
second page code
<?php
session_start();
$roman_id = romanic_number($_GET['id']);
if(isset($_SESSION[$roman_id])){
echo "working";
}else{
echo "not working";
}
function romanic_number($integer, $upcase = true)
{
$table = array('M'=>1000, 'CM'=>900, 'D'=>500, 'CD'=>400, 'C'=>100, 'XC'=>90, 'L'=>50, 'XL'=>40, 'X'=>10, 'IX'=>9, 'V'=>5, 'IV'=>4, 'I'=>1);
$return = '';
while($integer > 0)
{
foreach($table as $rom=>$arb)
{
if($integer >= $arb)
{
$integer -= $arb;
$return .= $rom;
break;
}
}
}
return $return;
}
?>
output
working
thanks #gre_gor and #Katie
Could be that in your normal code (this just looks like a quick mockup), you have a space after ?> somewhere. That could cause issues.
<?php
// start.php
session_start();
$id = $_GET['id'];
$_SESSION[$id] = "mysecretstringline";
and
<?php
// next.php
session_start();
$id = $_GET['id'];
if (isset($_SESSION[$id])) {
echo "working";
} else {
echo "not working";
}
works for me. Notice no ?> characters.
UPDATE:
The following might be of interest regarding session name constraints (can a php $_SESSION variable have numeric id thus : $_SESSION['1234’])
You have that issue in your example you could just add an id_ and then do the same check when validating/getting the session.
I was doing this code for my project and it seems that I can't get the values of the query into $currentRow. All that saved into the variable $currentrow is 22 which is the number rows in the database. I want to have access to all the query results. Please help. Here's the code.
public function getBSIConfig(){
$conn = oci_connect("472proj","system","//localhost/XE");
$sql = oci_parse($conn,"SELECT conf_id, conf_key, conf_value FROM bsi_configure");
oci_execute($sql);
echo "0";
while($currentRow = oci_fetch_all($sql,$res)){
echo "1.5";
echo $currentRow;
if($currentRow["conf_key"]){
echo "1";
if($currentRow["conf_value"]){
$this->config[trim($currentRow["conf_key"])] = trim($currentRow["conf_value"]);
echo "2";
}else{
$this->config[trim($currentRow["conf_key"])] = false;
echo "3";
}
}
}
}
And the output is only:
0
1.5
22
The results from this function are stored in the 2nd argument, rather than returned directly. See if this works for you:
$results = array();
$numResults = oci_fetch_all($sql, $results);
foreach ($results as $result) {
if ($result["conf_key"]) {
// etc ...
}
}
Read this http://php.net/manual/en/function.oci-fetch-all.php , you might get an idea what's wrong.
I am writing code for math problems -- they follow a format, with randomly generated variables, and then I lock in the variables per the code below. What isn't working -- form03 allows the user to finish the page of math problems and to reset for another. I need to destroy the session on that condition. But even when I enter data in form03, so that it isset, the old session values remain.
???
require_once 'random.php';
require_once 'forms-functions.php';
if (isset($_SESSION['z'])) {
$_SESSION['y'] = "";
session_start();
session_destroy();
}
session_start();
if (isset($_SESSION['y'])) {
echo "hello isset<br>";
$x01 = $_SESSION['x01'];
$x02 = $_SESSION['x02'];
$output01b = $_SESSION['output01b'];
$output02b = $_SESSION['output02b'];
} else {
echo "hello else<br>";
ob_start();
random1();
$output01 = ob_get_clean();
$output01b = "single string: ".$output01."";
$x01 = $x;
ob_start();
random1();
$output02 = ob_get_clean();
$output02b = "single string: ".$output02."";
$x02 = $x;
$_SESSION['x01'] = $x01;
$_SESSION['x02'] = $x02;
$_SESSION['output01b'] = $output01b;
$_SESSION['output02b'] = $output02b;
$y = "1";
$_SESSION['y'] = $y;
}
echo $output01b;
$user_input01 = form01('user_input01');
echo $output02b;
$user_input02 = form02('user_input02');
$user_input03 = form03('user_input03');
if(isset($user_input03)) {
$z = 1;
$_SESSION['z'] = $z;
echo "hello \$z";
}
You need to call session_start() before you try to access the session variable z. And you need to set the new session variable y after you destroy the old session and start a new one.
session_start();
if (isset($_SESSION['z'])) {
session_destroy();
session_start();
$_SESSION['y'] = "";
}
In order to generate a XML i am using following Code currently.
.<?php
require ('../dbconfig/dbconfig.php');
$appId = $_GET['id'];
$sqlTabs = "Select _id,tab_title,position from tab_info where app_id=$appId order by position ";
$resultTabs=mysql_query($sqlTabs );
$countTabs=mysql_num_rows($resultTabs);
if($countTabs>0)
{
echo '<application applicationName="sample app">';
echo '<tabs>';
while ($rowTab = mysql_fetch_array($resultTabs) ) {
echo '<tab id="t'.$rowTab['_id'].'" tabtitle="'.$rowTab['tab_title'].'" position="'.$rowTab['position'].'" data="somedata">';
$sqlTabItems = "Select _id as tabitemId,item_type,item_title,item_data from items_info where tab_id=".$rowTab['_id']." and parent_id=0 order by _id ";
$resultTabItems=mysql_query($sqlTabItems);
$countTabItems=mysql_num_rows($resultTabItems);
if($countTabItems>0)
{
$level = 1;
echo '<listItems>';
while ($rowTabItem = mysql_fetch_array($resultTabItems) ) {
echo '<listItem id="'.$rowTabItem['tabitemId'].'" parentId="t'.$rowTab['_id'].'" itemtype="'.$rowTabItem['item_type'].'" itemtitle="'.$rowTabItem['item_title'].'" itemdata="'.$rowTabItem['item_data'].'" level="'.$level.'">';
giveitems($rowTabItem['tabitemId'],$rowTab['_id'],$level);
echo '</listItem>';
}
echo '</listItems>';
}
else
echo 'No Data';
echo '</tab>';
}
echo '</tabs></application>';
}
else
{
echo 'No Data';// no tabs found
}
function giveitems($pitemId,$tabId,$level)
{
$sqlItems = "Select _id,item_type,item_title,item_data from items_info where parent_id=".$pitemId." order by _id ";
$resultItems=mysql_query($sqlItems);
$countItems=mysql_num_rows($resultItems);
$numbers = 0;
if($countItems>0)
{
$level = $level +1;
echo '<listItems>';
while ($rowItem = mysql_fetch_array($resultItems) ) {
echo '<listItem id="'.$rowItem[0].'" parentId="'.$pitemId.'" itemtype="'.$rowItem[1].'" itemtitle="'.$rowItem[2].'" itemdata="'.$rowItem[3].'" level="'.$level.'">';
/*********** Recursive Logic ************/
if(giveitems($rowItem[0],$tabId,$level)==1)
{
echo '</listItem></listItems>';
return 1;
}
else
{
echo '</listItem></listItems>';
return -1;
}
}
}
else
{
echo 'No Data';// no tabs found
return -1;
}
}
?>
Now in this code i want to replace all echo statements with a String variable and then i want to write that String variable content into a file , the porblem is if i define the string variable at the top of the file even then also that string variable cannot accessible from the giveItems functions below.
Pls suggest some solution
To access a global variable from within a function you need to write global $varname; at the top of that function's definition. Example:
function giveitems($pitemId,$tabId,$level) {
global $xmlstring;
// ....
}
However, this is pretty bad practice nowadays and you'd be better off writing a class that will both produce the XML and write it to a file.