Sharing a session variable between multiple php scripts - php

My question is that when I copy my array elements between different PHP scripts using session variables, nothing gets printed out. The following are my two PHP files.
file1.php
<?PHP
session_start();
$SQL = "SELECT * FROM tblquestions";
if ($db_found) {
$result = mysql_query($SQL);
$numRows = mysql_num_rows($result); //return number of rows in the table
echo '<FORM NAME ="form1" METHOD ="POST" ACTION ="file2.php">';
for ($i = 1; $i <= 2; $i++)
{
$db_field = mysql_fetch_assoc($result);
$qID[$i] = $db_field['QID'];
$question[$i] = $db_field['Question'];
$A[$i] = $db_field['qA'];
$B[$i] = $db_field['qB'];
$C[$i] = $db_field['qC'];
echo '<P>';
print $question[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'A'>";
print $A[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'B'>";
print $B[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'C'>";
print $C[$i];
//if (isset($_POST[$name_Value]))
$survey_Answers[$i-1] = $_POST[$qNum];
print '</BR>'.$survey_Answers[$i-1]."</BR>";
$question_Number = ltrim($qNum,'q');
$question_Number++;
$qNum ='q'.$question_Number;
}
echo '<p>';
$_SESSION['answers'] = $survey_Answers;
echo '<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Click here to vote">';
echo '</form>';
?>
On my Second file (file2.php), I have the following:
<?PHP
session_start();
if (isset($_POST['Submit1'])) {
$results = $_SESSION['answers'];
print $results[0];
}
?>
However, on my file2.php I get the following error: Undefined offset: 0 and nothing gets printed out.

echo '<p>';
session_start();
that can´t work, session_start has to be called before any output!
if you put session_start() at the beginning of your file, you should be all right.

To use cookie-based sessions, session_start() must be called before outputing anything to the browser.
source: http://php.net/manual/en/function.session-start.php
You need to call session_start() before you output anything. It is a best practice to place it at the beginning of your script before you output anything.

Please Add the below code to every page you want to use the session data.Other wise it will return an error .
<?php
session_start();
?>

in file1.php session_start(); should be first line of the code same as in file2.php

There is a comment on the PHP manual page for session_start() which sounds very similar to your problem. http://php.net/manual/en/function.session-start.php#65944
It says that an array with integer keys assigned either as a straight array or using the integers will fail and the data will not pass to the next page.
Modify your code to use strings as keys.

Related

How to create strings in for loop with SELECT using variable variables PHP

Where I made a mistake to get output like I wrote below?
Inside array are names of tables.
Let's say in those tables are 0 rows, so everywhere should be 0 as a output.
<?php
$g_module =
array(
'm_b_broadcast_live',
'm_b_browsing_live',
'm_e_askfm_likes_live',
'm_e_facebook_followers_live',
'm_e_facebook_group_joins_live',
);
for ($i = 0; $i <= 5; $i++) {
$modules_names = "g_module[$i]";
$modules_from = '$'.$modules_names;
$modules_rows = '$g_module_row_'.$i;
$$modules_rows = mysql_num_rows("SELECT * FROM $$modules_from");
}
echo $g_module_row_1;
echo '</br>';
echo $g_module_row_2;
echo '</br>';
echo $g_module_row_3;
echo '</br>';
echo $g_module_row_4;
echo '</br>';
echo $g_module_row_5;
/* output should be:
0
0
0
0
0
*/
?>
As stated in the comments to your question already, mysql_num_rows() takes a query result as parameter, not a query string.
Also, you should use mysqli! Look at the documentation here.
Something else that you can simplify is to escape the dollar sign so you don't have to concatenate one to $modules_names again.
The corrected code would look like this:
<?php
$g_module = [
'm_b_broadcast_live',
'm_b_browsing_live',
'm_e_askfm_likes_live',
'm_e_facebook_followers_live',
'm_e_facebook_group_joins_live',
];
// you have to create a connection to your database server first
// of course you will have to swap out my placeholders for the actual credentials
$con=mysqli_connect('mysql_server_address_here','username_here','password_here','database_name_here');
for($i=0;$i<=5;$i++){
$modules_from = "\$g_module[$i]";
$modules_rows = "\$g_module_row_$i";
$q=mysqli_query("SELECT * FROM $$modules_from");
//use mysqli_num_rows instead
$$modules_rows = mysqli_num_rows($q);
}
// close your connection after you are finished
mysqli_close($con);
echo $g_module_row_1;
echo '</br>';
echo $g_module_row_2;
echo '</br>';
echo $g_module_row_3;
echo '</br>';
echo $g_module_row_4;
echo '</br>';
echo $g_module_row_5;
<?php
$g_module =
array(
'm_b_broadcast_live',
'm_b_browsing_live',
'm_e_askfm_likes_live',
'm_e_facebook_followers_live',
'm_e_facebook_group_joins_live',
);
foreach($g_module as $table_name){
$count = mysql_num_rows("SELECT * FROM $table_name");
echo "<br/>".$count;
}
?>
I think you should try like this.

PHP-how to send data to another php-sql page and recive an chart image on the same page

PHP-how to send data to another php-sql page and recive an chart image on the same page
hi guys. i have an problem and i dont know how i could solve that. i have an mainpage, where i want to put some data in an input field, which would send
the data to an other page to create the chart. ok. thats not the problem. it works fine, if i open the secound page. the chart img is created. but if i want to stay on the mainpage klicking the button and recive the img from the secound page, the img is empty and i dont know how to realize that.
here is an short code of the mainpage.php
echo "<form action='#' method='post' type='text'>";
echo "Abzufragendes Jahr [JJJJ]:";
echo '<input type="text" name="eingabe_1" value="">';
echo "<input type='submit' name='eingabe_2' value='DB Abfrage'/>";
echo "<input type='submit' name='ausgabe_statistik' value='Charts erstellen'
formaction='#' formmethod='post'/></br></br></br></br>";
echo "</form>";
//Versuch das Bild zu erzeugen
if(isset($_POST['eingabe_1']) && isset($_POST['ausgabe_statistik'])) {
echo "<img src='charts/charts_jahr.php'> </br>";
}
and the secound page consists
include("../../PHP/pChart2.1.4/class/pData.class.php");
include("../../PHP/pChart2.1.4/class/pDraw.class.php");
include("../../PHP/pChart2.1.4/class/pImage.class.php");
include("../../SQL/log-in.php");
mysql_select_db(MYSQL_DATENBANK) or die("Auswahl der Datenbank fehlgeschlagen");
for ($a = 1 ; $a <= 365 ; $a++) {
$kalenderwoche[] = $a;
}
$var = $_POST['eingabe_11'];
$var_jahr = "j" . $var;
$Result = mysql_query("SELECT sum(gewicht) as gewicht_1 FROM $var_jahr group by datum",$db_link);
while($row = mysql_fetch_array($Result))
{
$gewicht[] = $row["gewicht_1"];
$fett[] = $row["fett"];
}
//chartpart
$myData = new pData();
$myData->addPoints($gewicht,"Serie1");
..
.
i thought over another solution to save the temp var in he sql and get the value for $var_jahr out of them. but i think thats not the solution right?
br and many thx for an solution!
My solution:
if ( isset($_POST['statistik_gewicht']) ) {
$var22 = $_POST['eingabe_1'];
mysql_query("update variablen set var1 = $var22 where id = 1");
mysql_query("update variablen set var_gewicht = 1 where id = 1");
echo "<div align='center'><img src='charts/charts_jahr.php'></div> </br>";
}
Not well, but it works! Write an tmp var over
echo '<td colspan="3">Abzufragendes Jahr [JJJJ]'; echo '<input type="text" name="eingabe_1" value="">';

How to send the values of a php array of classes from a php file to another php file

i have an array of classes in a php file, this class has 3 fields, and i am using these fields to save the values of SELECTS and INPUT CHECKBOXs inside a FORM using POST, then i need to send this array of classes to another php file for proccessing data.
<?php
class info_subject{
public $code_as;
public $time_as;
public $selectionn_as;
}
$subjects[0] = new info_subject();//The only way I have seen for creating an array of classes
//is with a for loop, but if you have a better way for doing this, please let me know
$subjects[1] = new info_subject();
//here i am using the fields to save info in a form
$i=0;
echo "<form name = 'formsubjects' method='post' action='file2.php'>";
echo "<select name=\"".$subjects[$i]->time_as ."\">";
//options
echo "</select>";
echo "<input type='checkbox' name=\"".$asignaturas[$i]->selection_as."\">";
//and so on with every position of the array using $i
?>
//then there is a button to send the the dato to file2.php
//file2.php
<?php
$subjects=$_POST["$subjects"];//I am using this but i cant retrieve the fields of $subjects
?>
What can i do buddies?
instead of:
$i=0;
echo "<form name = 'formsubjects' method='post' action='file2.php'>";
echo "<select name=\"".$subjects[$i]->time_as ."\">";
//options
echo "</select>";
echo "<input type='checkbox' name=\"".$asignaturas[$i]->selection_as."\">";
you can try something like:
$i=0;
echo "<form name = 'formsubjects' method='post' action='file2.php'>";
echo "<select name=\"subjects[$i][".$subjects[$i]->time_as ."]\">";
//options
echo "</select>";
echo "<input type='checkbox' name=\"subjects[$i][".$asignaturas[$i]->selection_as."]\">";
and then in file2
$subjects=$_POST["subjects"];
and pick off what you need.
To be honest, I find your question hard to understand. Maybe try streamlining your problem and clean up some code/formatting and it will be easier for us to give you advice.
You can't submit a class or array via $_POST because the post array is an array which can only contain simple values.
Hi~ Jose Ricardo Citerio. I hope you can read Chinese
我不知道你是不是需要这样,在file1里面存储着select的option选项。然后file2接收去后处理
<?php
class info_subject{
public $code_as = ['name' => 'select_name', 'option' => ["k" => "v"]];
public $time_as;
public $selectionn_as;
}
$subjects = new info_subject();
echo "";
echo 'code_as["name"] . '">"';
//loop options for $subjects["option"] and print k and v; like => foreach($subjects->code_as["name"] as $k => $v){echo '' . $v . '';}
echo "";
echo 'xxx['name'] . '">please check';
?>
//then there is a button to send the the dato to file2.php
//file2.php
<?php
$subjects = $_POST["select_name"];
$subjects1 = $_POST["checkbox_name"];
?>

I already tried solving this with html array input name, it works on my sample but it doesn't during my implementation to my website

I already tried solving this problem with html array input name, it works on my sample but it doesn't during my implementation to my website.
This is my code for the Page.php
<form action = "POST" action = "Comments.php">
<?php
$x = 0;
while ($getRows = mysql_fetch_array($iQuer)){
echo "<input type = 'text' name = 'thes[ths][]' placeholder = 'Write a comment..'>
<a href = 'Comments.php?idy=".$_SESSION['ids']."&pageid=".$getRows['id']."&pagecount=".$x."'>";
$x++;
}
?>
</form>
Comments.php
<?php
session_start();
mysql_connect("127.0.0.1", "root", "toor");
mysql_select_db("matutorials");
$c = $_GET['pagecount'];
$d = $_POST['thes']['ths'][$c];
$a = $_GET['idy'];
$b = $_GET['pageid'];
echo $a ."<br>" . $b . "<br>";
echo $d;
?>
i do not have an idea if POST and GET is available/functioning at same time.
But according to my sample, it throws an error and searching for the undefined variable thes whenever i put $_GET superglobals on my another page where navigation happens.

I want to increment a value from outside a php block

Basically its a web page where someone would press a button to increment the $selection variable. Globals and statics do not seem to work.
Code looks like this:
<?php
if(isset($_POST['next']))
{
displaynext();
}
else
{
global $image_folder = "/images/";
echo "global declared";
global $selection;
$selection = 1;
}
function displaynext()
{
$selection++;
if (file_exists($image_folder."/".$selection.".png")) {
echo "<img src=\"$image_folder/".$selection.".png\">";
}
else {
echo "No next image was found for $selection in ".$image_folder."/".$selection.".png";
}
?>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<input type="submit" name="next" value="Next">
</form>
Once PHP runs and the output is sent to the client, the code will not run unless the page is requested again from the server. You could create a session variable and use that to store the variable across page requests. You need to either access the page again or perform an AJAX request to call your PHP code again.
Instead of using Global, why don't you use a $_SESSION var?
Put:
global $selection
inside your function, so:
global $selection;
$selection++;
Just use another form element.
<input type=hidden name=selection value=1>
Do a sanity check like is_numeric on $_POST['selection'] before displaying the image tag. If $_POST['selection'] is set, increment it for the input tag above.
Full example:
<?php
$selection = 0;
$image_folder = "images/";
if (isset($_POST['selection'])) {
$userSelection = $_POST['selection'];
if (is_numeric($userSelection) && file_exists($image_folder . $userSelection)) $selection = $userSelection;
}
echo "<img src=\"images/" . $selection . ".png\">";
echo "<form action=\"" . $_SERVER['PHP_SELF'] . "\" method=post>";
echo "<input type=hidden name=selection value=\"" . ($selection + 1) . "\">";
echo "<input type=submit name=subnext value=\"Next\">";

Categories