PHP condition fails while using Session - php

I made a card game with PHP but there I'm facing some issue.
if ($_SESSION["bet"] != NULL)
{
echo "Your starting bankroll is: " . $_SESSION["bankroll"] . "<br>";
echo "Your bet is: " . $_SESSION["bet"] . "<br>";
}
I'm getting an input from the user. The problem is, when the game loads at first, and the user enters an input and clicks submit, the game won't work. The condition ($_SESSION["bet"] != NULL) is giving true and bankroll is not defined.
Is there a way I can set this up properly? Is there some PHP method that can initialize the variable once then only works it on session start, then the rest of the code can take care of how that variable gets updated? The bankroll variable gets initialized if the user clicks submit without anything in it right now, so the game still works but it starts improperly.
if ($_SESSION["bet"] == NULL)
{
$_SESSION["bankroll"] = 1000;
}
The bankroll variable gets initialized to 1000 every time user submits a NULL input. I want to change this.
More code... Updating...
session_start();
$_SESSION["bet"] = $_POST["bet"];
echo "<br>";
//print_r($_SESSION);
if ($_SESSION["bet"] != NULL)
{
echo "Your starting bankroll is: " . $_SESSION["bankroll"] . "<br>";
echo "Your bet is: " . $_SESSION["bet"] . "<br>";
}
if ($_SESSION["bet"] == NULL)
{
$_SESSION["bankroll"] = 1000;
}
else if ($_SESSION["bet"] > 1000 || $_SESSION["bet"] < 0)
{
echo " Please enter between 0 and 1000.";
}
else if ($_SESSION["bet"] > $_SESSION["bankroll"])
{
echo "You can't enter more than what you have.";
}
else
{
$deck = array();
for($x = 0; $x < 54; $x++) {
$deck[$x] = $x;
}
shuffle($deck);
//Then more stuff. This one for example...
if(($houseSuits[0] == -100) || ($houseSuits[1] == -100) || ($houseSuits[2] == -100) || ($houseSuits[3] == -100))
{
echo "<br>";
echo '<center> PLAYER WINS! (HOUSE HAS JOKER) </center>';
echo "<br>";
$_SESSION["bankroll"] = $_SESSION["bankroll"] + $_SESSION["bet"]; //THESE NEED TO BE ADDRESSED.
}
I JUST WANT TO FIND A WAY TO INITIALIZE BANKROLL TO 1000 AT START. THE WAY I'M DOING IT IS BY SUBMITTING A NULL VALUE THEN ASSUMING USER NEVER SUBMITS NULL VALUE AGAIN.
I WOULD LIKE BANKROLL TO BE INITIALIZED TO 1000, THEN FOR THE GAME TO TAKE CARE OF HOW BANKROLL GETS UPDATED.
I FOUND A WAY TO DO IT BUT IT'S NOT A PROPER WAY SO THAT'S WHY I'M ASKING FOR HELP.
THANK YOU.

Ok try this.
So if the bankroll is not set, then set it, once it's set it wont get set again because it's set.
Then any conditions after are fine.
session_start();
// Initialise bankroll if not already
if (!isset($_SESSION['bankroll'])) {
$_SESSION['bankroll'] = 1000;
echo "Your starting bankroll is: " . $_SESSION["bankroll"] . "<br>";
}
$_SESSION['bet'] = $_POST['bet'];
if ($_SESSION['bet'] != NULL) {
echo "Your bet is: " . $_SESSION['bet'] . "<br>";
}
if ($_SESSION['bet'] > 1000 || $_SESSION['bet'] < 0) {
echo " Please enter between 0 and 1000.";
} elseif ($_SESSION['bet'] > $_SESSION['bankroll']) {
echo "You can't enter more than what you have.";
} else {
// Your card game stuff
}
Notes: you may have issues with using session as it'll store their bet wherever they are, so issuing a bet sets the session, then navigate elsewhere and come back and their bet will still be as before. Maybe this doesn't matter.
You also might not want to check if the bet is null, more perhaps empty or whatever. Test either way to be sure.

Related

Concatenation & conditions in php

I'm learning PHP and i'm trying to show an " €" when and only when $autocollant_total_ht_custom isset.
This is what i wrote :
$euro = " €";
if (isset($autocollant_total_ht_custom)) {
$autocollant_total_ht_custom = $autocollant_total_ht_custom . $euro;
} else echo " ";
However my " €" is always showing even when $autocollant_total_ht_custom is not set.
I spent 75 minutes on it, trying and failing again and again despite researching.
I also tried with !is_null, !is_empty with the same result.
I'm fairly certain that my logic isn't wrong but the way to do it is.
Anyone to the rescue?
Have a nice Saturday everyone !
Mike.
Edit 1:
A little visual aid image
My goal was to only show the content of a cell if there was indeed something in it. By default i could see 0 in the empty cells.
if (!$autocollant_total_ht_lot10) {
$autocollant_total_ht_lot10 = " ";
} else echo "error ";
if (!$autocollant_total_ht_lot20) {
$autocollant_total_ht_lot20 = " ";
} else echo " ";
if (!$autocollant_total_ht_lot50) {
$autocollant_total_ht_lot50 = " ";
} else echo " ";
if (!$autocollant_total_ht_custom) {
$autocollant_total_ht_custom = " ";
} else echo " ";
I know my code must look primitive but it works and i don't see it making a conflict with what we are trying to achieve in the initial question.
Then, as asked, this is what i'm writing in the table row and table data :
<tr>
<td class=table_align_left>A partir de 100</td>
<td><?php echo $autocollant_prix ?></td>
<td><?php echo $autocollant_custom?></td>
<td><?php echo $autocollant_total_ht_custom?> </td>
</tr>
So in short, i'm trying to not show anything if there's no value to be shown (which is currently working) and then adding a " €" after the variable is there's something to be shown.
Edit 2 :
My primitive code : my_code
Edit 3 :
The $autocollant_total_ht_custom is already conditioned to be shown earlier in this statement :
} elseif($autocollant_quantité >= 90 && $autocollant_quantité <= 99){
$autocollant_quantité_lot50 = 2;
} elseif($autocollant_quantité >= 100 && $autocollant_quantité <= 1000){
$autocollant_custom = $autocollant_quantité;
} else echo "entrée invalide";
$autocollant_total_ht_custom = $autocollant_prix * $autocollant_custom;
$autocollant_total_ht_lot10 = $autocollant_prix_lot10 * $autocollant_quantité_lot10;
$autocollant_total_ht_lot20 = $autocollant_prix_lot20 * $autocollant_quantité_lot20;
$autocollant_total_ht_lot50 = $autocollant_prix_lot50 * $autocollant_quantité_lot50;
$pointeuse_total_ht = $pointeuse_prix * $pointeuse_quantité;
$pointeuse_autocollant_offert = $pointeuse_quantité * 10;
$pointeuse_autocollant_offert_total_ht = $pointeuse_autocollant_offert * $autocollant_prix;
$pointeuse_autocollant_offert_total_ht = $pointeuse_autocollant_offert * $autocollant_prix;
I posted my code if that can help.
Mike.
//$autocollant_total_ht_custom = null;
$autocollant_total_ht_custom = "something that isnt null";
//if you switch the variable assignment above you will see it behaves as expected.
$euro = "€";
if (isset($autocollant_total_ht_custom))
{
echo $autocollant_total_ht_custom = $autocollant_total_ht_custom . " " .$euro;
}
else
{
//$autocollant_total_ht_custom wouldn't be set at all if we reach this point, this is why im un-sure what your requirements are. Nothing would be echoed.
echo $autocollant_total_ht_custom;
}
Something like this maybe? It's hard to understand your exact requirements.
IsSet checks if a variable is set to something if its not null then it passes the test, and if you're manipulating strings at this variable then it will never be null, meaning the euro sign will always show up.
If the variable IS null then you fail the conditional test, hit else and echo nothing a null string.
If you can update your answer with what you would expect "$autocollant_total_ht_custom" to be set to, I can help better.
EDIT:
Seems to me you can simplify what you what, basically we are only concerned with echoing a string at all if there is something set, otherwise there's no point doing anything, so your checks could be as simple as
$autocollant_total_ht_lot10 = null;
$autocollant_total_ht_lot11 = "";
$autocollant_total_ht_custom = "1,000";
$euro = "€";
if (isset($autocollant_total_ht_custom))
{
echo 'ht custom';
echo TDFromString($autocollant_total_ht_custom, $euro);
}
//notice this doesnt output anything because it isnt set
if (isset($autocollant_total_ht_lot10, $euro))
{
echo 'lot 10';
echo TDFromString($autocollant_total_ht_lot10, $euro);
}
//notice this does because the string, while empty is something that isnt null
if (isset($autocollant_total_ht_lot11))
{
echo 'lot 11';
echo TDFromString($autocollant_total_ht_lot11, $euro);
}
//lets set it to null and see what happens
$autocollant_total_ht_lot11 = null;
if (isset($autocollant_total_ht_lot11))
{
echo 'lot 11 AGAIN';
echo TDFromString($autocollant_total_ht_lot11, $euro);
}
//it doesnt get printed!
//create a function that takes the string in question,
//and for the sake of your use case also the currency to output,
//that way you could change 'euro' to 'currency'
//and have the sign change based on what the value of the $currency
//string is, eg $currency = "£"
function TDFromString($string, $currency)
{
return '<td>' . $string . ' ' .$currency . '</td>';
}
Live example : https://3v4l.org/r5pKt
A more explicit example : https://3v4l.org/JtnoF
I added an extra echo to indicate (and newlines) which variable is being printed out you dont need it of course!
I'll just note the function name is a good example of a bad function name, as it not only returns a td around the string but also inserts the currency, you may want to name it a little better :)
EDIT EDIT:
A final edit outside the scope of your question, you should look into keeping your data in arrays and working on them instead.
Using the previous example we can reduce the code to just this !
$autocollant_total_ht_lot10 = null;
$autocollant_total_ht_lot11 = "";
$autocollant_total_ht_lot12 = "2,0000000";
$autocollant_total_ht_custom = "1,000";
$euro = "€";
//create an array, and stick all our strings in it, from now, if we need to do something to one of the strings(or all!), we do it through the array
$arrayofLots = array($autocollant_total_ht_lot10, $autocollant_total_ht_lot11, $autocollant_total_ht_lot12, $autocollant_total_ht_custom);
//go over each array 'entry' so the first time is '$autocollant_total_ht_lot10', then '$autocollant_total_ht_lot11' etc
foreach ($arrayofLots as $lot)
{
//and we've been over this bit :)
//$lot is a variable we set so we have something to refer to for the individual array entry we are on, we could just as easily name it anything else
if (isset($lot))
{
echo TDFromString($lot, $euro);
}
}
function TDFromString($string, $currency)
{
return '<td>' . $string . ' ' .$currency . '</td>';
}
Good day. It looks like you are missing the end brace
if (isset($autocollant_total_ht_custom)) {
$autocollant_total_ht_custom = $autocollant_total_ht_custom . $euro;
} else {
echo " ";
}

Using random variables inside Arrays

First of all, sorry if this is worded poorly, as I'm a beginner at code.
I'm currently working on an online computer science course, however I'm quite confused on how to do one small part. We need to use arrays for this activity, where the user has multiple selections and each different selection has a different/unique text output. Everything works fine, except I need an option to choose a random selection, however I'm a bit confused on how to make it. You can see from my code the options 1-8. I want it to randomly select one of the selections.
Here's my code:
<?php
$train[0] = "Canada";
$train[1] = "Sahara Desert";
$train[2] = "Russia";
$train[3] = "Chernobyl";
$train[4] = "United States";
$train[5] = "North Korea";
$train[6] = "Germany";
$train[7] = "Hawaii";
?>
<!DOCTYPE html>
<html>
<head>
Took out everything here, it's not important.
</head>
<body>
<center>
<h1>Vacation Time!</h1>
<h4>You and your family just won the lottery! You all want to go on vacation, but nobody can agree where to go. Inside each train cart has a card with a location written on it. Whatever you find is where you're going! </h4>
<form name="form1" action="activity-2-7-arrays-a.php" method="post">
<label>Which cart on the train do you want to choose?</label>
<br>
<select name="cart" required>
<option value="1">First Cart</option>
<option value="2">Second Cart</option>
<option value="3">Third Cart</option>
<option value="4">Fourth Cart</option>
<option value="5">Fifth Cart</option>
<option value="6">Sixth Cart</option>
<option value="7">Seventh Cart</option>
<option value="8">Eight Cart</option>
<option value="show">Show all options</option>
<option value="any">Choose Randomly</option>
<br>
</select><br/>
<input type="submit" name="subButton" class="subButton" value="Go!"/><br/>
</form>
<h1><u>Final Results</u></h1>
<?php
if($_POST['subButton']) {
$cart = $_POST['cart'];
$roll = rand(1,9);
if($cart == show) {
for($x = 1; $x <= 9; $x++) {
echo "<p> You could have ender up in... </p>";
echo "<h2> " . $train[$x] . "</h2>";
}
return;
}
echo "<h2>"."Well, it looks like you're going to " . $train[$cart] . "! Have fun! </h2>";
}
return;
if ($cart == $roll) {
}
echo "<h2>"."Can't handle the pressure? You were selected to go to " . $train[$roll] . "! Have fun! </h2>";
?>
I'm sure it's a bit messy, also. Hopefully you understand what I mean. If you're able to explain the answer to me that would be extremely helpful. Thank you :)
You are randomly generating a value regardless of the user choice and comparing it with user's selection and other weird things.
<?php
if($_POST['subButton']) {
$cart = $_POST['cart'];
$roll = rand(1,9);
You are generating a random value before even checking if user selected 'Choose randomly' and why generate a random between 1 and 9? Your $train array starts with index 0 and ends with index 7.
if($cart == show) {
String needs to be quoted.
for($x = 1; $x <= 9; $x++) {
Again looping $x from 1 to 9 makes no sense because of your array indexes.
echo "<p> You could have ender up in... </p>";
echo "<h2> " . $train[$x] . "</h2>";
Will fail when $x reaches 8 since last index in $train is 7.
}
return;
}
echo "<h2>"."Well, it looks like you're going to " . $train[$cart] . "! Have fun! </h2>";
}
return;
So if user didn't select 'Show all options' you show him his chosen location. If user chose 'Select Randomly' this will fail since $cart would have value 'any' and $train['any'] does not exist.
Here is code with correct logic.
<?php
if($_POST['subButton']) {
$cart = $_POST['cart'];
if ($cart == 'any') {// Check if user selected 'Choose Randomly'
$roll = rand(0, 7);
echo "<h2>"."Can't handle the pressure? You were selected to go to " . $train[$roll] . "! Have fun! </h2>";
}
else {
if ($cart == 'show') { // If user selected 'Show all options'
echo "<p> You could have ender up in... </p>";
for($x = 0; $x <= 7; $x++) {
echo "<h2> " . $train[$x] . "</h2>";
}
}
else { // User selected cart so show him chosen location
echo "<h2>"."Well, it looks like you're going to " . $train[$cart] . "! Have fun! </h2>";
}
}
}
?>
Here is some problems in the code
from where and why we return?
no closing html-tags
I would change the last part of php-code like that:
<?php
if ($_POST['subButton']) {
$cart = $_POST['cart'];
$value = intval($cart);
$roll = mt_rand(1, 8); // mt_rand() has more entropy than rand()
if ($cart == 'show') {
// show target locations (according the OP-source)
for($x = 1; $x <= 8; $x++) {
echo "<p> You could have ender up in... </p>";
echo "<h2> " . $train[$x-1] . "</h2>";
}
} else if ($value > 0 && $value <= 8) {
echo "<h2>"."Well, it looks like you're going to " . $train[$value-1] . "! Have fun! </h2>";
// idk why it needed, but move it here
if ($value == $roll) {
}
} else if ($cart == 'any') {
echo "<h2>"."Can't handle the pressure? You were selected to go to " . $train[$roll-1] . "! Have fun! </h2>";
} else {
// $_POST['cart'] has something wrong
}
}
?>
<!-- lines below was added to close html-tags -->
</body>
</html>
What you're looking for is array_rand():
$random = array_rand($train);
Instead of rand() use mt_rand() because the PHP DOCUMENTATION literally says
mt_rand — Generate a better random value
Regarding your php code, you have a lot of errors. This is how your bottom php code should look:
<?php
if($_POST['subButton'])
{
$cart = $_POST['cart'];
$roll = mt_rand(0,7);
//0-7 because those are the values you inserted into
//the $train[] array
if($cart == 'show') {
//another correction here, it has to be 0-7
for($x = 0; $x <= 7; $x++) {
echo "<p> You could have ender up in... </p>";
echo "<h2> " . $train[$x] . "</h2>";
}
}
else if ($cart!='any')
{
"<h2>Well, it looks like you're going to " . $train[$cart] . "! Have fun! </h2>";
}
else //took out return and placed an else
{
echo "<h2>Well, it looks like you're going
to " . $train[$cart] . "! Have fun! </h2>";
}
?>

Storing and retrieving $_SESSION variables

I've got a problem. I'm sure I'm being really stupid but I can't seem to be able to rertive a $_SESSION variable. I run throught the code with a variable called $setup which I post each time as reset. Each time I run through the code I increment $setup so it starts off with no value then has the value 1 and then then value 2. When it's one, I set a SESSION to a posted value. The next time when it's two, the SESSION doesn't seem to have a value.
This is the code when the page is loaded:
<?php
session_start();
$setup=$_POST['reset'];
if ($setup==NULL)
{
$setup=0;
}
elseif ($setup==1)
{
$_SESSION['value1']=$_POST['value1'];
$value1=$_SESSION['value1'];
}
elseif ($setup==2)
{
$value1=$_SESSION['value1'];
$_SESSION['value2']=$_POST['value2'];
$value2=$_SESSION['value2'];
}
?>
When setup is one I can print out value1 however when setup is two is use this code
echo $value2 . " " . $value1 . ".";
All I get is value2 followed by a dot. Am I doing something wrong here?
In this part of your code :
elseif ($setup==2)
{
$value1=$_SESSION['value1'];//HERE
$_SESSION['value2']=$_POST['value2'];
$value2=$_SESSION['value2'];
}
$_SESSION['value1'] is empty so $value1 will be empty too , instead of this i suggest this code:
elseif ($setup==2)
{
if(isset($_SESSION['value1']) $value1=$_SESSION['value1'];
else $value1='Some value for test';
$value2=$_SESSION['value2'];
}
ALSO:
echo $value2 . " " . $value1 ".";
Should be :
echo $value2 . " " . $value1 . ".";//if you want dot in the end
or :
echo $value2 . " " . $value1 ;//without dot int end of line
<?php
session_start();
if (!isset($_POST['reset'])) {
// do nothing or something more useful
}
else {
if ($_POST['reset'] == 1) {
$value1 = $_SESSION['value1'] = $_POST['value1'];
}
elseif ($_POST['reset'] == 2) {
$value1 = $_POST['value1']; // $_POST !!! Not $_SESSION['value1'], which is not set here!
$value2 = $_SESSION['value2'] = $_POST['value2'];
}
}
?>
$value1=$_SESSION['value1']; // you can't do this here ( == 2), because you did not set $_SESSION['value1'] to anything before
It depends on what you want to echo.
Example:
$value1 = "hello";
$value2 = "Richard";
echo $value1." ".$value2;
// will output "hello Richard" (Without the quotes)
//using your code (and syntax corrected)
echo $value1." ".$value2.".";
// will output "hello Richard." (Without the quotes)
If you want the dot to be echoed, you need to surround it with quotes "", and to break in and out of PHP vars/text etc in an echo as above.
You forgot a concatenating dot before "." string
Should be:
echo $value2 . " " . $value1 . ".";
I've fixed it. I has a reset button at the bottom to destroy the session and it had PHP in it. Maybe this question will help anyone else who make this mistake. I can happen.

Why does this undefined error occur when storing the first number to a $_SESSION[] variable?

I'm making a mini shopping cart for my project. Im storing the number of items chosen by the user, I don't understand that when i add one to my session variable I always get this error on the first go
Undefined index: cart_1 in D:\wamp\www\MiniCart\cart.php on line 100
And when I add again or refresh the same page it works fine. Why could this error be coming up? I removed the +=1 from the statement and it worked fine, apparently there is no syntax error too.
Cart.php
<!DOCTYPE>
<html>
<head></head>
<body>
<?php
session_start();
//The page where to jump to after adding/editing cart.
$page = 'mini_cart_index.php';
$link = mysqli_connect("localhost","root","","cart");
if(mysqli_connect_errno())
{
echo "Error:".mysqli_connect_error();
echo "<br/>";
} else {
echo "Connected to SQL<br/>";
}
//==================================================
if(isset($_GET['add']))
{
$obt=$_GET['add'];
$quantity_limit = 'SELECT id,quantity FROM products WHERE id='.mysqli_real_escape_string($link,(int)$_GET['add']);
$quantity = mysqli_query($link,$quantity_limit);
while($quantity_row=mysqli_fetch_assoc($quantity))
{
if($quantity_row['quantity']!=$_SESSION['cart_'.$_GET['add']])
{
$_SESSION['cart_'.$_GET['add']]+='1';
}
}
/*
echo 'id='.$obt.' '.'next<br/>';
echo 'Now storing info into session variable and adding one<br/>';
echo $_SESSION['cart_'.$_GET['add']];
echo '<br/>';
echo 'info stored<br/>';
*/
}
//***************************************************
function products()
{
GLOBAL $link;
$get ="SELECT id,name,description,price FROM products
WHERE quantity > 0 ORDER by id ASC";
if($result=mysqli_query($link,$get))
{
echo "Data Selected to be displayed<br/>";
} else {
echo "Error:".mysqli_error($link);
}
if(mysqli_num_rows($result)==0)
{
echo "There are no products to display!<br/>";
} else {
while($get_row=mysqli_fetch_assoc($result))
{
echo '<hr/><br/>';
echo 'displaying data from database<br/>';
echo '==================================';
echo '<p>'.$get_row['name'].'<br/>'.
$get_row['description'].'<br/>'.
number_format($get_row['price'],2).
' Add'.'</p>';
echo '<hr/><br/>';
}
}
}
echo 'outside'.$_SESSION['cart_1'];
?>
</body>
</html>
Mini_cart_index.php
<?php require 'cart.php';?>
<!DOCTYPE>
<html>
<head>
</head>
<body>
<?php products() ?>
</body>
</html>
That code is filled with SQL injection vulnerabilities, you should use PDO and prepare your statements.
PHP is warning you because it has to read the current value and add to it, but the first time you try to access it doesn't exist.
You could suppress the warning with:
#$_SESSION['cart_'.$_GET['add']]+='1';
A better way to do it though would be checking if it exists first
$name = 'cart_'.$_GET['add'];
if(isset($_SESSION[$name]) {
$_SESSION[$name] = 1;
} else {
$_SESSION[$name] += 1;
}
The problem is caused by the fact that...
$var['abc'] += 1
...is the same as
$var['abc'] = $var['abc'] + 1
So if you've got a clean session and $var['abc'] doesn't exist, you're going to get a warning because you're trying to read a non-existant value in order to add 1 to it.
While it's true that 0 + 1 = 1
...what's actually happening here is undefined + 1 = 1 with a warning.
As other answers have mentioned - to fix the issue, you can explicitly check that the array index exists before trying to increment it.
I'd do that with the ternary operator like this:
$key = 'card_' . $_GET['add'];
$_SESSION[$key] = (isset($_SESSION[$key]) ? $_SESSION[$key] : 0) + 1;
This is effectively saying
$val = ($val if it exists, otherwise 0) + 1;
Change your if statement to check if it's empty too:
if (!isset($_SESSION['cart_'.$_GET['add']])) {
$_SESSION['cart_'.$_GET['add']] = 1;
} elseif ($quantity_row['quantity'] != $_SESSION['cart_'.$_GET['add']]) {
$_SESSION['cart_'.$_GET['add']] += 1;
}

If statement and Objects

this is by Far the weirdest thing i have ever seen and i am completely confused. please someone help me with this.
$variable=array();
$count=0;
// now im am going to loop through a resource that i made
while(!feof($job))
{
$data=fgets($job);
// i am search for different things below. search for name, date, employer
// i am using regex to search btw
// presume object in class works fine, and they do.
if(search for eg name in $data, storing in $variable[$count].first($match))
// the problem is at this point i will have access to
// $variable[$count].getFirst(returns value set by first) which was set above;
if(search for eg Employer in $data, storing in variable[$count].next($match))
// i will have access here as well
// $variable[$count].getFirst(returns value set by first) which was set above
if(search for 3rd search in $data, storing in variable[$count].name($match))
// down here after the second if i am not able to see any of my variables set more than 2 if statements ago????
// $variable[$count].getFirst(does not returns the value set by first()) which was set above
if(search for 4th search in $data, storing in variable[$count].foo($match))
// check if everything is set then count++;
}
Now each one of these methods are completely dependent from the next but after 2 if statements. I am just not able to access $variable[count]->getfirst()
the answer is null;
edited
this is the actual code
require "functions/decodeEncodedUrl.php";
require "objects/jobObject.php";
$url=decodeEncodedUrl();
$profile=array();
$companies=0;
$url_search='http://www.jobbank.gc.ca/';
$startReading=0;
$job=fopen($url['url'], 'r')or die("JobBanks is failing to respond.<br>Please Try again Later");
while(!feof($job))
{
set_time_limit(500);
$profile[$companies]= new jobProfile();
$trash=fgets($job);
if(!$startReading)
{
if(preg_match('~RepeaterSearchResults_hypJobItem_[0-9]+~',$trash,$matches))
{
$startReading=true;
}
}
if($startReading)
{
$data=$trash;
if(preg_match("~href=\".*\"~",$data,$matches))
{
$temp=preg_replace("~href=~",'',$matches[0]);
$temp=preg_replace("~\"~",'',$temp);
$profile[$companies]->setLink($url_search.$temp);
var_dump($profile[$companies]);
echo "<br>";
echo "<br>";
}
if(preg_match("~>[A-Za-z-, ]+\(~",$data,$matches))
{
$temp=preg_replace("~>|\(~",'',$matches[0]);
$profile[$companies]->setPosition(ucfirst($temp));
var_dump($profile[$companies]);
echo "<br>";
echo "<br>";
}
if(preg_match("~# *[0-9]+~",$data,$matches))
{
$profile[$companies]->setOrderNum(preg_replace("~#| ~",'',$matches[0]));
var_dump($profile[$companies]);
echo "<br>";
echo "<br>";
}
if(preg_match("~Employer:</strong>.*~",$data,$matches))
{
$temp=preg_replace("~Employer:</strong> ~",'',$matches[0]);
$temp=preg_replace("~<br.*~",'',$temp);
$temp=ucfirst($temp);
$profile[$companies]->setEmployer($temp);
var_dump($profile[$companies]);
echo "<br>";
echo "<br>";
}
if(preg_match("~[$][0-9]+.*~",$data,$matches))
{
$temp=preg_replace("~/.*~",'',$matches[0]);
$profile[$companies]->setSalary(preg_replace("~[$]~","$ ",$temp));
var_dump($profile[$companies]);
echo "<br>";
echo "<br>";
}
if(preg_match("~[$][0-9]+.*~",$data,$matches))
{
$temp=preg_replace('~[$A-Za-z0-9. ]*[/] ?~','',$matches[0]);
$profile[$companies]->setRate(preg_replace('~<.*~','',$temp));
var_dump($profile[$companies]);
echo "<br>";
echo "<br>";
}
if(preg_match("~Location:.*~",$data,$matches))
{
$temp=preg_replace('~.*;~','',$matches[0]);
$temp=preg_replace('~^ |,~','',$temp);
$profile[$companies]->setCity(ucfirst($temp));
//echo ucfirst($temp)."<br>";
}
if(preg_match("~Location[:<>/\,A-Za-z ]*~",$data,$matches))
{
$profile[$companies]->setProvince($matches[0]);
//echo " ".$matches[0]."<br>\n";
//echo $profile[$companies]->getLocation()."\n<br>";
}
if(preg_match("~[0-9]{4}/[0-9]{2}/[0-9]{1,2}~",$data,$matches))
{
echo $profile[$companies]->displayHTML();
$profile[$companies]->setDate($matches[0]);
if($profile[$companies]->allDataSet())
{
//echo "data was set"."<br>";
$startReading=false;
$companies++;
}
else
{
$startReading=false;
$companies++;
echo "Data was Not set";
}
}
}
}
fclose($job);
everything works except the $profile[number] doesn't store anything in it at all after the 3 rd if statement when the variable is stored.
If
{
//Profile[number] info stored
}
if
{
//Profile[number] info available
}
if
{
//profile[number] info available
}
if
{
//profile[number] info is gone
}
variable[$count].next($match)
the .next() moves the internal pointer to the next element in the array.

Categories