retrieving data from database with php and send to another page - php

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.

Related

PHP Paging with HTML variables

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'];
}

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.

Setting cookie in codeigniter with one name and several values

I want to set a cookie in Codeigniter whenever the user clicks on "add to my favorites". But I'm confused. Because I have to add several items with one name at the same time. You know this is not possible and the CI overrides the previous values. Look at this:
$this->input->set_cookie(array("name"=>'fav', 'value'=>2500, 'expire'=>100000));
$this->input->set_cookie(array("name"=>'fav', 'value'=>3500, 'expire'=>100000));
$this->input->set_cookie(array("name"=>'fav', 'value'=>4500, 'expire'=>100000));
And when I try to get fav value using this function:
printer($this->input->cookie("fav"));
I get this result:
4500
How should I set a cookie for user when they ad an item to their favorite list so that in the moment of retrieving them I know what to retrieve. I cannot use database because this implementation is for the users who are not registered members.
You can use $this->session->set_userdata for storing values.
$fav = $this->session->userdata("my_favs");// get existing list
$fav[] = $new_fav; // append new items to list
$this->session->set_userdata(array("my_favs"=>$fav)); // update session with existing one.
To print all items
$fav = $this->session->userdata("my_favs")
foreach($fav as $fitems)
echo $fitems."<br/>";
I think you should use print_r() instead of printer().
more than that, you should use:
$this->input->get_cookie("fav");
Have a look here for more information: Cookie helper

PHP Cart with Object Oriented PHP

I am developing a simple system of sample products with Object Oriented PHP, very simple thing. So far, no problem, but I have to create a button that adds a product code recorded in the database to a form in the sidebar. I do not know to develop a shopping cart with OO PHP, and codes that I find always give error because of the call of the database, or when the data list. I've been thinking of doing for JS, any help?
sorry my bad english
I got it, first I did when I click a link step by GET and the ID Code I need after seto it in a cookie, each cookie with an ID. Then I check if cookie has registered with the IDs. Not the best and most correct, but it works (more or less). Now another problem, I need to click two times to get the result as it passes by id and need to be caught refresh = /
I think it was a bit confusing but it is the maximum that dyslexia allows me to do hehehe
Here I set up the structure with the data I have in my product page:
add
<?php
$cod_get = $_GET['cod'];
setcookie("SITENAME_cod_".$id_get."", $cod_get, time()+3600, "/","", 0);
?>
And here I have a loop checking if cookie with ids, I think it will give problems, but for now I think it works ...
Thank you all.
$produto = new produtos();
$i = 0;
$produto->selecionaTudo($produto);
$produto->selecionaCampos($produto);
while($res = $produto->retornaDados()):
$res->id;
$i++;
$get_cookie = $_COOKIE['SITENAME_cod_'.$res->id.''];
if (isset($get_cookie)) {
echo $get_cookie.', ';
}else{
echo "";
}
endwhile;

Use dropdown list selection as mySQL query parameter

I had asked a similar question a few days ago but think I was trying to do to much at one time. I am hoping someone can help get me started on this.
I have two drop down lists, one will be populated with years (2012, 2011 etc) and I have some mySQL databases called "db_2012", "db_2011" etc. In these databases are tables representing months.
I would like the user to select a year and then use that selection to query the correct db and return a list of table names which will be used to populate the second drop down list. Then click a button "See Results" to query the selected table and show the results.
I am putting this on a wordpress website and am using a php template file that I created. This is still new to me and what I have so far doesnt work like I want it too, it is basically setup now that you select a year and select a month (not populated from db) and click a button. It makes the query and my table is displayed, but I need this solution to be more dynamic and work as described above. Thanks for the help.
echo '<form action="" method="post">';
echo'<select name="years" id="years">';
foreach($yearList as $year){
echo'<option value="'.$year.'">'.$year.'</option>';
}
echo'</select><br />';
echo '<select name="monthList" id="months">';
foreach($monthList as $month) {
echo'<option value="'.$month.'">'.$month.'</option>';
}
echo '</select>';
echo '<input type=\'submit\' value=\'See Results\'>';
echo '</form'>
$yearList and $monthList are just pre populated arrays. So now from here I want to click the See Results button and query my sql database using the parameters from the drop down selections.
$database = $_POST['yearList'];
$month = $_POST['monthList'];
$wpdbtest_otherdb = new wpdb('Username', 'Password', $database, 'localhost');
$qStr = "SELECT * FROM $month";
$myResults = $wpdbtest_otherdb->get_results($qStr, OBJECT);
It sounds like you want to send an AJAX call to a separate php page for security and processing, then have the PHP return XML that you parse back into the second selection box via the AJAX callback. It can be a little messy, but it allows you to check for weird form values that users might inject.
Edit: The PHP will receive your AJAX parameters as parts of the $_GET or the $_POST array. From there, you can do your checks and db call (or not), then add header("Content-Type:text/xml"); so the server sends it back with the correct header. After that you'll need to echo the XML-formatted data you want the JavaScript to receive. Just remember not to echo anything other than the XML if the request is supposed to go through.

Categories