Nenad Milosavljevic
Nenad Milosavljevic

Reputation: 147

php can't add data to array

here's a question : After entering some data about students, i need to print them in top side of the page (form one). I've managed to print data for single student, but i can't make it to store data in $studenti array, so that it will print data for all students. here's code that i used(i forgot to mention, i need to use sessions for this):

    <?php
session_start();

$_SESSION['aindex'] = $_POST['index'];
$_SESSION['aime']= $_POST['ime'];
$_SESSION['aprosek'] = $_POST['prosek'];

//if ($index != "" && $ime != "" && $prosek !="")
//{
// = $index;
 //= $ime;
 //=$prosek;

//}

//print ($_SESSION['aindex']);
function inicijalizacija()
{
    $studenti = array ();
    $ind = $_SESSION['aindex'];
    $im = $_SESSION['aime'];
    $pr = $_SESSION['aprosek'];

    $studenti[$ind]["ime"] = $im;
    $studenti[$ind]["prosek"] = $pr;

return $studenti;   
}

function dodaj($studenti)
{
$studenti[$_SESSION['aindex']]["ime"] = $_SESSION['aime'];
$studenti[$_SESSION['aindex']]["prosek"] = $_SESSION['aprosek'];

return $studenti;
}

function prikazi($studenti) //ovde u argumentu treba $studenti
{

print ("<h2> Lista Studenata: </h2>");
foreach ($studenti as $ind => $student)
{
if (empty($ind))
    continue;
$n = $student["ime"];
$p = $student["prosek"];
print ("Index: " . $ind . " " . "Ime: " . $n . " " .  "Prosek: " . $p );


}
print("<hr size ='1'>");

//Forma dodavanja

print (" <form action = 'index.php' method = 'post' >");
print ( " Indeks:&nbsp   <input type = 'text' name = 'index' />");
print(" </br>");
print ( " Ime:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp   <input type = 'text' name = 'ime' >");
print(" </br>");
print ( " Prosek : <input type = 'text' name = 'prosek' />");
print(" </br>");
print (" <input type = 'submit' value = 'Dodaj' name = 'Dodaj' />");
}




$studenti = inicijalizacija();
?>


<html>
    <head> <title> pokusaj </title> </head>
    <body>
    <?php

    prikazi($studenti);
    dodaj($studenti);
    ?>

    </body>



</html>

Upvotes: 1

Views: 622

Answers (1)

user2428118
user2428118

Reputation: 8104

It seems you're misunderstanding the way PHP works. For efficiency and security, all variables are destroyed when the script has ran and the variables used for this user aren't visible for the script when called by other users.

$_SESSION is an exception; data in $_SESSION will be preserved until the session expires, but it will still only be visible to one unique user (identified by a cookie).

If you want to save the data of a script for use when it is called again (using another session), you'll have to write data to a file or use a database.

PS, your script looks like it will introduce XSS and CSRF vulnerabilities; make sure you won't make the same mistakes that many people before you made.

Upvotes: 1

Related Questions