Neither IF Nor ELSE Triggers In php Script Flow! Why? - php

Folks,
I am not killing the script flow, before the CONDITION, with
die();
And so, one of the 2 should trigger:
IF
ELSE
But they don't.
if(!$result_2)
{
echo __LINE__; echo "<br>"; //LINE 92: THIS LINE IN 'IF' DOES NOT TRIGGER. NEITHER THE LINE IN THE 'ELSE'. WHY ?
die("Fetching Error");
}
while($row = mysqli_fetch_array($result_2,MYSQLI_ASSOC))
{
echo __LINE__; echo "<br>";//LINE 98: THIS LINE IS LIKE AN 'ELSE'. IT DOES NOT TRIGGER. NEITHER THE LINE IN THE 'IF'. WHY ?
Either Line 92 (IF) should trigger or Line 98 (which is like the ELSE).
Do notice the comments in the code to understand where the script is ending the flow without any reason.
<?php
$query_2 = "SELECT id,page_url,link_anchor_text,page_description,keyphrases,keywords FROM links WHERE keywords = ? ORDER by id LIMIT $offset,$limit";
$stmt_2 = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt_2,$query_2))
{
echo __LINE__; echo "<br>";//LINE 84: THIS LINE GETS TRIGGERED AND ECHOED IN TEST. LAST LINE THAT GETS ECHOED.
mysqli_stmt_bind_param($stmt_2,'s',$keywords);
mysqli_stmt_execute($stmt_2);
$result_2 = mysqli_stmt_get_result($stmt_2);
if(!$result_2)
{
echo __LINE__; echo "<br>"; //LINE 92: THIS LINE IN 'ELSE' DOES NOT TRIGGER. NEITHER THE LINE IN THE 'IF'. WHY ?
die("Fetching Error");
}
What is killing the script flow ?
Context:
<?php
echo __LINE__; echo "<br>"; //LINE 16: THIS LINE GETS TRIGGERED AND ECHOED IN TEST
if(!ISSET($_GET['keywords']))
{
echo __LINE__; echo "<br>";
die("Type your keywords");
}
$keyword = $_GET['keywords'];
//Check if the PAGE NUMBER is specified or not and if it's a numer or not. If not, return the default: 1.
$page = ISSET($_GET['page']) && is_numeric($_GET['page']) ? $_GET['page'] : 1;
//Check if the PAGE RESULT LIMIT is specified or not and if it's a numer or not. If not, return the default: 1.
$limit = ISSET($_GET['limit']) && is_numeric($_GET['limit']) ? $_GET['limit'] : 1;
$query_1 = "SELECT COUNT(id) FROM links WHERE keywords = ?";
$stmt_1 = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt_1,$query_1))
{
echo __LINE__; echo "<br>";//LINE 57: THIS LINE GETS TRIGGERED AND ECHOED IN TEST. BUT WHY SCRIPT FLOW DOES NOT GO BEYOND THIS LINE ?
mysqli_stmt_bind_param($stmt_1,'s',$keywords);
mysqli_stmt_execute($stmt_1);
$result_1 = mysqli_stmt_bind_result($stmt_1,$row_count);
mysqli_stmt_fetch($stmt_1);
}
else
{
echo __LINE__; echo "<br>"; //LINE 67
printf("Error: %s.\n", mysqli_stmt_error($stmt_1));
printf("Error: %d.\n", mysqli_stmt_errno($stmt_1));
die("A. Prepare failed!");
}
mysqli_stmt_close($stmt_1);
//$total_pages = ceil($result_1/$limit); //SHOULD I KEEP THIS LINE OR THE ONE BELOW THIS ONE ?
$total_pages = ceil($row_count/$limit); //SHOULD I KEEP THIS LINE OR THE ONE ABOVE THIS ONE ?
$offset = (($page * $limit) - $limit);
$query_2 = "SELECT id,page_url,link_anchor_text,page_description,keyphrases,keywords FROM links WHERE keywords = ? ORDER by id LIMIT $offset,$limit";
$stmt_2 = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt_2,$query_2))
{
echo __LINE__; echo "<br>";//LINE 84: THIS LINE GETS TRIGGERED AND ECHOED IN TEST. LAST LINE THAT GETS ECHOED.
mysqli_stmt_bind_param($stmt_2,'s',$keywords);
mysqli_stmt_execute($stmt_2);
$result_2 = mysqli_stmt_get_result($stmt_2);
if(!$result_2)
{
echo __LINE__; echo "<br>"; //LINE 92: THIS LINE IN 'IF' DOES NOT TRIGGER. NEITHER THE LINE IN THE 'ELSE'. WHY ?
die("Fetching Error");
}
while($row = mysqli_fetch_array($result_2,MYSQLI_ASSOC))
{
echo __LINE__; echo "<br>";//LINE 98: THIS LINE IS LIKE AN 'ELSE'. IT DOES NOT TRIGGER. NEITHER THE LINE IN THE 'IF'. WHY ?
echo "LIMIT: $limit<br>";
echo "ROW COUNT: $row_count<br><br>";
echo "TOTAL PAGES: $total_pages<br><br>";
//Retrieve Values.
$id = $row["id"];
$page_url = $row["page_url"];
$link_anchor_text = $row["link_anchor_text"];
$page_description = $row["page_description"];
$keyphrases= $row["keyphrases"];
$keywords = $row["keywords"];
echo "Id: $id<br>";
echo "Page Url: $page_url<br>";
echo "Link Anchor Text: $link_anchor_text<br>";
echo "Page Description: $page_description<br>";
echo "Keyphrases: $keyphrases<br>";
echo "Keywords: $keywords<br>";
echo "<br>";
echo "<br>";
}
}
else
{
echo __LINE__; echo "<br>";//Line 124
printf("Error: %s.\n", mysqli_stmt_error($stmt_2));
printf("Error: %d.\n", mysqli_stmt_errno($stmt_2));
die("B. Prepare failed!");
}
Also, out of these 2, which one is correct ?
$total_pages = ceil($result_1/$limit); //SHOULD I KEEP THIS LINE OR THE ONE BELOW THIS ONE ?
$total_pages = ceil($row_count/$limit); //SHOULD I KEEP THIS LINE OR THE ONE ABOVE THIS ONE ?
UPDATE
My code now looks like this.
My issues are mentioned clearly in the code comments in CAPITALS.
CURRENT ISSUES:
ISSUE 1:
Pagination Section only displays link to PAGE 1 from PAGE 1. Fails to display link to PAGE 2. Code configured to display 1 row per page. Since there are 2 matching rows then naturally 2 pages should display all the results. Why pagination section fails to display link to PAGE 2 from PAGE 1 ?
error_reporting.php
<?php
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
ini_set('error_reporting',E_ALL);
?>
<?php
require 'conn.php';
require 'error_reporting.php';
?>
<!DOCTYPE HTML">
<html>
<head>
<meta name="viewport" content="width-device=width, initial-scale=1">
</head>
<body>
<form method='GET' action="<?php echo $_SERVER['PHP_SELF'];?>?keywords=$keywords&limit=$limit&page=1">
<label for="keywords">Keywords:*</label>
<input type="text" name="keywords" id="keywords" placeholder="Input Keywords" required>
<br>
<label for="limit">Results per Page</label>
<select name="limit" id="limit">
<option value="1">1</option>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
<br>
<button name="search" id="search" value=" ">Search</button><br>
<button type="submit" name="search" id="search" value="search">Search</button>
<br>
<input type="reset">
<br>
</form>
<?php
echo __LINE__; echo "<br>"; //LINE 16: THIS LINE GETS TRIGGERED AND ECHOED IN TEST
if(!ISSET($_GET['keywords']))
{
echo __LINE__; echo "<br>";
die("Type your keywords");
}
$keywords = $_GET['keywords'];
//Check if the PAGE NUMBER is specified or not and if it's a numer or not. If not, return the default: 1.
$page = ISSET($_GET['page']) && is_numeric($_GET['page']) ? $_GET['page'] : 1;
//Check if the PAGE RESULT LIMIT is specified or not and if it's a numer or not. If not, return the default: 1.
$limit = ISSET($_GET['limit']) && is_numeric($_GET['limit']) ? $_GET['limit'] : 1;
$query_1 = "SELECT COUNT(id) FROM links WHERE keywords = ?";
$stmt_1 = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt_1,$query_1))
{
echo __LINE__; echo "<br>";//LINE 57: THIS LINE GETS TRIGGERED AND ECHOED IN TEST.
mysqli_stmt_bind_param($stmt_1,'s',$keywords);
mysqli_stmt_execute($stmt_1);
$result_1 = mysqli_stmt_bind_result($stmt_1,$row_count);
mysqli_stmt_fetch($stmt_1);
echo "ROW COUNT: $row_count<br><br>";
}
else
{
echo __LINE__; echo "<br>"; //LINE 67
printf("Error: %s.\n", mysqli_stmt_error($stmt_1));
printf("Error: %d.\n", mysqli_stmt_errno($stmt_1));
die("A. Prepare failed!");
}
mysqli_stmt_close($stmt_1);
$total_pages = ceil($row_count/$limit);
$offset = (($page * $limit) - $limit);
$query_2 = "SELECT id,page_url,link_anchor_text,page_description,keyphrases,keywords FROM links WHERE keywords = ? ORDER by id LIMIT $offset,$limit";
$stmt_2 = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt_2,$query_2)) //LINE 82:
{
echo __LINE__; echo "<br>";//LINE 84: THIS LINE GETS TRIGGERED AND SO PREPARED STATEMENT DID NOT FAIL AT LINE 82!
mysqli_stmt_bind_param($stmt_2,'s',$keywords);
mysqli_stmt_execute($stmt_2);
$result_2 = mysqli_stmt_get_result($stmt_2);
if(!$result_2)
{
echo __LINE__; echo "<br>"; //LINE 92: THIS LINE IN 'IF' DOES NOT TRIGGER. NEITHER THE LINE IN THE 'ELSE'. WHY ?
die("Fetching Error");
}
while($row = mysqli_fetch_array($result_2,MYSQLI_ASSOC))//LINE 96: THIS LINE IS LIKE AN 'ELSE'. IT DOES NOT TRIGGER. NEITHER THE LINE IN THE 'IF'. WHY ?
{
echo __LINE__; echo "<br>";
echo "LIMIT: $limit<br>";
echo "ROW COUNT: $row_count<br><br>";
echo "TOTAL PAGES: $total_pages<br><br>";
//Retrieve Values.
$id = $row["id"];
$page_url = $row["page_url"];
$link_anchor_text = $row["link_anchor_text"];
$page_description = $row["page_description"];
$keyphrases = $row["keyphrases"];
$keywords = $row["keywords"];
echo "Id: $id<br>";
echo "Page Url: $page_url<br>";
echo "Link Anchor Text: $link_anchor_text<br>";
echo "Page Description: $page_description<br>";
echo "Keyphrases: $keyphrases<br>";
echo "Keywords: $keywords<br>";
echo "<br>";
echo "<br>";
}
}
else
{
echo __LINE__; echo "<br>";//LINE 124
printf("Error: %s.\n", mysqli_stmt_error($stmt_2));
printf("Error: %d.\n", mysqli_stmt_errno($stmt_2));
die("B. Prepare failed!");
}
mysqli_stmt_close($stmt_2);
//PAGINATION SECTION STARTS FROM HERE:
//WHY PAGINATION SECTION FAILS TO DISPLAY ? ONLY A LINK TO PAGE 1 IS SHOWN WHEN YOU LOAD PAGE 1. NO LINK TO PAGE 2. THERE ARE 2 MATCHING ROWS. SCRIPT FIXED TO SHOW 1 ROW PER PAGE. AND SO, 2 PAGES SHOULD DISPLAY ALL RESULTS. HENCE, PAGINATION SECTION SHOULD SHOW A LINK TO PAGE 2 FROM PAGE 1. BUT PAGE 1 ONLY LINKS TO ITSELF IN THE PAGINATION SECTION.
if($page>$total_pages) //If Page Number is greater than Total Pages, show only a link to FINAL PAGE.
{
echo "?>";?><?php echo "<b> Final Page </b>";?><?php
}
else
{
$i = 1;
while($i<=$total_pages)
{
if($i<$total_pages)
{
echo "";?><?php echo " $i ";?><?php
}
elseif($i==$page) //Bold the Current Page Number.
{
echo "";?><?php echo "<b> $i </b>";?><?php
}
$i++;
}
}
?>
UPDATE AGAIN:
ISSUE: Missing in Url "&page=".
Look at this html:
<form method='GET' action="<?php echo $_SERVER['PHP_SELF'];?>?keywords=$keywords&limit=$limit&page=1">
As you can see, after clicking the form button, you should be sent to:
pagination_test_2.php?keywords=$keywords&limit=$limit&page=1"
But guess what ? you are sent to:
?keywords=$keywords&limit=$limit&search=search"
Where is the "&page=1" part in the url ?
Also, how not to have "search=search" added to the url ?
<?php
require 'conn.php';
require 'error_reporting.php';
?>
<!DOCTYPE HTML">
<html>
<head>
<meta name="viewport" content="width-device=width, initial-scale=1">
</head>
<body>
<form method='GET' action="<?php echo $_SERVER['PHP_SELF'];?>?keywords=$keywords&limit=$limit&page=1">
<label for="keywords">Keywords:*</label>
<input type="text" name="keywords" id="keywords" placeholder="Input Keywords" required>
<br>
<label for="limit">Results per Page</label>
<select name="limit" id="limit">
<option value="1">1</option>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
<br>
<button name="search" id="search" value=" ">Search</button><br>
<button type="submit" name="search" id="search" value="search">Search</button>
<br>
<input type="reset">
<br>
</form>
<?php
echo __LINE__; echo "<br>";
if(!ISSET($_GET['keywords']))
{
echo __LINE__; echo "<br>";
die("Type your keywords");
}
$keywords = $_GET['keywords'];
//Check if the PAGE NUMBER is specified or not and if it's a numer or not. If not, return the default: 1.
$page = ISSET($_GET['page']) && is_numeric($_GET['page']) ? $_GET['page'] : 1;
//Check if the PAGE RESULT LIMIT is specified or not and if it's a numer or not. If not, return the default: 1.
$limit = ISSET($_GET['limit']) && is_numeric($_GET['limit']) ? $_GET['limit'] : 1;
$query_1 = "SELECT COUNT(id) FROM links WHERE keywords = ?";
$stmt_1 = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt_1,$query_1))
{
echo __LINE__; echo "<br>";
mysqli_stmt_bind_param($stmt_1,'s',$keywords);
mysqli_stmt_execute($stmt_1);
$result_1 = mysqli_stmt_bind_result($stmt_1,$row_count);
mysqli_stmt_fetch($stmt_1);
echo "ROW COUNT: $row_count<br><br>";
}
else
{
echo __LINE__; echo "<br>";
printf("Error: %s.\n", mysqli_stmt_error($stmt_1));
printf("Error: %d.\n", mysqli_stmt_errno($stmt_1));
die("A. Prepare failed!");
}
mysqli_stmt_close($stmt_1);
$total_pages = ceil($row_count/$limit);
$offset = (($page * $limit) - $limit);
$query_2 = "SELECT id,page_url,link_anchor_text,page_description,keyphrases,keywords FROM links WHERE keywords = ? ORDER by id LIMIT $offset,$limit";
$stmt_2 = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt_2,$query_2))
{
echo __LINE__; echo "<br>";
mysqli_stmt_bind_param($stmt_2,'s',$keywords);
mysqli_stmt_execute($stmt_2);
$result_2 = mysqli_stmt_get_result($stmt_2);
if(!$result_2)
{
echo __LINE__; echo "<br>";
die("Fetching Error");
}
while($row = mysqli_fetch_array($result_2,MYSQLI_ASSOC))
{
echo __LINE__; echo "<br>";
echo "LIMIT: $limit<br>";
echo "ROW COUNT: $row_count<br><br>";
echo "TOTAL PAGES: $total_pages<br><br>";
//Retrieve Values.
$id = $row["id"];
$page_url = $row["page_url"];
$link_anchor_text = $row["link_anchor_text"];
$page_description = $row["page_description"];
$keyphrases = $row["keyphrases"];
$keywords = $row["keywords"];
echo "Id: $id<br>";
echo "Page Url: $page_url<br>";
echo "Link Anchor Text: $link_anchor_text<br>";
echo "Page Description: $page_description<br>";
echo "Keyphrases: $keyphrases<br>";
echo "Keywords: $keywords<br>";
echo "<br>";
echo "<br>";
}
}
else
{
echo __LINE__; echo "<br>";
printf("Error: %s.\n", mysqli_stmt_error($stmt_2));
printf("Error: %d.\n", mysqli_stmt_errno($stmt_2));
die("B. Prepare failed!");
}
mysqli_stmt_close($stmt_2);
if($page>$total_pages) //If Page Number is greater than Total Pages, show only a link to FINAL PAGE.
{
echo ""; echo "<b> Final Page </b>";?><?php
}
else
{
$i = 1;
while($i<=$total_pages)
{
if($i<$total_pages && $i!=$page)
{
echo ""; echo " $i ";?><?php
}
elseif($i==$page) //Bold the Current Page Number.
{
echo ""; echo "<b> $i </b>";?><?php
}
else
{
echo ""; echo " $i ";?><?php
}
$i++;
}
}
?>
Typos were on the urls in the pagination section. Now, I fixed them and so pagination section working fine.
Can someone be kind enough to checkout my code and let me know which lines to weedout if they are not really necessary.

I think neither lines are reached because the statement is valid but returns zero rows. Before $query_2 = ... could you add a check on $row_count to see if there are any rows?
To answer your second question, $total_pages = ceil($row_count/$limit); is the correct one to use because mysqli_stmt_bind_result returns a boolean so $result_1 would be true or false.
Personally I prefer object oriented style rather than procedural style as you have used because I find it easier to read but the choice is yours.

Related

Why $_SESSION Value Auto Changes On Every Page Load?

I am building a pagination (SERP). Stuck on a single issue. The $_SESSION['row_count'] auto changes on every page load. Same page load. I can't figure-out why this unpermitted activity takes place by php.
This is a one page membership script (one page site) I am building. That means, register, login, logout, account homepage, search & pagination are not all different pages but one page where each have their own parts (functions).
The log & reg parts of the codes (functions) work. Only the keyword search & pagaination part of the script is failing due to the $_SESSION['row_count'] = 5 auto switching to $_SESSION['row_count'] = 0 on every page load.
Because my keyword search has 5 matches and due to me setting it to show 1 row per page, I should see 5 pages with a total of 5 rows or 1 row per page.
The PAGE 1 manages to show 1 matching row as expected. It's just, when I click any page (PAGE 2/PAGE3/PAGE4/PAGE5) then the $_SESSION['row_count'] = 5 auto switches to $_SESSION['row_count'] = 0 and so the sql_query fetches no rows.
//Grab total number of pages to paginate.
$row_count = $_SESSION['row_count'];//Pages beyong PAGE 1 this switches value from 5 to 0. That is BIG ISSUE! Why the switching ?
$total_pages = ceil($row_count/$result_per_page);
After clicking the SEARCH button, this part of my code yields $SESSION['row_count'] = 5. So far so good.
$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,$query_1))
{
mysqli_stmt_bind_param($stmt_1,"ss",$_POST["first_name"],$_POST["marital_status"]);
mysqli_stmt_execute($stmt_1);
$result_1 = mysqli_stmt_bind_result($stmt_1,$row_count);
mysqli_stmt_fetch($stmt_1);
$_SESSION['row_count'] = $row_count;
NOTE:
I am successfully shown the matching rows on PAGE 1. Since I set it to display 1 row per page, I am shown 1 matching row. So far, so good.
Now, when I click PAGE 2 on the PAGINATION section, I expect to see the 2nd matching row, but "$SESSION['row_count'] = 5" auto switches to "$SESSION['row_count'] = 0" and so no matching rows get shown. I repeat: Why the switching of values from '5' to '0' when I click PAGE 2 or onwards ?
This illegal switching ruins this following query that runs when I click PAGE 2 or any PAGE beyond PAGE 1:
$row_count = $_SESSION['row_count'];
//$total_pages = ceil($result_1/$result_per_page); //Should I keep this line or the line below ? Which one ?
$total_pages = ceil($row_count/$result_per_page); //Should I keep this line or the line above it ? Which one ?
CONTEXT:
<?php
error_reporting(E_ALL);
session_start();
?>
<!DOCTYPE HTML">
<html>
<head>
<meta name="viewport" content="width-device=width, initial-scale=1">
</head>
<body>
<?php
if(!isset($_GET['query_type']) && empty($_GET['query_type']))
{
die("Invalid Query!");
}
else
{
$_SESSION['query_type'] = $_GET['query_type']; echo __LINE__; echo "<br>";//DELETE
}
echo __LINE__; echo "<br>";//DELETE
if(!isset($_GET['form_type']) && empty($_GET['form_type']))
{
die("Invalid Form!");
}
else
{
$_SESSION['form_type'] = $_GET['form_type']; echo __LINE__; echo "<br>";//DELETE
if(!function_exists($_SESSION['form_type']))
{
die("Invalid Form!");
}
else
{echo __LINE__; echo "<br>";//DELETE
if(!isset($_SESSION['form_step']))// || $_SESSION['form_step'] != 'end')
{
$_SESSION['form_step'] = 'start'; echo $_SESSION['form_step'];
echo __LINE__; echo "<br>";//DELETE
$_SESSION['form_type']();
}
else
{
$_SESSION['form_step'] = $_GET['form_step'];
echo __LINE__; echo "<br>"; echo $_SESSION['form_step'];//DELETE
$_SESSION['form_type']();
}
}
}
//FUNCTIONS START FROM HERE
function search()
{echo __LINE__; echo "<br>";//DELETE
function rows_count()
{
//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());
}
$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,$query_1))
{
mysqli_stmt_bind_param($stmt_1,"ss",$_POST["first_name"],$_POST["marital_status"]);
mysqli_stmt_execute($stmt_1);
$result_1 = mysqli_stmt_bind_result($stmt_1,$row_count);
mysqli_stmt_fetch($stmt_1);
$_SESSION['row_count'] = $row_count;
echo __LINE__; echo "<br>";//DELETE
$_SESSION['form_step'] = 'end'; //$form_step = 'end'; WRONG
//fetch_rows();
}
//Close Statement.
mysqli_stmt_close($stmt_1);
//Close Connection.
mysqli_close($conn);
}
function fetch_rows()
{ echo __LINE__; echo "<br>";//DELETE
$form_step = $_GET['form_step'];
$page_number = $_GET['page'];
$result_per_page = $_GET['page_limit'];
$offset = (($page_number * $result_per_page) - $result_per_page); //Offset (Row Number that 'Starts' on page).
$last_row_on_page = ($page_number * $result_per_page); //Max Result (Row Number that 'Ends' on page).
$previous_page = $page_number-1;
$next_page = $page_number+1;
echo "Row Start: $offset";echo "<br>";
echo "Row End: $last_row_on_page";echo "<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());
}
$query_2 = "SELECT * FROM users WHERE first_name = ? AND marital_status = ? ORDER BY id LIMIT $offset,$last_row_on_page";
$stmt_2 = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt_2,$query_2))
{echo __LINE__; echo "<br>";//On PAGINATION PAGE 2, THIS GETS ECHOED. IT IS LINE: 111.
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);
echo __LINE__; echo "<br>";//On PAGINATION PAGE 2, THIS GETS ECHOED. IT IS LINE: 114.
//Grab total number of pages to paginate.
$row_count = $_SESSION['row_count'];
//$total_pages = ceil($result_1/$result_per_page);
$total_pages = ceil($row_count/$result_per_page);
echo "TOTAL PAGES: $total_pages<br><br>";
while($row = mysqli_fetch_array($result_2,MYSQLI_ASSOC))
{echo __LINE__; echo "<br>";
//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>";
echo "<br>";
echo "<br>";
}
$i = 1;
while($i<=$total_pages)
{
if($i<$total_pages)
{
echo "<a href='http://localhost/power.page/pagination_test_simple_WORKING_ON_NOW_1.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_WORKING_ON_NOW_1.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($page_number>$total_pages)
{
echo "<a href='http://localhost/power.page/pagination_test_simple_WORKING_ON_NOW_1.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 "<b> Previous </b>";?></a><?php
}
}
//Close Statement.
mysqli_stmt_close($stmt_2);
//Close Connection.
mysqli_close($conn);
$_SESSION['form_step'] = 'end';
//die();
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>?form_type=<?php echo $_SESSION['form_type'];?>&query_type=<?php echo $_SESSION['query_type'];?>&form_step=end&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">
<?php
//$current_function = __FUNCTION__;
//echo $current_function;
//Do following if "Search" button clicked.
if($_SERVER['REQUEST_METHOD'] === 'POST')
{echo __LINE__; echo "<br>";//DELETE
//Do following if "Search" button clicked.
if(isset($_POST['search']))
{echo __LINE__; echo "<br>";//DELETE
rows_count(); //This function will forward script flow to fetch_rows() before halting the script.
fetch_rows(); //On PAGINATION PAGE 2, THIS FUNCTION IS NOT GETTING TRIGGERED! WHY ? IT IS LINE: 200. MAIN ISSUE HERE, I SUSPECT.
echo __LINE__; echo "<br>";//On PAGINATION PAGE 2, THIS GETS ECHOED. IT IS LINE: 201.
die;
}
}
echo __LINE__; echo "<br>";//On PAGINATION PAGE 2, THIS FAILS TO ECHO. IT IS LINE: 198.
//Do following if "Search" button not clicked but pagination numbered links are clicked. Eg Page 1, 2, 3, etc..
//rows_count(); //This function will forward script flow to fetch_rows() before halting the script.
fetch_rows(); //On PAGINATION PAGE 2, THIS FUNCTION IS NOT GETTING TRIGGERED! WHY ? IT IS LINE: 200. MAIN ISSUE HERE, I SUSPECT.
echo __LINE__; echo "<br>";//On PAGINATION PAGE 2, THIS GETS ECHOED. IT IS LINE: 201.
die;
}
?>
NOTE: I moved the session_start() to the top of the file underneath the error_reporting() but no luck. I even switched form method='post' to 'get' and tested. No luck. So, switched it back.

PHP pagination isn't working and I'm not sure why

I feel like I ask a lot of questions.
Anyways, I'm writing pagination for some database entries, and it looks sound to me but it's only displaying the first 10 posts and nothing else when I click the links.
The whole shebang is right here:
<?php
$post_limit = 10;
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("failed to connect: " . $conn->connect_error);
}
$sql = "SELECT count(id) FROM $tablename";
$result = mysqli_query($conn, $sql);
if (!$result) {
echo "you fucked up";
} else {
echo $row["id"];
}
$row = mysqli_fetch_array($result, MYSQL_NUM);
$post_count = $row[0];
if(isset($_GET['page'])) {
$page = $_GET['page'] + 1;
$offset = $post_limit * $page;
} else {
$page = 0;
$offset = 0;
}
$post_left = $post_count - ($page * $post_limit);
$sql = "SELECT id, upvotes, downvotes, name, title, message, date, time FROM posts ORDER BY date DESC, time DESC LIMIT $offset, $post_limit";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<br><div id='messageBar'>";
echo " ❖ </b>";
echo "Posted by <b>";
echo htmlspecialchars($row["name"]);
echo "</b> on ";
echo $row["date"];
echo " at ";
echo $row["time"];
if (!empty($row['title'])) {
echo " - <b>";
echo htmlspecialchars($row["title"]);
echo "</b>";
}
echo "<span style='float: right'>#";
echo $row["id"];
echo "</span>";
echo "</div><div id='messageContent'>";
echo htmlspecialchars($row["message"]);
echo "<br><br><span id='commentLink'><a class='commentLink' href='thread.php?id=$row[id]'>view thread </a></span>";
echo "<br></div><br><hr>";
}
} else {
echo "<br>";
echo "<center><i>it's dusty in here</i></center>";
echo "<br>";
}
if ($page > 0) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a> | ";
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($page == 0) {
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($post_left < $post_limit) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a>";
}
$conn->close();
?>
The link for the next page appears at the bottom, but clicking it takes you to the page you're already on with the same 10 most recent posts.
I am trying to learn PHP as I go, so I appreciate any help. Thank you!
Instead of using $_GET please use $_SESSION to manage a counter.
Every time you go in this page you increment the counter.
So, you have to do this on the top of the page:
if(isset($_SESSION['counter'])) {
$page = $_SESSION['counter'] + 1;
$offset = $post_limit * $page;
} else {
$page = 0;
$offset = 0;
$_SESSION['counter']=0;
}
Try this.
By the way there is Datatables which do what you're looking for.
P.S. If you don't start sessions in some other points in your code, please put session_start(); in the first page (e.g., login.php) otherwise put on this page.
Fixed. Problem was here:
if ($page > 0) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a> | ";
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($page == 0) {
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($post_left < $post_limit) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a>";
}
The URL I was linking to wasn't supposed to have spaces around the = sign. It's still buggy, but it works.

display text if in mysql there is a number

I have a database with 4 columns, id, user, vipplan and expire.
What i want to do, is this:
i have my vipplan table, and:
if number 0 is in database: then display "N/A"
if number 1 is in database: then display "Sr.Pro"
if number 2 is in database: then display "No seas"
if number 3 is in database: then display "Level0"
But i do not know how to do it, i post my code:
<?php
echo "<h2>Resultados:</h2><p>";
if(isset($_POST['user']))
{
$find = $_POST['user'];
if ($find == "")
{
echo "<p>Olvidaste poner tu usuario -.-!!!";
exit;
}
mysql_connect("localhost", "root", "2513") or die(mysql_error());
mysql_select_db("invasionvip") or die(mysql_error());
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
$iname = mysql_query("SELECT * FROM users WHERE usuario LIKE '%$find%'")
or die(mysql_error());
while($result = mysql_fetch_array( $iname ))
{
echo "id:" .$result['id'];
echo "<br>";
echo "usuario:".$result['usuario'];
echo "<br>";
echo "Plan VIP:".$result['planvip'];
echo "<br>";
echo "Vencimiento :".$result['vencimiento'];
echo "<br>";
}
$anymatches = mysql_num_rows($iname);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query...<br><br>";
}
echo "<b>Searched For:</b> " .$find;
}
?>
and my form is very simple:
<form class="pure-form" method="post" action="user.php">
<center>Aqui podrás ver tus servicios activos, como V.I.P, vehiculos, skins, etc.</center><br/>
<span style="text-align:left;font-size:25px;">Usuario: </span>
<input type="text" name="user">
<button type="submit" class="pure-button">Search</button>
</form>
thank you, :)
I believe what you are after is a case select. You should put this in the select line of your query.
there are multiple way that you can achieve this ourput
i thing the easiest way is switch statement second if else if and else third one is array notation which #b0s3 define earlier.
Switch example
switch(expression) {
case 1:
echo "Sr.Pro";
break;
case 2:
echo "No seas";
break;
case 3:
echo "Level0";
break;
default:
echo "N/A";
}
if else example
if( $databaseValue == 1 ){
echo "Sr.Pro";
}else if( $databaseValue == 2 ){
echo "No seas";
}else if( $databaseValue == 3 ){
echo "Level0";
}else{
echo "N/A";
}
Array Example
$yourValues = ['N/A', 'Sr.Pro', 'No seas', 'Level0'];
echo $yourValues[$databaseValue];
now it's up to your which one you like to use
You can use the "case" expression in the mysql select line.
This is a switch statement that allows you to return an arbitrary value for different conditions.
SELECT
CASE number
WHEN 0 THEN "N/A"
WHEN 1 THEN "Sr.Pro"
WHEN 2 THEN "No seas"
WHEN 3 THEN "Level0"
END CASE
FROM table_exemple

How to go product details page from product page

I'm trying with a E-Commerce website. But I'm having trouble. I want that when I click in the view details link of a product, the details of the product will be shown on the product_details.php page. But I can't transfer the product id to the product_details.php page.
My code is here...
<?php
include ("include/header.php");
?>
<?php
mysql_connect("localhost", "root", "") or die("problem with Connection");
mysql_select_db("finalproject");
$per_page = 3;
$pages_query = mysql_query("SELECT COUNT('product_id') FROM product");
$pages = ceil(mysql_result($pages_query, 0) / $per_page);
$page = (isset ($_GET['page'])) ? (int) $_GET['page'] : 1;
$start = ($page - 1 ) * $per_page;
$query = mysql_query("SELECT * FROM product LIMIT $start,$per_page");
while ($query_row = mysql_fetch_assoc($query))
{
echo "<b>$query_row[product_name]</b><br>";
echo "<b>Brand : </b> $query_row[product_brand] <br>";
echo "<b>Description : </b> $query_row[description] <br>";;
echo "<b>Price : </b> $query_row[price] <br>";
echo ('View details<br><br>') ;
?>
<form action="product_details.php?productId=<?php echo $row['product_id'];? >>" method="post">
<?php
}
$prev = $page - 1;
$next = $page + 1;
if (!($page <=1))
{
echo "<a href='buyproduct.php?page=$prev'>Prev</a> ";
}
if($pages >= 1)
{
for ($x=1; $x<=$pages; $x++)
{
echo ($x == $page) ? '<b>'.$x.'</b> ' : ''.$x.' ';
}
}
if (!($page >= $pages))
{
echo "<a href='buyproduct.php?page=$next'>Next</a> ";
}
?>
<?php
include ("include/footer.php");
?>
and my product_details.php is
<?php
include ("include/header.php");
?>
<?php
include ("database.php");
$productId = $_GET['productId'];
$sql = "SELECT * FROM product WHERE product_id = $productId";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo "<b>$row[product_name]</b><br>";
echo "<b>Brand : </b> $row[product_brand] <br>";
echo "<b>Description : </b> $row[description] <br>";;
echo "<b>Price : </b> $row[price] <br><br>";
"<br>";
}
?>
<?php
include ("include/footer.php");
?>
and when running in the browser when clicking to viw details in product_details.php the error is :
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\project2\product_details.php on line 17
Now what can I do....
In product_details.php the syntax of sql query is incorrect. Put $productId in quote.
The query sholu look like this..
$sql = "SELECT * FROM product WHERE product_id = '$productId'";
Hope this will help..
You have an error in your html...
<form action="product_details.php?productId=<?php echo $row['product_id'];? >>" method="post">
Should be...
<form action="product_details.php?productId=<?php echo $row['product_id'];?>" method="post">
Your sending an extra ">" with your product id

Fulltext Search engine, multiple columns, boolean mode

I am making a search engine for an android app that does fulltext search and match against multiple columns against '+word1 +word2' in boolean mode.
However, I can't get any search result.
E.g. search field type- "open sea"
then, Sql will search Match...Against ('+open +sea' IN BOOLEAN MODE)
and display list of selectable results, on which each result clicked, will provide details of the particular result on a new page.
Sorry, I am a newbie in android app development.
Here is my php code for search.php
<?php
# $db = new mysqli('localhost','username','password','db');
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database.
Please try again later.';
exit;
}
if(!empty($_POST)){
$term = $_POST['query'];
$words = explode(" ", trim($term));
$termArray = array();
foreach($words as $word){
if(!empty($word)){
$termArray[] = "+$word";
}
}
$searchquery = implode(" ", $termArray);
if (!$term) {
echo 'You have not entered any search details. Please go back and try again.';
exit;
}
//initial query
$query = "SELECT *
FROM servicetable
WHERE MATCH(title,cat,brand,company)
AGAINST ('".$searchquery."' IN BOOLEAN MODE)
ORDER BY title ASC";
$result = $db->$query;
$num_results = $result->num_rows;
//show user what user searched.
echo $searchquery;
echo "<p>Results found: ".$num_results."</p>";
//counts results.
if ($num_results == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
for ($i=0; $i <$num_results; $i++) {
$row = $result->fetch_assoc();
echo "<p><strong>".($i+1).". Outlet Name: ";
echo stripslashes($row['title']);
echo "</strong><br />Category: ";
echo stripslashes($row['cat']);
echo "<br />Opening Hours: ";
echo stripslashes($row['ophours']);
echo "<br />Brand: ";
echo stripslashes($row['brand']);
echo "</strong><br />Company: ";
echo stripslashes($row['company']);
echo "</p>";
}
$result->free();
$db->close();
} else {
?>
<h1>Search</h1>
<form name="form1" action="search.php" method="post">
Enter Search:<br />
<input type="text" name="query" id="query" placeholder="Search a service"/>
<br/>
<input type="submit" value="Search Now" name="completedsearch" />
</form>
<?php
}
?>
Hi I have found my error:
this line correction-->
$result = $db->query($query);

Categories