/    Sign up×
Community /Pin to ProfileBookmark

Why “if(!session_id()” Condition Triggers When Session ID Exists ?

Trying to build a pagination that works in 3 phases: Start, Midway, End.

QUESTIONS:

Q1. I need to know why following line never triggers when I press the ENTER and page loads. Lines 4-11.

[code]
if(isset($_SESSION[‘form_step’]))//Q1. WHY THIS ‘IF’ NEVER TRIGGERS WHEN PRESSING ‘ENTER’ AND LOADING PAGE AND THIS LINE IS UNCOMMENTED ?
{
unset( $_SESSION[‘form_step’] );
session_unset();
session_destroy();
echo “Form Step:”; echo $_SESSION[‘form_step’];
echo “Line: 10”;
}
[/code]

Q2. I need to know why the following IF gets triggered when I click any numbered links (eg page 2, page 3, Next Page, Previous Page) since session id already exists. It should only trigger if session id doesn’t exist. NOTE: This still gets triggered even if I delete/comment-out the lines 4-11 mentioned above on Q1.

[code]
if(!session_id()) //Q2. WHY THIS IF GETS TRIGGERED WHEN CLICKING ANY NUMBERED PAGE LINKS (ON PAGINATION SECTION (EG PAGE 1 2 3 ETC.)) SINCE SESSION ID ALREADY EXISTS DUE TO [‘form_step’] = ‘end’ ?
{
session_start();
$_SESSION[‘form_step’] = ‘start’;
echo session_id();
echo “Line: 20<br>”;
}
[/code]

Q3. When numbered links on pagination section (eg. Page 2, Next Page, Previous Page, etc.) are clicked, should I re-count the row matches using $sql_query_1 from result_count() or should I leave the code as it currently is ?

Trying to build a pagination that works in 3 phases: Start, Midway, End.

**NOTE: Am beginner. Still on: Procedural style prepared statements mysqli. Not yet into: Oop or Pdo.
Would appreciate sample code demonstrations in them formats only.**

I got a my questions written on the code comments where I am stuck and puzzled.

**SCRIPT:**
This is a one/single page script. And so, different params in the url trigger different parts (functions) of the script.

**HOW SCRIPT WORKS**

  • 1.

    At “Start” phase, page loads displaying webform. When Form is submitted, “midway” phase counts mysql matching rows using $sql_query_1 from result_count().

  • 2.

    Then rows are fetched using $sql_query_2 in pagination().

  • 3.

    If you click any numbered links on pagination section (eg. page 2, page 3, next page, previous page, etc.) then again only the matching rows are fetched using $sql_query_2 from pagination().

  • INITIAL URL FORMAT:
    http://localhost/power.page/pagination_test_simple.php
    http://localhost/power.page/pagination_test_simple.php?form_type=search&query_type=select&form_step=start

    PAGINATION URL SAMPLES:
    1.
    http://localhost/power.page/pagination_test_simple.php?form_type=search&query_type=select&form_step=end&page_limit=2&page=2

    2.
    http://localhost/power.page/pagination_test_simple.php?form_type=search&query_type=select&form_step=end&page_limit=2&page=3

    NOTE: Note the “form_step=” in the urls.

    The Single page Script:

    [code]
    <?php
    error_reporting(E_ALL);

    if(isset($_SESSION[‘form_step’]))//Q1. WHY THIS ‘IF’ NEVER TRIGGERS WHEN PRESSING ‘ENTER’ AND LOADING PAGE AND THIS LINE IS UNCOMMENTED ?
    {
    unset( $_SESSION[‘form_step’] );
    session_unset();
    session_destroy();
    echo “Form Step:”; echo $_SESSION[‘form_step’];
    echo “Line: 11”;
    }

    if(!session_id()) //Q2. WHY THIS IF GETS TRIGGERED WHEN CLICKING ANY NUMBERED PAGE LINKS (ON PAGINATION SECTION (EG PAGE 1 2 3 ETC.)) SINCE SESSION ID ALREADY EXISTS DUE TO [‘form_step’] = ‘end’ ?
    {
    session_start();
    $_SESSION[‘form_step’] = ‘start’;
    echo session_id();
    echo “Line: 20<br>”;
    }

    //$_SESSION[‘form_step’] = ‘start’;//DELETE THIS
    if(isset($_SESSION[‘form_step’]) && $_SESSION[‘form_step’] == ‘start’)//Only run this IF or one of the upcoming ELSEIFs when page is loaded due to page refresh or ENTER pressed or numbered page links clicked on pagination section (eg. page 1 2 3 etc.).
    {
    echo “Line: 26<br>”;//DELETE THIS LINE
    if(!isset($_GET[‘form_type’]) && empty($_GET[‘form_type’]))
    {
    die(“Invalid Form!”);
    }
    else
    {
    $_SESSION[‘form_type’] = $_GET[‘form_type’];
    echo “Line: 34<br>”;//DELETE THIS LINE

    if(!isset($_GET[‘query_type’]) && empty($_GET[‘query_type’]))
    {
    die(“Invalid Query!”);
    }
    else
    {
    $_SESSION[‘query_type’] = $_GET[‘query_type’];
    echo “Line: 43<br>”;//DELETE THIS LINE
    if(!function_exists($_SESSION[‘form_type’]))//eg. $_SESSION[‘search’]. This should trigger the search() function.
    {
    echo “Line: 46<br>”;//DELETE THIS LINE
    die(“Invalid Form!”);
    }
    else
    {
    echo “Line: 51<br>”;//DELETE THIS LINE
    $_SESSION[‘form_type’]();
    }
    }
    }
    }
    elseif(isset($_SESSION[‘form_step’]) && $_SESSION[‘form_step’] == ‘midway’)//Only run this ELSEIF or the next one or the previous one when page is loaded due to page refresh or ENTER pressed or numbered page links clicked on pagination section (eg. page 1 2 3 etc.).
    {
    echo “Line: 59<br>”;
    die(“invalid Query!”);
    }
    elseif(isset($_SESSION[‘form_step’]) && $_SESSION[‘form_step’] == ‘end’)//Only run this ELSEIF or the previous one or the IF before that, when page is loaded due to page refresh or ENTER pressed or numbered page links clicked on pagination section (eg. page 1 2 3 etc.).
    {
    echo “Line: 64<br>”;
    pagination();
    }
    ?>

    <!DOCTYPE HTML”>
    <html>

    <head>
    <meta name=”viewport” content=”width-device=width, initial-scale=1″>
    </head>
    <body>

    <?php
    function search()
    {echo “Line: 79<br>”;//DELETE THIS LINE
    ?>
    <form action=”<?php echo $_SERVER[‘PHP_SELF’];?>?form_type=<?php echo $_SESSION[‘form_type’];?>&query_type=<?php echo $_SESSION[‘query_type’];?>&form_step=midway&page_limit=2&page=1″ method=’post’ enctype=’plain/text’>
    <?php
    //Added ‘*’ (asterisk) to indicate the ‘Text Field’ is a ‘required’ one.
    echo “<label for=”first_name”>First Name *:</label>
    <input type=”text” name=”first_name” placeholder=”First Name” value = “”>”;?>
    <br>
    <?php
    echo “<label for=”marital_status”>Marital Status *:</label>”;
    echo “<select name=”marital_status”>”;
    echo “<option value=”single”>Single</option>”;
    echo “<option value=”married”>Married</option>”;
    echo “</select>”;
    echo “<br>”;
    ?>
    <input type=”submit” name=”search” value=”Search”>
    </form>
    <?php
    function result_count()
    {
    echo “result_count function started<br>”;//DELETE THIS LINE
    if(isset($_SESSION[‘form_step’]) && $_SESSION[‘form_step’] == ‘midway’)
    {echo “Line: 102<br>”;//DELETE THIS LINE

    //Connect to Database. (DB_SERVER, BD_USERNAME, DB_PASSWORD, DB_NAME).
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $conn = mysqli_connect(“localhost”,”root”,””,”powerpage”);
    $conn->set_charset(‘utf8mb4’); //Always set Charset.

    if($conn === false)
    {
    die(“ERROR: Connection Error!. ” . mysqli_connect_error());
    }

    $sql_query_1 = “SELECT COUNT(id) FROM users WHERE first_name = ? AND marital_status = ?”;
    $stmt_1 = mysqli_stmt_init($conn);
    if(mysqli_stmt_prepare($stmt_1,$sql_query_1))
    {
    mysqli_stmt_bind_param($stmt_1,”ss”,$_POST[“first_name”],$_POST[“marital_status”]);
    mysqli_stmt_execute($stmt_1);
    mysqli_stmt_bind_result($stmt_1,$row_count);
    mysqli_stmt_fetch($stmt_1);
    $_SESSION[“row_count”] = $row_count;
    mysqli_stmt_close($stmt_1);
    mysqli_close($conn);
    }
    $_SESSION[‘form_step’] = ‘end’;
    echo $_SESSION[‘form_step’];
    echo “Line: 128<br>”;//DELETE THIS LINE
    pagination();
    }
    }

    function pagination()
    {
    echo “pagination function started<br>”;//DELETE THIS LINE
    if(isset($_SESSION[‘form_step’]) && $_SESSION[‘form_step’] == ‘end’)
    {echo “Line: 137<br>”;//DELETE THIS LINE
    echo $_SESSION[‘form_step’];//DELETE THIS LINE
    $page_number = $_GET[‘page’];
    $result_per_page = $_GET[‘page_limit’];
    $row_start = (($page_number * $result_per_page) – $result_per_page); //Offset (Row Number that ‘Starts’ on page).
    $row_end = ($page_number * $result_per_page); //Row Number that ‘Ends’ on page.
    $previous_page = $page_number-1;
    $next_page = $page_number+1;

    echo “Row Start: $row_start<br>”;
    echo “Row End: $row_end<br>”;

    //Connect to Database. (DB_SERVER, BD_USERNAME, DB_PASSWORD, DB_NAME).
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $conn = mysqli_connect(“localhost”,”root”,””,”powerpage”);
    $conn->set_charset(‘utf8mb4’); //Always set Charset.

    if($conn === false)
    {
    die(“ERROR: Connection Error!. ” . mysqli_connect_error());
    }

    $sql_query_2 = “SELECT * FROM users WHERE first_name = ? AND marital_status = ? LIMIT $row_start,$row_end”;
    //$_SESSION[‘sql_query_2’] = $sql_query_2;
    $stmt_2 = mysqli_stmt_init($conn);
    if(mysqli_stmt_prepare($stmt_2,$sql_query_2))
    {
    mysqli_stmt_bind_param($stmt_2,”ss”,$_POST[“first_name”],$_POST[“marital_status”]);
    mysqli_stmt_execute($stmt_2);
    $result_2 = mysqli_stmt_get_result($stmt_2);

    $row_count = $_SESSION[“row_count”];
    $total_pages = ceil($row_count/$result_per_page);
    echo “TOTAL PAGES: $total_pages<br><br>”;
    echo “Line: 171<br>”;//DELETE THIS LINE
    while($row = mysqli_fetch_array($result_2,MYSQLI_ASSOC))
    {
    //Retrieve Values.
    $id = $row[“id”];
    $first_name = $row[“first_name”];
    $middle_name = $row[“middle_name”];
    $surname = $row[“surname”];
    $gender = $row[“gender”];
    $marital_status = $row[“marital_status”];
    $working_status = $row[“working_status”];

    echo “Id: $id<br>”;
    echo “First Name: $first_name<br>”;
    echo “Middle Name: $middle_name<br>”;
    echo “Surname: $surname<br>”;
    echo “Gender: $gender<br>”;
    echo “Marital Status: $marital_status<br>”;
    echo “Working Status: $working_status<br>”;
    }

    mysqli_stmt_close($stmt_2);
    mysqli_close($conn);

    $i = 1;
    if($page_number>$total_pages)
    {
    echo “<a href=’http://localhost/power.page/pagination_test_simple.php?form_type=”;?><?php echo $_SESSION[‘form_type’];?>&query_type=<?php echo $_SESSION[‘query_type’];?>&form_step=end&page_limit=2&page=<?php echo $total_pages;?>’><?php echo “<b> ->Final Page<- </b>”;?></a><?php
    }
    else
    {
    if($i<$total_pages)
    {
    echo “<a href=’http://localhost/power.page/pagination_test_simple.php?form_type=”;?><?php echo $_SESSION[‘form_type’];?>&query_type=<?php echo $_SESSION[‘query_type’];?>&form_step=end&page_limit=2&page=<?php echo $next_page;?>’><?php echo ” Next Page-> “;?></a><?php
    }

    while($i<=$total_pages)
    {
    if($i<$total_pages)
    {
    echo “<a href=’http://localhost/power.page/pagination_test_simple.php?form_type=”;?><?php echo $_SESSION[‘form_type’];?>&query_type=<?php echo $_SESSION[‘query_type’];?>&form_step=end&page_limit=2&page=<?php echo $i;?>’><?php echo ” $i “;?></a><?php
    }
    elseif($i==$page_number)
    {
    echo “<a href=’http://localhost/power.page/pagination_test_simple.php?form_type=”;?><?php echo $_SESSION[‘form_type’];?>&query_type=<?php echo $_SESSION[‘query_type’];?>&form_step=end&page_limit=2&page=<?php echo $i;?>’><?php echo “<b> $i </b>”;?></a><?php
    }
    $i++;
    }

    if($i<$total_pages)
    {
    echo “<a href=’http://localhost/power.page/pagination_test_simple.php?form_type=”;?><?php echo $_SESSION[‘form_type’];?>&query_type=<?php echo $_SESSION[‘query_type’];?>&form_step=end&page_limit=2&page=<?php echo $previous_page;?>’><?php echo ” <-Previous Page “;?></a><?php
    }
    }
    }
    //die();
    }
    }

    if($_SERVER[‘REQUEST_METHOD’] === ‘POST’)
    {
    if(isset($_POST[‘search’]))
    {
    $_SESSION[‘form_step’] = ‘midway’;
    echo $_SESSION[‘form_step’];//DELETE THIS LINE
    echo “Line: 237<br>”;//DELETE THIS LINE
    result_count();
    }
    }
    }

    ?>
    [/code]

    to post a comment
    PHP

    4 Comments(s)

    Copy linkTweet thisAlerts:
    @developer_webauthorJun 18.2020 — I was suggested to place this after error reporting or before it.
    <i>
    </i>session_start();


    But no luck solving my problems. Instead getting a new error:

    **Notice: Undefined index: form_step in C:xampphtdocspower.pagepagination_test_SIMPLE.php on line 10**

    Need suggestions that will solve my original issues without raising new ones. :)
    Copy linkTweet thisAlerts:
    @NogDogJun 18.2020 — > @developer_web#1619664 Notice: Undefined index: form_step in C:xampphtdocspower.pagepagination_test_SIMPLE.php on line 10

    Because you did you get rid of everything in $_SESSION right before that with these lines:
    <i>
    </i>{
    unset( $_SESSION['form_step'] );
    session_unset();
    session_destroy();
    Copy linkTweet thisAlerts:
    @developer_webauthorJun 21.2020 — @NogDog#1619667

    I do not understand.

    Anyway, I updated the code for further tests.

    Latest code:
    <i>
    </i>&lt;?php
    error_reporting(E_ALL);

    if(isset($_SESSION['form_step']))//Q1. WHY THIS 'IF' NEVER TRIGGERS WHEN PRESSING 'ENTER' AND LOADING PAGE AND THIS LINE IS UNCOMMENTED ?
    {
    unset( $_SESSION['form_step'] );
    session_unset();
    session_destroy();
    echo "Line: 11 "; echo "session destroyed!&lt;br&gt;";
    echo "Line: 12 "; echo "Session Step: "; echo $_SESSION['form_step'];
    }

    if(!session_id()) //Q2. WHY THIS IF GETS TRIGGERED WHEN CLICKING ANY NUMBERED PAGE LINKS (ON PAGINATION SECTION (EG PAGE 1 2 3 ETC.)) SINCE SESSION ID ALREADY EXISTS DUE TO ['form_step'] = 'end' ?
    {
    session_start();
    $_SESSION['form_step'] = 'start';
    echo "Line: 18 "; echo "Session Step: "; echo $_SESSION['form_step']; echo "&lt;br&gt;";
    echo "Line: 19 "; echo "New Session Id: "; echo session_id(); echo "&lt;br&gt;";
    }


    NogDog,

    Can you check my logic and my understanding of sessions, if you don't mind.

    Now concentrate on the above code. What is it saying ?

    It is saying that when the page loads, if it finds any session existing then kill all sessions.

    Then echo "Line 11" & "line 12" as a confirmation that the session has been killed.

    Then start a new session.

    And echo "Line 18" and "line 19" as a confirmation that a new session has been started.

    That is what I intended.

    Q1. Now, is my code correct to do that bit atleast ?

    Now let us test this code, shall we ?

    I load the page for the very 1st time. Obviously there will be no sessions at the beginning.

    And so, I do not get echoed "Line 11" & "line 12".

    But get echoed "Line 18" & "line 19".

    So far, so good.

    Now NogDog, bear in mind that, the session now exists.

    Let us now reload the page by CTRL+R or pressing the enter button on the url field.

    Result ?

    When I reload the page for the 2st time, the script should have found a session exists since we started it on the 1st round. Therefore, the 1st IF condition should have triggered echoing "Line 11" & echoing "line 12". But they don't get echoed. Why is that ?

    It means, on the 2nd round or 2nd time page load, the php found no session. Why did it not find the session that was started on the 1st round (started during the 1st page load) ?
    Copy linkTweet thisAlerts:
    @NogDogJun 22.2020 — I have never worried about session_id(), but I believe it's empty until after you do session_start(). So my suggestion is that, unless you have some specific reason to need to know what the session ID is, don't even bother with it. Instead, make sure you have a functioning session_start() for each page that needs it, and look for an element of interest in the $_SESSION array if you need to know if the user is logged in, or has been to page X, or whatever it is you need to know.
    ×

    Success!

    Help @developer_web spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 4.29,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,
    )...