PHP Paging with HTML variables - php

I have been going through pagination tutorials for past 1 week. I have an html page wherein user enter values into the textfields and click submit button. The page then redirects to a php page which displays corresponding output from the sql database. The database makes use of variables which were received by the php script from the HTML page. I am trying to paginate the final table displayed on the php page but have been unable to do so. Relevant Code for the same is:
Search.html
ClOrdID
Symbol
**index.php**
<?php $clordid = $_POST['clordid'];?>
<?php $orderid = $_POST['orderid'];?>
//connected to database using mysqli
$result = mysqli_query($con,"SELECT * FROM abc where clordid like '$clordid' and orderid like '$orderid'
while ($row = $result->fetch_array(MYSQLI_BOTH)) {
echo "<tr>";
for($k=0;$k<150;$k++){
echo "<td>" .$row[$k]. "</td>";}
This code works fine. When I run this query again to calculate total number of rows and also total number of page links to be displayed in pagination, that works as well. However, whenever I click next page using pagination, the code forgets the value of variables imported earlier from html page. I tried to pass it using the url but has been unsuccessful. I believe somehow the values from html page must be retained by the program at all times to make query execute successfully at all times. Can anyone provide me some basic example (or a url) that could help me understand the process? Thanks

You can assign the variable to the session like so:
session_start();
if ($_GET['page_number'] == 1){
$_SESSION['clordid'] = $_POST['clordid'];
}

Related

Creating fusioncharts from database with variable where-condition

I'm creating FusionCharts with data from my database. It works if I set a static where-condition with a variable set in the code ($kommunenr = '3001';). But I would like the user of the website to choose which data the chart is based on, by inserting a number in a form field, i.e. 3018. So the value of the variable should come from the user's choice. But when I test the variable seems empty.
My code is based on these tutorials:
https://www.fusioncharts.com/dev/using-with-server-side-languages/tutorials/php-mysql-charts
https://www.youtube.com/watch?v=nqavhILvBVU
https://a1websitepro.com/jquery-ajax-form-submit-with-php-processing/2/
I have the following files:
valginfo.php (the main page)
skjema.js (get the data (the number) from the form on the main page)
chart_sample.php (lists the data from the database)
app.js (creates the chart)
I have tried to find the error by both posting the content from chart_sample.php in a div on the mainpage, and in an iframe. And of course googling.
My query in my chart-data.php (choosing the data to use in making the chart):
$query = "SELECT * FROM valg19_kommune WHERE kommunenr = $kommunenr AND kandidatnr = 1 ORDER BY kommunenr, sortering, kandidatnr LIMIT 500";
It works if the variable is static, set like this:
$kommunenr = '3001';
But when I set the variable like this, it looks empty:
$nr=$_POST['nr1'];
$kommunenr=$nr;
I expect the posted number to be stored as the value of the variable and beeing part of the query, but it is not. When I echo the query and the result from chart_sample.php into a div on the main page, I looks perfect:
SELECT * FROM valg19_kommune WHERE kommunenr = 3018 AND kandidatnr = 1 ORDER BY kommunenr, sortering, kandidatnr LIMIT 500
[{"label":"Fremskrittspartiet","value":"42","color":"#000099","tooltext":"Elisabeth Stene"},{"label":"H\u00f8yre","value":"64","color":"#3366ff","tooltext":"Benedicte Dyvik"},{"label":"Kristelig Folkeparti","value":"56","color":"#ffff00","tooltext":"Brynjar H\u00f8idebraaten"},{"label":"Senterpartiet","value":"45","color":"#00cc00","tooltext":"Reidar Kaabbel"},{"label":"Arbeiderpartiet","value":"44","color":"#ff3300","tooltext":"Kai Guttulsr\u00f8d"},{"label":"SV - Sosialistisk Venstreparti","value":"39","color":"#ff4d4d","tooltext":"Tore Andersen"},{"label":"R\u00f8dt","value":"37","color":"#cc0000","tooltext":"Martin Werner Olsen"}]
But in my iFrame this is displayed:
SELECT * FROM valg19_kommune WHERE kommunenr = AND kandidatnr = 1 ORDER BY kommunenr, sortering, kandidatnr LIMIT 500[]
The iframe content is not updated when I submit the number.
How can I make sure the chart is made based on the number entered by the user?
Before I enter a number in the form field
After I entered the number
If I set the variable as this $kommunenr = '3001'; and remove the echo og the query.
Now I feel really stupid! I should use sessions and globals!
Start each page with session_start(); and first set and then use the global variables:
$_SESSION["kommunenr"] = $kommunenr;
$kommunenr = $_SESSION["kommunenr"];

Can I write all my SQL queries to phpMyAdmin / HTML-file or do I need to use other programmes?

I have a database in phpMyAdmin that I have set up with XAMPP. I am working on a website that shows statistics from the user inputted scores in the database. Say that I would like to show the score percentile to the user after they submit their score: where do I write the query for that? In the HTML/PHP code? In phpMyAdmin? Somewhere else like a workbench or PopSQL?
I have successfully gotten the website to display the average score in any given table by writing this code to the HTML file:
<?php
$sql = "SELECT AVG(score) AS score FROM $input_subject";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_object($result) ;
echo nl2br("Average score for $input_subject: \n \n"
. round($row->score));
?>
It works, but when I search for tutorials for example for the percentile query or something like the CHECK function (to not accept anything less than 0 or more than 120) it seems that the queries are always written somewhere else than the HTML file.
Also, when I try to write the SQL code in phpMyAdmin, it always shows a bunch of error messages, even though I copy/pasted it in (changing the table names etc., of course).
So, do I need to look into some other programmes were to write the queries in or can I just write them into the HTML-file or in the phpMyAdmin? I'm a total newbie with this so anything helps!
Yes, you can write SQl queries(PHP) before your html code and also in between your html code, but make sure to change file extension to .php from .html otherwise PHP code will be printed on browser as it is.
"it seems that the queries are always written somewhere else than the HTML file."
we do this while using AJAX. we send data to server (a PHP file where we process data received) and server will give response. All this happens behind the scenes without page reloading.
in your case you can create a new PHP file lets say process.php, add your PHP code into it.
process.php
<?php
$sql = "SELECT AVG(score) AS score FROM $input_subject";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_object($result) ;
echo nl2br("Average score for $input_subject: \n \n"
. round($row->score));
?>
send user inputted scores from HTML file through ajax to PHP file (process.php) and response received from that file can be displayed in html file without page reloading.
you can go through the ajax api by following link jQuery-AJAX

retrieving data from database with php and send to another page

I am now trying to create a page which shows restaurants in a list for people to comment and rate, the restaurant info is in the database. I've already get the data I want using while() function, but I am struggling to pick one of them and pass to another page. Below is my code. I tried to use sessions to store the data, like the "$_SESSION['rid']" for storing the restaurant ids. I have 8 rows in the restaurant table, and when I click on the first restaurant, the number shows on the other page is 8.
<?php
$sql_restaurant = "select * from tbl_restaurants";
$results = mysql_query($sql_restaurant);
while($restaurant_row=mysql_fetch_assoc($results)){
$_SESSION['rid'] = $restaurant_row['restaurant_id'];
echo "<a><span style = 'color:black'>".$restaurant_row['restaurant_name']."</span></a>";
echo "<dd>";
echo "<a><span style = 'color:black'>".$restaurant_row['restaurant_address']."</span></a>";echo '</dd>';
echo '<i class="mod_subcate_line"></i>';
echo 'Rate it!';
echo 'Comment!';
echo '<br/>';
echo '<br/>';
}
?>
I want it to show the right restaurant id when I click on different restaurants. How can I solve this?
Right now your code is changing $_SESSION['rid'] every time you cycle through the loop. So it will have the last cycle of the loop.
You shouldn't do this with sessions, always keep in mind that HTTP is a stateless system and sessions are stateful. It's always better to not rely on state.
As mentioned in the comments, you should write the restaurant ID as part of the URL of the link in a query parameter that you can then access through the $_GET array.
If you want to use $_SESSION, choose a different name for every loop. Here, $_SESSION['rid'] get the value of the last loop.

How to put MySQL table into session variable and using the table on next page?

I have two PHP pages. On page1 a temporary table is created and filled with data from a mysql database. I am trying to store this table into a $_SESSION variable so that I can put the table onto page2.
Right now this has been my approach:
This is (part) of the code on page1:
ob_start();
session_start();
//Select data from temporary table
$result = mysqli_query($mysqli,"SELECT * FROM table");
//store table into session variable
$_SESSION['fase1result'] = $result;
This is the code on page2:
ob_start();
session_start();
$table = $_SESSION['fase1result'];
echo "<table border='1'>
<tr>
<th>ProductID</th>
<th>ProductName</th>
<th>Fase1</th>
</tr>";
while($row = mysqli_fetch_array($table))
{
echo "<tr>";
echo "<td>" . $row['ProductID'] . "</td>";
echo "<td>" . $row['ProductName'] . "</td>";
echo "<td>" . $row['Fase1'] . "</td>";
echo "</tr>";
}
echo "</table>";
Unfortunately, up until now these scripts return me an error on page2. At this moment, the echoing of the table on page2 is just to test and verify that the table is actually passed on. At a later moment I want to be able to use MySQL queries to further add data to the table. Hope you could help me.
UPDATE:
Error that I'm getting is:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in domain/page2.php on line 32
With line 32 in page2 being:
while($row = mysqli_fetch_array($table))
To better explain my question, I have posted another question which can be found here:
Modifying MySQL table on different pages with scores from a HTML form
On page1 a temporary table is created and filled with data from a mysql database. I am trying to store this table into a $_SESSION variable so that I can put the table onto page2.
That's impossible.
And shouldn't be used anyway.
something wrong with your design. Most likely such a table is superfluous and you don't actually need it at all.
As of the real problem behind this one - better ask another question, explaining the real life task for which you decided to use a temporary table passed between pages.
Responding to your question one by one:
Error you are Getting
The error that you are getting normally is the result of incorrect spelling or reference of table name, field name or any other variable in the MySQL query. In your case, it may be due to incorrect calling/storing your Session Variable. For example,
//Instead of "table", you typed "tabel". This is just an example.
$result = mysqli_query($mysqli,"SELECT * FROM table");
Share your code so that I can try picking up this error. Above is just an example.
Storing values in Session Variable is not Recommended
Suppose your user fills in the form and moves on to the next phase. The data from the first phase is transferred to the second phase via Session Variable. What if the user simply closes the tab and restarts the process? Session Variable will still be set and the previous data may interfere with the new one and can produce unexpected results.
Ideal Solution
It is better to store the values in JavaScript Array and then transfer to the next page by Hidden Input field. Some of the benefits of using this logic are:
Fast Performance
More Secure
Easily Manageable
Reference Code
If you are taking the values from HTML Forms, then it is very simple to have the value in POST. Using the JQuery UI selection, you can add the selected values in a JavaScript Array.
//Declare Global JavaScript Variable on Page Load. This will be at the end of <head>
$(document).ready(function() {
window.fase1result = [];
} );
After this, on each click event where you want to add the data to be taken to the next page, use the following code to add the value to this array.
fase1result.splice(indexOf_to_add, 1, "SelectedValue");
To understand .splice better, click here.
One selection, e.g. clicking on a Div or link, add the value to a fase1result and on submit add the array value to Input Hidden by using the following:
Add a Javascript Function on form's onsubmit.
<form id="myForm" method="POST" action="fase2.php" onsubmit="return fase1Values()">
Add <input type="hideen" name="fase1values_input" id="fase1values_id"> in the form.
Below is the JavaScript onsubmit function just before </body>.
function fase1Values() {
$( '#fase1values_id' ).val( JSON.stringify(fase1result) );
}
Note that JSON.stringify is required in order to set the Array as an input value.
$decode_fase1result = json_decode( $_POST['fase1values_input'] );
Now you have transferred the fase 1 selection data using an Array from Page 1 to Page 2 without storing data in any temporary table.
Hope this answers your question and solves your problem as well.

post-redirect-GET, GET? How?

Since I asked my question (Previous question) in a way no doubt most users think "dude this is tl;dr" let me put it more simple. I want to use post-redirect-get pattern to avoid user refreshing the site and resubmiting the data etc... I understand that in order to do so I have to redirect the user from html form, through php processing script and back to a new site (or original html form site) that displays the processed data.
Now my question. How do I GET my processed data back from my php? I don't understand the GET part... Currently I don't know how to show php generated data in a nice html display (view) page without include 'site.html';. This example isn't what I am looking for either: Simple Post-Redirect-Get code example. Code in the below example just redirects me to a current page.
It depends on context, but for example:
Given: invoice-form.html, invoice-processing.php and current-invoices.php:
User fills in data on invoice-form
User submits form which has action="invoice-processing.php"
Browser POSTs data to invoice-processing
invoice-processing takes the data from the form and puts it in a database
invoice-processing outputs 302 status and a Location header
Browser goes to current-invoices
current-invoices fetches a list of invoices (including the most recently submitted one) from the database and sends them to the browser as an HTML document
I hope this will help because it has taken me quite a while to get it as well. I tested my understanding like this. I have two php pages, the first page (prg1.php) sends the form to the database, action set to the second one (prg2.php). prg2.php checks the POST data, updates the database and issues a redirect to prg1.php with anything I need to pass back as GET variables. prg2.php looks like this
<?php
if (isset($_POST['gameid'])){
// process the data, update the database
$gameid = htmlspecialchars($_POST['gameid']);
$playerid = htmlspecialchars($_POST['playerid']);
$message = htmlspecialchars($_POST['message']);
//redirect, after updating the database
$getinfo = '?gameid=' . $gameid . '&playerid=' . $playerid;
header("Location: prg1.php" . $getinfo );
exit();
}
?>
You could try something like this:
/****************************************/
/* Fetch my data. */
/****************************************/
$mydata = $_GET["data"];
/****************************************/
/* Has to be sent before anything else! */
/****************************************/
header( 'Location: http://www.yoursite.com/index.php?data='.$mydata );

Categories