I have a page that is the result of a php query click (individual job list). I want to use an ORDER BY so the individuals can order their results based on either due date, job name, etc.
The problem seems to come into play when the user clicks on the variable table header. This causes a page refresh and the variable from the _GET is obviously then gone. I tried setting it as a cookie but I believe perhaps I am not setting this correctly.
This is in the top of the document:
<?php
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['assignee'] ) ){
$assignee = filter_input( INPUT_GET, 'assignee', FILTER_SANITIZE_STRING );
}
$assignee_name = $assignee;
setcookie($assignee_name, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
This is the PHP directly before the foreach loop:
<?php
$servername = "localhost";
$username = "jobs_usr1";
$password = "xxxxxxxxx";
$dbname = "jobs_users";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM `jobs_canjobs` WHERE assignee = \"$assignee\"";
$orderBy = array('job_numb', 'job_name', 'due_date', 'show_date', 'status');
$order = 'type';
if (isset($_GET['orderBy']) && in_array($_GET['orderBy'], $orderBy)) {
$order = $_GET['orderBy'];
}
if(isset($_COOKIE[$assignee_name])){
$sql = "SELECT * FROM `jobs_canjobs` WHERE assignee = \"$assignee_name\" ORDER BY $order";
}
$results = mysqli_query($conn, $sql);
?>
Then in the results table, under the table heads, I have this:
<table>
<tr style="background-color: cadetblue">
<th><b>Job ID#</b></th>
<th><b>Title</b></th>
<th><b>Due Date</b> | <b>Show Date</b></th>
<th><b>Status</b></th>
</tr>
<?php
foreach ($results as $result){
$job_numb = $result['job_numb'];
$assignee = $result['assignee'];
$job_name = $result['job_name'];
$due_date = $result['due_date'];
$show_date = $result['show_date'];
$status = $result['status'];
?>
<tr>
<td>
<p><?php echo $job_numb;?></p>
</td>
<td>
<p><?php echo $job_name;?></p>
</td>
<td>
<p><?php echo $due_date;?> | <?php echo $show_date;?></p>
</td>
<td>
<p><?php echo $status;?></p>
</td>
</tr>
<? php } ?>
</table>
Without the reordering $order, it works just fine - but once someone clicks on the th with the order by, the variable disappears, and I am not sure how to keep it even after a page reload.
Is there a way to keep this variable $assigneeon the page so I can reference it again to display the results? I know it is the page refresh because the url after clicking does not contain the variable.
Any help would be appreciated. Thank you.
The cool thing about PHP is you can just plonk it just about anywhere within HTML document
<th><a href="?orderBy=job_numb<?php if ( (isset($_GET['assignee'])) && (!empty($_GET['assignee'])) ){
echo '&assignee='.URL_ENCODE($_GET['assignee']);}?>"><b>Job ID#</b></a></th>
This first checks if that var is defined, and isn't defined as '' aka empty
then appending to your hard coded URL..
Putting that all on one line to ensure no line breaks are introduced to the URL.
So the resulting link will end with &assignee=$VAR where $VAR is the previously set $_GET['assignee']
PS while working on scripts I always add this to teh top so I can see errors without looking at log files
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
Related
I am trying to develop an e-commerce website where I will put some products.Customers can put products in "wishlist" they like, at the same time the button should be changed to 'collected' from 'collect' sooner they click on it . My code so far :
in dbconnect.php
function if_already_collected($collector_id){
$db_conn=getConnection();
mysqli_set_charset($db_conn,'utf8');
if(!$db_conn)return false;
$sql="SELECT collected_id from collection where collector_id=$collector_id";
$result=$db_conn->query($sql);
$db_conn->close();
return $result->num_rows > 0;
}
in member_profile.php
<?php
include_once("dbconnection.php");
if(!isset($_SESSION['logged_in'])){
header("Location: login.php");
die();
}
/*USER INFO : GETTING ID*/
$uname = $_SESSION['username'];
$pword = $_SESSION['password'];
$members = display_member_info($uname, $pword);
while($member = $members->fetch_assoc()) :
$collector_id=$member['id'];
endwhile ;
?>
<div class="member_card">
<div class="member">
<?php $mems=
serach_members($query_name,$query_elaka,$query_division,$query_district,$query_thana); ?>
<?php while ($mem= $mems->fetch_assoc()) : ?>
<?php if (if_already_collected($collector_id)) { ?>
<table>
<tr>
<td><a href="member_collect.php?get_id_cll=<?php echo $mem['id']; ?> &&
get_name_cll=<?php echo $mem['full_name']; ?>">Collect</a></td>
</tr>
<?php }else{ ?>
<tr>
<td>Collected</td>
</tr>
</table>
<?php } ?>
<?php endwhile; ?>
</div>
these code yields "collect" for all products even if i click on 'collect' (stored in database as well ) and yield 'collected' for all products even if i don't click on any when i replace the conditional statement by this :
<?php if (!if_already_collected($collector_id)) { ?>
The function needs to check whether $mem['id'] is in the user's collection. Currently it just checks whether the user has anything in their collection, not that specific item.
function if_already_collected($collector_id, $collected_id){
$db_conn=getConnection();
mysqli_set_charset($db_conn,'utf8');
if(!$db_conn)return false;
$sql="SELECT 1 from collection where collector_id = ? and collected_id = ?";
$stmt = $db_conn->prepare($sql);
$stmt->bind_param("ii", $collector_id, $collected_id);
$stmt->execute();
$stmt->bind_result($ignore);
$row = $stmt->fetch();
$db_conn->close();
return $row;
}
Then you would call it like this:
<?php if (if_already_collected($collector_id, $mem['id'])) { ?>
I've also shown how to convert the code to use a prepared statement instead of substituting variables, to protect against SQL injection.
Case
So once I learned PHP the non ObjectOriented way I decided to move to it.
While doing a simple query, I get the "rows" the query returns but trying to access its fields (columns) just seems not to work.
To be clearer, I have this PHP code, where I show the results into a table:
<?php
header("Content-Type: text/html;charset=utf-8");
include 'connectDB.php';
$connection = openConnection();
//Query
$query = "SELECT
field1,
field2
FROM table";
//Check there are results
if($result = $connection->query($query)) {
//get data
while($object = $result->fetch_object()) {
?>
<tr>
<td><?php $object->field1 ?></td>
<td><?php $object->field2 ?></td>
</tr>
<?php
}
closeConnection($connection);
} else {
echo '<tr><td>No info found.</td></tr>';
}
?>
Where openConnection() and closeConnection() are functions from the "connectDB.php" file. Those are ok, but in case it is relevant:
function openConnection() {
$dbhost = "localhost";
$dbuser = "user1";
$dbpass = "1234";
$db = "myDatabase";
$connection = new mysqli($dbhost, $dbuser, $dbpass,$db) or die(" Error while connecting: %s\n". $connection->error);
return $connection;
}
function closeConnection($connection) {
$connection -> close();
}
What I tried
I've already tried the following:
$object = mysqli_fetch_object($result)
$object = $result->fetch_result("newClass") // and created a new class
And down in selecting the fields:
$object->returnData() //where this is a function that literally does return $this->field1
Also checked a lot of PHP codes where it supposedly worked and was the same as the first code block mentioned above.
Result:
What I get as result is 9 rows, which is what the query should return, but trying to access with <?php $object->field1 ?> just leaves a blank space.
If I open the Web Inspector, there's actually nothing inside the <td>.
Extra: I'm using XAMPP on its lastest version 7.3.4 and Bootstrap 4.
Extra 2: the SQL query works separately.
Thanks in advance!
You're not echoing the value out. Try this:
<tr>
<td><?= $object->field1 ?></td>
<td><?= $object->field2 ?></td>
</tr>
How would I output the selected data from the database over a certain amount of pages.
For example I'd like 20 result per page and it automatically adds the extra pages needed (bit like google search pages but no search is needed as I am getting everything from the database).
Sorry for a bad explanation and also badly indented code, new to stackoverflow. I've tried putting just the php, rest of the page isn't complete or I removed the unnecessary code, feel free to improve as well.
At the moment I am just calling all the data onto one page using very simple
code
<?php
session_start();
if(isset($_POST['logout'])) {
unset($_SESSION['Username']);
session_destroy();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Backend</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="" style="min-width: 1024px; max-width: 1920px; margin: 0 auto; min-height: 1280px; max-height: 1080px;">
<?php
if (isset ($_SESSION['Username']))
{
?>
<button onclick="location.href = 'logout.php';">Logout</button>
<?php
if (isset ($_SESSION['Username']))
{
echo "";
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "request";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM request";
$result = $conn->query($sql);
$sql = "SELECT * FROM request ORDER BY id DESC";
$result = $conn->query($sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
if (isset ($_SESSION['Username']))
{
?>
<div align="center">
<div class="requests">
<p><?php echo $row["Name"]; ?></p>
<p><?php echo $row["Number"]; ?></p>
<p><?php echo $row["Song"]; ?></p>
</div>
</div>
<?php
}else{
header("Location: index.php");
}
}
} else {
echo "0 requests";
}
}
mysqli_close($conn);
?>
Let's see an example of pagination in PHP. Before that, we need to understand what pagination is. Result pagination is quite simple.
We do a search on a certain DataBase table, and with the result of the search, we divide the number of records by a specific number to display per page.
Related: Data pagination in PHP and MVC
For example a total of 200 records, and we want to display 20 per page, we will soon have 200/20 = 10 pages. Simple, right? Well let's go to the code then.
First connect to MySQL:
<?php
$conn = mysql_connect("host","user","pass");
$db = mysql_select_db("database");
?>
Now let's create the SQL clause that should be executed:
<?php
$query = "SELECT * FROM TableName";
?>
Let's get to work ... Specify the total number of records to show per page:
<?php
$total_reg = "10"; // number of records per page
?>
If the page is not specified the variable "page" will take a value of 1, this will avoid displaying the start page 0:
<?php
$page=$_GET['page'];
if (!$page) {
$pc = "1";
} else {
$pc = $page;
}
?>
Let's determine the initial value of the limited searches:
<?php
$begin = $pc - 1;
$begin = $begin * $total_reg;
?>
Let's select the data and display the pagination:
<?php
$limit = mysql_query("$query LIMIT $begin,$total_reg");
$all = mysql_query("$query");
$tr = mysql_num_rows($all); // checks the total number of records
$tp = $tr / $total_reg; // checks the total number of pages
// let's create visualization
while ($dados = mysql_fetch_array($limit)) {
$name = $data["name"];
echo "Name: $name<br>";
}
// now let's create the "Previous and next"
$previous = $pc -1;
$next = $pc +1;
if ($pc>1) {
echo " <a href='?page=$previous'><- Previous</a> ";
}
echo "|";
if ($pc<$tp) {
echo " <a href='?page=$next'>Next -></a>";
}
?>
Ready, your pagination in PHP is created!
Hello i am seen lot of question like Session doesn't working first time. But couldn't see any good explanation on this question and why doesn't working first time also what is happening during sessioning. Mine is also like others first time doesn't working after that works fine.
this is php which is sessioning.
session_start();
$PersonName=$_GET['PersonName'];
$SurName=$_GET['SurName'];
$TestXML=$_GET['TestXML'];
$TestDate=$_GET['TestDate'];
$TestPkID='0000000000000000000000000000';
include('DBConnect.php');
$proc = "{call p_set_Test(?,?,?,?,?,?,?,?,?)}";
$params = array(array($TestDate,SQLSRV_PARAM_IN),
array(0,SQLSRV_PARAM_IN),
array($PersonName,SQLSRV_PARAM_IN),
array($SurName,SQLSRV_PARAM_IN),
array($TestXML,SQLSRV_PARAM_IN),
array('',SQLSRV_PARAM_IN),
array(101,SQLSRV_PARAM_IN),
array(10,SQLSRV_PARAM_IN),
array($TestPkID, SQLSRV_PARAM_OUT)
);
$result = sqlsrv_query( $conn, $proc, $params);
if( $result === false )
{
echo "Error in executing statement 3.\n";
die( print_r( sqlsrv_errors(), true));
$message2 = "aldaatai";
echo "<script type='text/javascript'>alert('$message2 ' + $TestPkID);</script>";
}
$_SESSION['idpktestsession'] = $_POST["idpktest"] = $TestPkID;
$_SESSION['persontestname'] =$_POST['persontrollname'] = $PersonName;
$_SESSION['persontestlastname'] =$_POST['persontrolllastname'] = $SurName;
this is getting value from sessioned values
<?php include('DBConnect.php');
session_start();
$diskuserid = $_SESSION['idpktestsession'];
$diskusername = $_SESSION['persontestname'];
$diskuserlastname = $_SESSION['persontestlastname'];
$diskuserlastname = mb_substr($diskuserlastname, 0, 1);
?>
<?php
$proc = "{call p_rpt_Pattern(?,?)}";
$params = array($diskuserid,'M');
$procarr = array();
$result = sqlsrv_query( $conn, $proc, $params);
while ($row = sqlsrv_fetch_array($result))
{?>
<tr>
<td><?php echo $row['PatternCode']?></td>
<td><i class="fa fa-chevron-right rightarrow" > </i></td>
<td><?php echo $row['PatternDesc']?></td>
</tr>
<?php
}
?>
This statement was written incorrect:
$_SESSION['idpktestsession'] = $_POST['idpktest'] = $TestPkID;
If you want to assign the value you can rewrite above statement like this
$_SESSION['idpktestsession'] = $_POST['idpktest'];
and if you want to concatenate two values you can rewrite like this
$_SESSION['idpktestsession'] = $_POST['idpktest'] . ','. $TestPkID;
As long this is question wasn't answered i found why it don't work first time.
Everytime it sending session to another php with value ,its sending with value after page load so if you some how face this error just assign value before page load or put middle loading php insteand of showing direct.
I'm trying to pass the value of a session id to a different page, but only the last product id is passed to the second page no matter if a product with a different id is selected. Ideally what ever product is clicked that id should pass to the second page
<body>
<?php
session_start();
$_SESSION['favcolor'] = 'green';
?>
<!--Some other html code -->
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql2 = "SELECT * FROM tablename WHERE 1 ORDER BY ProductName ASC";
$myresult = $conn->query($sql2);
$x = 1;
while ($row = $myresult->fetch_assoc()) {
$_SESSION['id'] = $row['ProductID'];
?>
<div class="col-sm-4">
<div class="product-image-wrapper">
<div class="single-products">
<div class="productinfo text-center">
<img src="../../images/myImages/<?php echo $row['ProductImage1'];?>_0001_1.jpg" alt="../../images/myImages/<?php echo $row['ProductImage1'];?>_0001_1.jpg" />
<h2><?php echo $row['ProductPrice'];?></h2>
<!-- when i echo $_SESSION['id'] i get correct values for each product -->
<p><?php echo $_SESSION['id'];?></p>
<p><?php echo $row['ProductName']; ?></p>
<!-- Other HTML Code -->
Second Page after clicking a product and expecting the correct product id to be passed.
<body>
<?php
session_start();
echo $_SESSION['favcolor'];
echo $_SESSION['id'];
?>
This results in the last Product ID being passed to the second page no matter what product is clicked
When you print the Id's of the products you're retrieving from the table and iterate them in the while loop so they're gonna be right. To set the id product in the session when this is clicked you must either set the value in the second page or set it with an AJAX Request, in this case is necessary use Javascript.
Well because in while loop you override the value each time so at the end you only get last record.
Change your code at two places.
1. Make array of ids
$x = 1;
$idArray = array(); //define array
while ($row = $myresult->fetch_assoc()) {
$idArray[] = $row['ProductID']; //push values in array
//other code..
} // end while
$_SESSION['id'] = $idArray; //store to session
2. Use data from db not session
Replace this
<p><?php echo $_SESSION['id'];?></p>
With this
<p><?php echo $row['ProductID'];?></p>