PHP - Declaring Session Arrays...
I was wondering if its possible to add new elements to anarray i have called "$_SESSION['error']" like this:
Code: [Select] <?php $_SESSION["errors"][] = "string"; ?> Because i have a whole bunch of if statements that check my registration form and currently, if an error is found, i add a new element to that array like this: Code: [Select] <?php $_SESSION["errors"]["var"] = "string"; ?> Then i echo the form again with this: Code: [Select] <?php Foreach ($_SESSION["error"] as $object => $value) { echo $value; } ?> which basically just echos error messages...but the thing is is that i have a LOT of fields and its getting tiring having to give each error a unique name. So is it possible to add new elements to this array like that? Do the array elements automatically get id's? Similar TutorialsI'm trying to pass variables among many pages, in an interactive choose your own adventure game. I created the entire thing using sessions, and everything works as intended, but during high traffic there is much slowdown. I had memcached installed and that helped the slowdown considerably but it's still slowing down the site when there is a lot of traffic. I've been told using session arrays, instead of all these individual sessions, will help alleviate the server load. So I don't know if that's true or not, but I'd like to get the correct syntax for using these session arrays. First question - is it absolutely necessary to call the array() ? $_SESSION['game']=array(); Or if this is two separate sessions - $_SESSION['stairs'] = "true"; $_SESSION['dance'] = "true"; Is this two parts of one session array? $_SESSION['game']["stairs"]="true"; $_SESSION['game']["dance"]="true"; And in that case, do I need to call the array() ? I'm seeing different examples of session arrays online so I'm trying to get this clarified. Thanks. PS The purpose of the sessions is that I need them to be checked many pages later in the game in many cases. And I can't just add all the parts of the array at once, which is why I create an empty array first, to have items added as necessary as a user progresses through the game. I have a form that contains a list (Interests) where you can make multiple selections. This information, like the rest of the form, is saved in a session. When the form is processed, the information is sent and the user goes to a thank you page. Everything displays correctly except the list - it just displays like: Interest1, Interest2, Interest3. How can I get the Interests list to display in an unordered list? Thanks! Hi I am having trouble using the min() function to find the lowest value within my session arrays. On my site i have the following car values saved into my $car array: Code: [Select] $car = array( "itemNumber" => $itemNumber, "Model" => $Model, "EngineSize" => $EngineSize, "Colour" => $Colour, "Value" => $Value, ); I then store each $item array into a $_SESSION['all'] as below: Code: [Select] if (isset($_SESSION['all'])) { $_SESSION['all'][$number] = $car; } else { $_SESSION['all'] = array($number => $car); } Now i need to find the lowest Value of all the cars that the user may add. I have been using the min() function to try and do this with the following code but it gives me the error: Wrong parameter count for min()..... Code: [Select] $cheapest = min($car['Value']); Am i on the right tracks or is this not possible? If anyone could shed some light on how i can get this to work, would be very much appreciated! Hi, Im in trouble with a script. Mainly the problem is that the declared value is not reachable. lets sai i have main.php file where i declare that $user_id = '22'; and then i include a file that needs to get that value to work include('somescript.php'); now when i go over to the somescript.php i write at the top that print $user_id; and i get nothing. What am i doing wrong? I'm looking for a more efficient way of declaring variables within a class. What I normally use is a class which is actually a database object. Every time I make a new table in my database I make a new class and new attributes to match the fields in the db table. Looks something like this: Code: [Select] protected static $table_name="myTable"; protected static $db_fields=array('id', 'name', 'address', 'tel_number', 'fax_number'); public $name; public $address; public $tel_number; public $fax_number; //etc. etc. At the moment I am manually adding the attribute, everytime I add a field to the db table. I'm guessing there should be a way to loop through the $db_fields array and add an attribute in the loop? Can anyone help me with the syntax for this. Is there also a way that I don't have to list the fields everytime in $db_fields....can $db_fields not just look at the relevant db table and pull out the field names in some kind of clever method? I'm having troubling with trying to create a function to spit out a single array with the following array. I can write it in a away that looks through the arrays manually. the results i am trying to generate is that each item in generated array. Array to convert array( "account" => array( "login", "register", "logout", "edit", ), "p" => array( "report", ), "array1.0" => array( "array2.0" => array( "array3.0", "array3.1 ), "array2.1", ), generating the array will look like this
Array ( [0] => account [1] => account/login [2] => account/register [3] => account/logout [4] => account/edit [5] => p [6] => p/report [7] => array1.0 [8] => array1.0/array2.0 [9] => array1.0/array2.0/array3.0 [10] => array1.0/array2.0/array3.1 [11] => array1.0/array2.1 ) The idea is that id generates a single array with combined labels and arrays inside, etc. I just can't figure out how to create a script that will create this array even If I add a new value or array.
I have this thing that i am trying to make but i cant get it to work.. can anyone help? Code: [Select] function sql_read( $dbname,$dbusername,$dbpassword ) { $names = array(); $password = array(); $connect = @mysql_connect("mysql11.000webhost.com",$dbusername,$dbpassword) or die("Could Not Connect"); @mysql_select_db ($dbname) or die("Could not find DataBase"); $query = mysql_query("select * from users"); $numrows = mysql_num_rows($query); if ($numrows > 0){ while($row = mysql_fetch_assoc($query)){ $names[] = $row["uname"]; $password[] = $row["password"]; $id = $row["id"]; } $return = array($names,$password,$id); }else{ $return = array(); } return $return[]; } $names = array(); $names = sql_read("XXXXXX","XXXXXX","XXXXXXX")[0]; The error i get is Code: [Select] Parse error: syntax error, unexpected '[' in /home/a5480952/public_html/sql/index.php on line 28 Line 28 is "$names = sql_read("XXXXXX","XXXXXX","XXXXXXX")[0];" Please help... i REALLLLD need help with this.. ask questions if you want to know more about what i am trying to do... thanks! I am having trouble resolving an error. Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/s519970/public_html/header.php:27) in /home/s519970/public_html/admin/login.php on line 2 What I can gather is I can't use "header (Location: 'admin.php')" after i've used session_start(). I have tried to replace the header (Location: 'admin.php') with this: echo "<script>document.location.href='admin.php'</script>"; echo "<script>'Content-type: application/octet-stream'</script>"; I've been trying to read up on solutions but haven't been able to get it sorted. If anyone can offer some advice that would be greatly appreciated as im new to php. Code: [Select] <?php session_start(); if(isset($_SESSION['user'])) echo "<script>document.location.href='admin.php'</script>"; echo "<script>'Content-type: application/octet-stream'</script>"; ?> <div id="loginform"> <form action="dologin.php" method="post"> <table> <tr> <td><span>Username:</span></td> <td><input type="text" name="username" /></td> </tr> <tr> <td><span>Password:</span></td> <td><input type="password" name="password" /></td> </tr> <tr> <td colspan="2" align="right"><input type="submit" name="login" value="Login" /></td> </tr> </table> </form> </div> I have tried using require_once('yourpage.php'); before my <head></head> tags in the header document where I've specified the html information but this doesn't seem to work. I've been advised to use ob_start("ob_gzhandler"); but I am not sure how to implement this. Any advice is greatly appreciated! I am trying to create an index page which contains registration and login field the problem that i get is on successful login a warning is displayed session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\xampp\htdocs\Eventz.com\index.php:116) in C:\xampp\htdocs\Eventz.com\index.php on line 235 This is the login part of my index.php this tag is inside an html table below the login form I also have a registration form and its php code above the login form Code: [Select] <?php if (isset($_REQUEST['pass'])) { $id=$_POST['id']; $pass=$_POST['pass']; $conn =mysql_connect("localhost","root",""); if (!$conn) { die('Could not connect: ' . mysql_error()); } /* checking connection....success! */ $e=mysql_select_db('test', $conn); if(!$e) { die(''.mysql_error()); } else { echo 'database selected successfully'; } if (isset($_REQUEST['id']) || (isset($_REQUEST['pass']))) { if($_REQUEST['id'] == "" || $_REQUEST['pass']=="") { echo "login fields cannot be empty"; } else { $sql=mysql_query("Select email,password from login where email='$id' AND password='$pass'"); $count=mysql_num_rows($sql); if($count==1) /* $count checks if username and password are in same row */ { session_start(); $_SESSION['id']=$id; echo "</br>Login Successful</br>"; } else { echo "</br>invalid</br>"; echo "please try to login again</br>"; } } } } ?> Any help or suggestion would be appreciated in this page http://maximaart.com/newscp/ i have this problem Code: [Select] Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/maximasy/public_html/newscp/index.php:1) in /home/maximasy/public_html/newscp/index.php on line 2 my source code is <?php session_start(); include_once("config.php"); include_once("functions.php"); $errorMessage = ''; if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) { if ($_POST['txtUserId'] === "$user" && $_POST['txtPassword'] === "$pass") { // the user id and password match, $_SESSION['basic_is_logged_in'] = true; require("main.php"); exit;?> I'm making a simple login system with MySQL and PHP (very simple, I'm just starting with PHP). The MySQL portion is done, but I need to ensure only people who are logged in can see certain content. To check if people are logged in, my website checks that they have the $_SESSION['user'] variable set. If it is set, then it lets them continue through the website, if not, it tells them to login. Is that enough security, or can people simply inject a session cookie into their browser to spoof that they are logged in? My idea was to generate a session key cookie when they login (just a random string of letters and numbers) and store that in the database, then on every page, check to make sure their session key is the same thing that's in the database. Is this necessary? It seems expensive. hi everyone. i'm wondering what the best way is to create a session variable and pass it to an iframe. i need to do something along these lines, but it doesn't seem to pass the ID. Any hints on how i should accomplish this? Code: [Select] session_start(); $_SESSION['ID']=$_GET['ID']; // id from previous page $ID=session_id(); <iframe src="iframepage.php?ID=<?php echo $ID; ?>" style="width:680px; height:200px;" noresize="noresize" frameborder="0" border="0" scrolling="Yes" allowtransparency="true" /> </iframe> I have two arrays, both with the same key values. I'd like to combine them. So for instance... Code: [Select] <?php $array1['abcd'] = array( 'value1' => "blah", 'value2' => "blahblah"); $array1['efgh'] = array( 'value1' => "ha", 'value2' => "haha", 'valuex' => "xyz"); $array2['abcd'] = array('value3' => "three", 'value4' => "four"); $array2['efgh'] = array( 'value3' => "hohoho", 'value6' => "six6"); function combine_arrays($array1,$array2) { //*combining* return $single_array; } echo "<pre>"; print_r(combine_arrays($array1,$array2)); echo "</pre>"; /* would produce ['abcd'] = ( 'value1' => "blah", 'value2' => "blahblah", 'value3' => "three", 'value4' => "four" ) ['efgh'] = ( 'value1' => "ha", 'value2' => "haha", 'valuex' => "xyz", 'value3' => "hohoho", 'value6' => "six6" ) */ ?> What's the easiest way to do this? Just curious how other people feel about this. I am working on an application where a lot of info is pulled from MySQL and needed on multiple pages.
Would it make more sense to...
1. Pull all data ONCE and store it in SESSION variables to use on other pages
2. Pull the data from the database on each new page that needs it
I assume the preferred method is #1, but maybe there is some downside to using SESSION variables "too much"?
Side question that's kind of related: As far as URLs, is it preferable to have data stored in them (i.e. domain.com/somepage.php?somedata=something&otherdata=thisdata) or use SESSION variables to store that data so the URLs can stay general/clean (i.e. domain.com/somepage.php)?
Both are probably loaded questions but any possible insight would be appreciated.
Thanks!
Greg
Edited by galvin, 04 November 2014 - 10:30 AM. Evening! I've been iffing and ahhing over this and well im not too sure, hence the post. Code: [Select] // Redirects if there is no session id selected and echos the error on the previous page if(!isset($_GET['get']) || ($_GET['getget'])){ header("Location: #.php?error"); } So it should simply check if get is set if it isnt then see if getget is set? If not redirect and show the error. Now ive tried it and even when get/getget is set it still redirects, probably something silly. Care to share anyone? Harry. I've spent many hours trying to solve this with no success. So, here's my challenge. Sample Data from DB: Month Year Measure 5 2010 164 6 2010 31 7 2010 20 8 2010 10 9 2010 10 10 2010 10 12 2010 10 1 2011 10 I need to display this data in a chart, but notice that I don't have data for month 11 and the chart must show all months with data and the month that I don't have data for (11 in this case) will show an interrupted line. I need to put this into an array to display month/year as label and measure as chart value. So, the above data needs to become: Month Year Measure 5 2010 164 6 2010 31 7 2010 20 8 2010 10 9 2010 10 10 2010 10 11 2010 -- 12 2010 10 1 2011 10 The issue here isn't the chart, but how to add the missing month (11) to the array and keep the measures corresponding with their months. Thank you. I am trying to learn about sorting and modifying arrays and I am practicing on a book assignment but need some help to grasp what I need to do. If you go here, you will see how it is supposed to work. http://198.86.244.3/mabarckhoff/WEB182/ch11_ex1/ I need to write a case to sort the task when you click the sort button and modify when you click that button. The delete button works and the add task works. I understand the sort array and have added that case, but don't know how to get it to work with the submit. Also there is a promote button so would need 'promote' what ever you have chosen in the dropdown menu to the top. Here is my code. tasklist.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Task List Manager</title> <link rel="stylesheet" type="text/css" href="main.css"/> </head> <body> <div id="page"> <div id="header"> <h1>Task List Manager</h1> </div> <div id="main"> <!-- part 1: the errors --> <?php if (count($errors) > 0) : ?> <h2>Errors:</h2> <ul> <?php foreach($errors as $error) : ?> <li><?php echo $error; ?></li> <?php endforeach; ?> </ul> <?php endif; ?> <!-- part 2: the tasks --> <h2>Tasks:</h2> <?php if (count($task_list) == 0) : ?> <p>There are no tasks in the task list.</p> <?php else: ?> <ul> <?php foreach( $task_list as $id => $task ) : ?> <li><?php echo $id + 1 . '. ' . $task; ?></li> <?php endforeach; ?> </ul> <?php endif; ?> <br /> <!-- part 3: the add form --> <h2>Add Task:</h2> <form action="." method="post" > <?php foreach( $task_list as $task ) : ?> <input type="hidden" name="tasklist[]" value="<?php echo $task; ?>"/> <?php endforeach; ?> <label>Task:</label> <input type="text" name="newtask" id="newtask"/> <br /> <label> </label> <input type="submit" name="action" value="Add Task"/> </form> <br /> <!-- part 4: the modify/promote/delete form --> <?php if (count($task_list) > 0 && empty($task_to_modify)) : ?> <h2>Select Task:</h2> <form action="." method="post" > <?php foreach( $task_list as $task ) : ?> <input type="hidden" name="tasklist[]" value="<?php echo $task; ?>"/> <?php endforeach; ?> <label>Task:</label> <select name="taskid"> <?php foreach( $task_list as $id => $task ) : ?> <option value="<?php echo $id; ?>"> <?php echo $task; ?> </option> <?php endforeach; ?> </select> <br /> <label> </label> <input type="submit" name="action" value="Modify Task"/> <input type="submit" name="action" value="Promote Task"/> <input type="submit" name="action" value="Delete Task"/> <br /> <label> </label> <input type="submit" name="action" value="Sort Tasks"/> </form> <?php endif; ?> <!-- part 5: the modify save/cancel form --> <?php if (!empty($task_to_modify)) : ?> <h2>Task to Modify:</h2> <form action="." method="post" > <?php foreach( $task_list as $task ) : ?> <input type="hidden" name="tasklist[]" value="<?php echo $task; ?>"/> <?php endforeach; ?> <label>Task:</label> <input type="hidden" name="modifiedtaskid" value="<?php echo $task_index; ?>" /> <input type="text" name="modifiedtask" value="<?php echo $task_to_modify; ?>" /><br /> <label> </label> <input type="submit" name="action" value="Save Changes"/> <input type="submit" name="action" value="Cancel Changes"/> </form> <?php print_r($_POST); ?> <?php endif; ?> </div><!-- end main --> </div><!-- end page --> </body> </html> index.php <?php if (isset($_POST['tasklist'])) { $task_list = $_POST['tasklist']; } else { $task_list = array(); // some hard-coded starting values to make testing easier $task_list[] = 'Write chapter'; $task_list[] = 'Edit chapter'; $task_list[] = 'Proofread chapter'; } $errors = array(); switch( $_POST['action'] ) { case 'Add Task': $new_task = $_POST['newtask']; if (empty($new_task)) { $errors[] = 'The new task cannot be empty.'; } else { $task_list[] = $new_task; } break; case 'Delete Task': $task_index = $_POST['taskid']; unset($task_list[$task_index]); $task_list = array_values($task_list); break; case 'Sort Task': sort($task_list); print_r($task_list); break; /* case 'Save Changes': case 'Cancel Changes': case 'Promote Task': */ } include('task_list.php'); ?> I have ticket's for my lottery system. Somone chooses 3 random numbers out of 36, it will show 1|20|30 but now I want to beable to have my Members BUY multiple Tickets! So then I added a comma between the 3 arrays So the code will look like this when they select the balls they want Code: [Select] 1|20|30,20|10|5 /etc /etc But now I have 1 problem. How do I go about validating the arrays for each COMMA inside the | ARRAY? Cause let's saY I don't want anyone to Submit a ball number higher then "36" how would I go about making it so it checks through each array and if it's higher then 32 I can give them a Error? Also, I each Ticket costs (5 Forum Gold) so the above code would be a total of 10 Forum Gold, because they're "2" Tickets being bought, how would I go about making a $counter++ in the arrays to count only the "," so I can tell how much Gold the member needs to have before he purchases Thanks I have created two classes. One is called 'move' and the other 'unit'. To make my example easier to follow, I shall use the much loved pokemon series to explain my dilemma. Here are the class declarations. new class unit { var $name, $moves; public function newUnit($name, $moves) { $this->name = $name; $this->moves = $moves; } } new class move { var $name, $attack; public function newMove($name, $attack) { $this->name = $name; $this->moves = $moves; } } Now I shall instantiate these classes (if that makes sense xD) - I just started OOP yesterday, do mind my ignorance. $unit = array(); $move = array(); $unit[0] = new unit; $unit[0]->newUnit("picachu",array("thunderbolt","quick-attack")); Now, let's say I want to populate the $move array with the moves in the unit object (thunderbolt and quick-attack). I can retrieve their attack values from a database: $thunderboltAttack = 200; $quick-attackAttack = 40; I now want to create a function that will create instances of the 'move' class to produce: $move[0] = new move; $move[0]->newMove("thunderbolt",200); $move[1] = new move; $move[1]->newMove("quick-attack",40); Here is my dire attempt to do so: function createUnits($moves){ //$moves is the array holding the unit's moves for($i; $i < count($moves); $i++) { $arr[] =new move; $arr[count($units) - 1]->name = $moves[0]; $arr[count($units) - 1]->attack = $someAttackData; } return $arr; } $moves[] = createUnits; I'm ending up with a multi-dimensional array when I want a linear one like this: $move[0] = new move; $move[0]->newMove("thunderbolt",200); $move[1] = new move; $move[1]->newMove("quick-attack",40); What do I need to do. Do I have to resort to making $move global from within the function and do things that way? Hi, I'm having some trouble trying to generate my random string for a name. This is my code: Code: [Select] <?PHP function rand_string( $length ) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $size = strlen( $chars ); for( $i = 0; $i < $length; $i++ ) { $str .= $chars[ rand( 0, $size - 1 ) ]; } return $str; } $salt_string = rand_string( 5 ); $test = "1234"; echo "salt_string = $salt_string"; echo "<br>"; echo "test = 1234"; echo "<br>"; $array = array('$test', '$salt_string'); echo "<br>"; echo "array = $array"; echo "<br>"; $imploded = implode($array); echo "<br>"; echo "imploded = $imploded"; ?> And it returns: salt_string = 8pbAe test = 1234 array = Array imploded = $test$salt_string I don't understand why my imploded variable is not 12348pbAe |