I'm working on a project and I'm stuck with this problem: I have a variable called $category, which if is null or empty is set to 1. After submitting the form, $category++, so it becomes 2. Okay, but at the third submit it doesn't become 3. I checked what happens and I found out that actually after each submit, the $category becomes 1, because of the first code line that says that if it's null or empty it becomes 1. Let me show you the code to see what I'm talking about! Thank you in advance for helping! :)
session_start();
include_once('db.php');
$cat_SQL = 'SELECT * FROM categories ORDER BY id';
$cat_RESULT = mysql_query($cat_SQL, $conn);
$cat_ROWS = mysql_fetch_assoc($cat_RESULT);
$cat_ROWS_number = mysql_num_rows($cat_RESULT);
if (is_null($category) || empty($category)) {
$category = 1;
}
if (isset($category)) {
if ($category < $cat_ROWS_number) {
$category = $category + 1; echo $category;
}
}
So if I echo the category each time the page loads, I have something like this:
First time you enter the page: category is empty so it becomes 1 => $category = 1 After 1st SUBMIT $category = $category + 1 => $category = 2 After 2nd SUBMIT $category = $category + 1 => $category = 2 (still 2 instead of becoming 3) and so on... :( HOW CAN I STOP $category from become '1' each time the page reloads / submits, and become the new value instead (per session)?
So I eventually managed to do it before seeing your answers (not bragging, but happy that I found the answer myself :)) )
if (!isset($_SESSION['category'])) {
$_SESSION['category'] = 1;
$category = $_SESSION['category'];
}
else {
if($_SESSION['category'] < $cat_ROWS_number) {
$_SESSION['category']++;
$category = $_SESSION['category'];
}
}
However, thank you all for your quick replies!!! :)
One way to do this, is to put $category inside a session variable. After the session_start
but before the if (is_null($category) || empty($category))
you put:
if(isset($_SESSION['category']))
$category = $_SESSION['category'];
And then after the $category = $category + 1;
you put:
$_SESSION['category'] = $category;
That ought to do the trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With