php session id value to multiple pages - php

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>

Related

I have a button. When I press a button, one number reduces the number in the data base. I want it to be repeated every time

I have a button. When I press a button, one number reduces the number in the data base. I want when pressed each time it reduces the number by one
code html & php
<form method="post">
<div><?php
$username = "root";
$password = "";
$database = new PDO("mysql:host=localhost; dbname=testt;",$username,$password);
$ser = $database->prepare("SELECT * FROM test");
$ser->execute();
foreach ($ser AS $res){
echo '<h1>' . $res['NUMBER']; '</h1>';
}
?></div>
<input type="submit" name="click" value="click" id="click">
</form>
<?php
if (isset($_POST['click'])){
$username = "root";
$password = "";
$database = new PDO("mysql:host=localhost; dbname=testt;",$username,$password);
$tet = 12;
$update = $database->prepare("UPDATE test SET NUMBER=$tet-1 WHERE ID = 1");
$update->execute();
}
?>
Just use
SET NUMBER=NUMBER-1
to reduce the field by one from its current value. If you use $tet you will get 11 every time obviously because you hard coded it

Can't make MySQL queries in PHP webpage

So I'm working on a website where I need to pull data from a MySQL server and show it on a webpage. I wrote a simple PHP script to read data from the database depending upon an argument passed in the URL and it works just fine.
Here is the script:
<?php
function updator($item)
{
$servername = "localhost";
$username = "yaddvirus";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$table = "inventory";
//$item = "Rose Almonds";
$sql = "SELECT * FROM $table WHERE item = '$item'";
$result = $conn->query($sql);
while($data=$result->fetch_assoc()){
echo "<h1>{$data['item']}</h1><br>";
echo "<h1>{$data['item_desc']}</h1><br>";
echo "<h1>{$data['price125']}</h1><br>";
echo "<h1>{$data['price250']}</h1><br>";
}
//echo "0 results";
$conn->close();
}
if (defined('STDIN')) {
$item = $argv[1];
} else {
$item = $_GET['item'];
}
//$item = "Cherry";
updator($item);
?>
This script works exactly as expected. I call it using http://nutsnboltz.com/tester.php?item=itemname and it pulls and shows the data just fine.
P.S You can test it out by using Cherry or Blueberry as items.
The problem is, when I'm trying to put this data in my productpage.php file, I can't get the data to show up. Here's how the file hierarchy goes:
<php
*Exact same php script as above*
?>
<html>
<head>
Header and navbar come here
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-4">
<h1> RANDOM TEXT BEFORE </h1>
<?php
while($data=$result->fetch_assoc()){
echo "<h1>{$data['item']}</h1><br>";
echo "<h1>{$data['item_desc']}</h1><br>";
echo "<h1>{$data['price125']}</h1><br>";
echo "<h1>{$data['price250']}</h1><br>";
}
?>
</div>
<div class="col-8">
<H!> MORE RANDOM TEXT</h1>
</div>
</div>
</div>
</body>
<footer>
footer here
scripts etc
</footer>
</html>
So the script above the footer prints everything just fine. However, down where the HTML is, nothing is printed after the PHP code. It only shows my Navbar and the H1 tag saying "RANDOM TEXT BEFORE" and that's about it. My footer is gone along with everything else.
What exactly is the issue here and how do I fix this?
The problem seems to be that you're declaring $result inside the updator function, so it's not available when you're attempting to call it later.
The best thing to do might be to return $result from the function and assign that to a variable - something like this:
function updator($item)
{
// ... some code ...
$sql = "SELECT * FROM $table WHERE item = '$item'";
$result = $conn->query($sql);
// ... some more code ...
return $result;
}
<-- HTML CODE HERE -->
<?php
$item = !empty($_GET['item']) ? $_GET['item'] : false;
// yes I know it's a bit hacky to assign the variable
// within the 'if' condition...
if($item && $result = updator($item)) {
while($data=$result->fetch_assoc()){
echo "<h1>{$data['item']}</h1><br>";
echo "<h1>{$data['item_desc']}</h1><br>";
echo "<h1>{$data['price125']}</h1><br>";
echo "<h1>{$data['price250']}</h1><br>";
}
}
?>

Output database results over multiple pages

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!

Keeping a php variable that is retrieved via _GET when page reloads

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);

Give value to Database by Pressing button

So i ran into some trouble not to long ago. As a student i am relativly new to programming and thus i often visit sites like these for help. My question is how can i add value to database by pressing a button. For me the problem here is that the button has a javavscript function to print. So in other words i want the button to have 2 functions, one that prints the page (which i already have) and one that adds value to the database. The purpose to adding the value to database is so people can see that its already been printed before.
So essentialy what i am asking for is how can i give a button 2 functions (one which is Javascript) and show people that the button is used(in this case, that it has been printed). All help will be appreciated very much.
My code is as following:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$resultSet = $conn->query("SELECT * FROM orders");
// Count the returned rows
if($resultSet->num_rows != 0){
// Turn the results into an Array
while($rows = $resultSet->fetch_assoc())
{
$id = $rows['id'];
$naam = $rows['naam'];
$achternaam = $rows['achternaam'];
$email = $rows['email'];
$telefoon = $rows['telefoon'];
$bestelling = $rows['bestelling'];
echo "<p>Name: $naam $achternaam<br />Email: $email<br />Telefoon: $telefoon<br /> Bestelling: $bestelling<br /> <a href='delete.php?del=$id'>Delete</a> <input type='button' onclick='window.print()' value='Print Table' /> </p>";
}
// Display the results
}else{
echo "Geen bestellingen";
}
?>
This would aquire 2 tasks:
Is that you bind a function to the click handler of the button.
Although it is bad practice to use function calls directly, in your case this would be that you replace the window.print() by a custom javascript function.
In that javascript function, you execute the window.print() again, where-after you do the next step in the logic: sending data to PHP.
With ajax you can archieve this.
With a parameter in the function you can pass what the ID of the current row is, which need to be passed to PHP.
You need to create another PHP script, that will be called by tje AJAX script.
In that PHP script you will do the required updates to the database.
Ok There is a lot of ways you can do it but here is how i would do it :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$resultSet = $conn->query("SELECT * FROM orders");
// Count the returned rows
if($resultSet->num_rows != 0){
// Turn the results into an Array
while($rows = $resultSet->fetch_assoc())
{
$id = $rows['id'];
$naam = $rows['naam'];
$achternaam = $rows['achternaam'];
$email = $rows['email'];
$telefoon = $rows['telefoon'];
$bestelling = $rows['bestelling'];
//first you call a custom javascript function after the 'onclick'. I believe you'll have to pass a variable as an argument (like $id).
echo "<p>Name: $naam $achternaam<br />Email: $email<br />Telefoon: $telefoon<br /> Bestelling: $bestelling<br /> <a href='delete.php?del=$id'>Delete</a> <input type='button' onclick='print_table($id)' value='Print Table' /> </p>";
}
// Display the results
}else{
echo "Geen bestellingen";
}
?>
Then you write this function in the header of your page
<script>
function print_table(id)
{
//print your document
window.print();
//send your data
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","http://www.domaine.com/directories/printed_table.php?id=" + id;
xmlhttp.send();
}
</script>
Then you write your file printed_table.php where you store 1 if printed or 0 if not printed. I don't understand german so i don't know where you store your printed variable but it goes like this:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$id = $_GET['id'];
$resultSet = $conn->query("UPDATE `orders` SET `printed` = 1 WHERE `id` = `$id`");
?>
This should work. Just be careful and check the $_GET['id'] before to use it for security purposes. like you can use the php function is_int(). Depending of the security level you need you might want to secure this code a little more.

Categories