PHP refreshes the page before executing the query - php

I'm creating a webpage that loads a random product from one table (the "Products" table) from my database every time the page reloads. The logged in user (the user must be logged in) can choose to add that product to their personal favorites or not (stored in the "Favorites" table). Every time the user clicks the corresponding button to add that product to their favorites the webpage reloads and shows another new random item. The problem is that the webpage probably reloads before the query is executed, so the 'new' item is added to their favorites instead. Does anyone know how I can solve this? This is what I got so far:
HTML
<form method="get">
<button type="submit" name="like">
<img class="add-to-favorites" src="image.png">
</button>
</form>
PHP
header("Cache-Control: no-cache, must-revalidate");
session_start();
include_once 'dbconnect.php';
$user_id = ($_SESSION['user']);
$sSQLQuery = "SELECT product_id FROM Products ORDER BY RAND()";
$aResult = mysql_query($sSQLQuery);
$aRow = mysql_fetch_array($aResult, MYSQL_ASSOC);
$productid = $aRow['product_id'];
if(isset($_GET['like'])){
$SQL = "INSERT INTO Favorites(user_id,product_id)
VALUES('$user_id','$aRow[product_id]')";
$result = mysql_query($SQL);
}

Well, actually your PHP code only gets a random item and then saves it if the user clicked like. You should output the product ID on the form like this:
<form method="get">
<input type="hidden" name="current_product_id" value="<?php echo $productid; ?>">
<button type="submit" name="like">
<img class="add-to-favorites" src="image.png">
</button>
</form>
Where <?php echo $productid; ?> has the ID of the new random product.
Your PHP should go in this order and with these values:
if(isset($_GET['like'])){
$SQL = "INSERT INTO Favorites (user_id,product_id) VALUES ('$user_id','$_GET[current_product_id]')";
$result = mysql_query($SQL);
}
$sSQLQuery = "SELECT product_id FROM Products ORDER BY RAND()";
$aResult = mysql_query($sSQLQuery);
$aRow = mysql_fetch_array($aResult, MYSQL_ASSOC);
$productid = $aRow['product_id'];
So now, if you click on like, the $_GET['current_product_id'] will have the current product and then I output the new random product ID in the hidden input so that the next item works too!
Also: important, consider using mysqli_* functions instead of mysql_* functions because these last ones are deprecated :)

Your problem is that when the page refreshed, you first get new data from the Database and then save the old data - which is replaced by the new data.
Obviously you need to transfer the old product-id in the GET-Parameters. There are many options to do this, for example creating a hidden field.
echo "<input type=\"hidden\" name=\"oldProductId\" value=\"$productid\">
You can then access it when the page reloads with
$_GET['oldProductId']
and write it to the favorites-table.

Firstly, PDO... Always :P.
But to answer your question, you need to send the product_id along with $_GET['like'], so you know which product they selected. Since you're randomly selecting one from the database on every load.
In its current state, that is your best option.
But please consider moving to PDO especially since you mention logged in users and products.
How can I prevent SQL injection in PHP?
*Link credits to Sean (comment)

Related

php script not working in Internet explorer and Firefox

I have a button on a webpage that allows users to add a video on that page to their list of favourites. behind this button is a form and some php. The PHP code uses a session variable to retrieve the username. This information is used to get the relevant user id from the database and store its value in a variable. Using the input value from the form it was possible to retrieve the tuple from the videos database table that related to the video in question and store the values of the video title and URL attributes in variables. The code then checks if the user has already added the video as a “favourite”. The favourites database entity is checked for tuples containing both the user id and video id. If both are contained in a single row of the database table the user has already added the video and is notified of this. Otherwise, the user id, video id, video title and URL are inserted into the favourites database entity and the user is informed that the video has been added
this all works fine in chrome or safari but does nothing in ie or firefox. The database is updated and message is displayed only in Chrome and safari. I've attached the code, please note the session has already been started in earlier code on the webpage. Any assistance would be greatly appreciated.
<div id="addfav">
<form action="python.php" method="post">
<input name="add" src="images/add.png" type="image"
value="3">
</form>
<?php
$user=$_SESSION['user'];
if ( isset( $_POST['add'] ) )
{
$vid = $_POST["add"];
$sql = "SELECT * FROM `users` WHERE username = '$user'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);
$uid= $row['user_id'];
$sql = "SELECT * FROM `Video` WHERE Video_id = '$vid'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);
$url=$row['URL'];
$title=$row['Title'];
$check = mysql_query("SELECT * FROM `favourites` WHERE Uid = '$uid' AND vid_id = '$vid'") or die (mysql_error());
$r = mysql_num_rows($check);
if ($r>=1)
{
echo "already added to favourites";
echo '<script type="text/javascript">window.alert("Already added to favourites")</script>';
//'<span style="color: red;" />Already added to favourites </span>' ;
}
else
{
mysql_query("INSERT INTO `favourites` (`Uid`,
`vid_id`,`url`,`title`) VALUES ('$uid',
'$vid','$url','$title')")or die(mysql_error());
echo "Added to favourites";
}
}
?>
</div>
(Just a debug idea) Try to change your input image to a hidden element like this :
<form action="python.php" method="post">
<!-- I don't remove this, to keep the image shown-->
<input name="addimg" src="images/add.png" type="image" value="3">
<input type='hidden' name='add' value='3' />
</form>
Does it works now?
PHP is run server-side. This means that regardless of what browser you're using, it works as expected. The problem is definitely from HTML codes you've written if IE and Firefox can connect to your website without any problem.
I think the problem is inside your form tag because I think it's not standard you can either use a GET method inform that your form is submitted, or use a hidden input indicating it.
P.S. I think your code has security issues. (SQL Injection)
When user clicks on <input type="image" /> browser will pass coordinates of a click. Chrome will send three values:
add.x = x_coord
add.y = y_coord
add = input_value (3 in your case)
Note that in php you can access add.x/add.y value with $_POST["add_x"]/$_POST["add_y"] (see dot replaced with underscore)
At the same time, IE will not pass third value. That is why your if ( isset( $_POST['add'] ) ) will never return true. Option is to put video id value into some hidden field and use its name in that if.
You can easily check that behavior by doing var_dump($_POST); in php
PS:
You should never use values received in request without them being sanitized in sql queries. Right now code below is opened to sql injections:
$sql = "SELECT * FROM `Video` WHERE Video_id = '$vid'";
You should, at least, user mysql_real_escape_string function before value is inserted into a query:
$sql = "SELECT * FROM `Video` WHERE Video_id = '".mysql_real_escape_string($vid)."'";
And take a look at warning message on top of php manual page linked above: mysql_* functions are deprecated and you should better use PDO or mysqli extension.

php select to get a variable and then apply if else on it

I have a car rental system I am working on. When a user rents a car, the system should first check if the number of available cars is greater than 0, if yes, then make the adjustment "AVAILABLE = AVAILABLE+1" (in the MySQL table which keeps track of cars), which means, rent the car to the user. Also, I am trying to record which car went to which user. So I have another database table called rentalrecords which takes in the values of the Username of the logged in user, and ID of the car rented. Now, the problem is, my 'IF-ELSE' part is not executing as desired.
<div id="stylized" class="myform">
<form id="form" name="form" method="POST" action="renting.php" >
<h1>Rent a Car</h1>
<label>Car ID
<span class="small">eg. Enter 1 for Mer1</span>
</label>
<input type="text" name="ID" id="ID" />
<input type="submit" style="margin:30px 100px;" name="submit" value="Check-Out">
<div class="spacer"></div>
</form>
</div>
Now,the action of this form, which is renting.php, is as follows:
<?php
session_start();
if(!session_is_registered(theUSERNAME)){
header("location:customer_login.php");
}
mysql_CONNECT("xx", "xx", "xx") OR DIE("Unable to connect");
mysql_SELECT_DB("xx") OR DIE("Unable to select database");
$ID = $_POST['ID'];
$result = mysql_query("SELECT AVAILABLE FROM car WHERE ID='$ID'");
if(mysql_fetch_array($result)>0)
{
$query="UPDATE car SET AVAILABLE=AVAILABLE-1 WHERE ID='$ID'";
mysql_query($query);
$query = "insert into rentalrecords (USERNAME,ID,RENTED_ON) values ('$_SESSION[theUSERNAME]','$_POST[ID]',CURDATE())";
$result = mysql_query($query);
header("location: list_Clogged.php");
}
else
{
echo "<script>alert('The car you chose is currently unavailable!'); location.href='rent.php';</script>";
}
?>
Even though I have available=0, it still is NOT executing the else part and no matter what, it always executes the IF part. The ID and AVAILABLE are the attributes of my MySQL table called 'car' and the in rental records table i just want to insert these values. I am aware that the script is vulnerable to injection at the moment, but first I want to get things working! Any immediate help would be much appreciated.
You're trying to count a resource...
if(mysql_fetch_array($result)>0)
You need to obtain the results and then count an item within those results:
$res = mysql_fetch_assoc($result);
if($res[0]['AVAILABLE'] > 0)
Note $res[0] means first row of the results. You can also use mysql_fetch_row to obtain a single result.
Keep in mind, mysql_ functions shouldn't be used at all. Look into switching to mysqli or PDO.
Also, you need to sanitize input. You're just blindly accepting $_POST['ID']
The mysql_fetch_array function doesn't do what you think it does; it returns an array, not a single value.

can't pass a correct value in betwen PHP pages

if my question appears to be silly but I ran out of explanations.
I'm trying to set up a page with some news on it. I have the database with such attributes like News_id, news_header, news body etc.
I have 2 pages first page gives a list of the brief descriptions of the news with the button which allows user to read some more of a particular news on it. If clicked it passes a corresponding news_id value to the page 2 which fetches News_Id Value, queries corresponding values from database value and outputs the content.
The problem is that no mater which button in the list of page 1 I click to see news, the page 2 always receives the news_id value of the news which is *first in the lin*e. here are the codes
PAGE ONE (the list)
<form name='NewsLineSelection' method='post' action='news.php'>
<?php
$News_Query = "Select * from news order by Date_Posted Desc;";
$GetNews = mysql_query( $News_Query, $IVE_Connection ) or die("ERROR: ".mysql_error());
while ( $News_Database = mysql_fetch_array( $GetNews ) ){
?>
<tr><td ><?php echo $News_Database[1]; ?></td>//header
<tr><td ><?php echo $News_Database[2]; ?></td>//news body
...etc
<tr><td class="maintext">
<input type='hidden' name='NewsToRead' value='<?php echo $News_Database[0]; ?>'>//News_ID is here
<input type='submit' name='AddNews' value='Read More...' >
</td></tr>
}//end of the loop
Page 2 (with info details)
$News_id = addslashes($_POST['NewsToRead']);
$News_Query = "Select * from news where news_id = ".$News_id.";";
$GetNews = mysql_query( $News_Query, $Connection ) or die("ERROR: ".mysql_error());
$News_Database = mysql_fetch_row( $GetNews );
//Then output the query's content
It looks perfect on paper. But I really can't understand why if there are 10 news in the list of page 1 for instance, no matter which button I click the value of $News_id in PAGE 2 will be always the id of the first news in the list on the page 1.
May be I don't see something. it suppose to work ok, but it doesn't.
Thanks for any kind of help or suggestions.
That's because you're having multiple inputs with the same name. You're looking at the problem wrong.
You're fetching (getting) data, you should be using a GET request, and not a POST request.
My recommendation, that each News headline would be wrapped in a link like so:
<h1>
<a href="news.php?id=<?php //Code to output the correct ID here ?>"><?php //Code to output the correct headline here ?>
</a>
</h1>
A few things extra
Don't use tables for laying out your page! Tables are meant for table data. Use correct semantic elements: (<h1> for important headlines, <h2> for less important headlines, <p> for paragraphs, and so on).
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

What is the right way to update mysql database using data coming from a dynamically generated list of textboxes?

I have a set of dynamically generated textboxes that holds the number of a certain product the user wants (quantity). I am trying to incorporate functionality that allows the user to change the number in the textbox to reflect the right number using php/mysql. I have the code below that pulls the current quantity the user enters from the previous page, but I’m not sure how to incorporate the changes in quantity from the current page. I’m assuming I will have to use UPDATE but I don’t know how to include it only for a certain product (or row).
#$link = $_GET['link'];
$price = $_GET['price'];
$title = $_GET['title'];
$retailer = $_GET['retailer'];
$options = $_GET['options'];
$quantity = $_GET['quantity'];
$session = session_id();
$_SESSION['sess_var'] = $session;
mysql_query("INSERT INTO sessionid (sessionid, link, retailer, price, title, qt, options) VALUES('$session' , '$link', '$retailer', '$price', '$title', '$quantity', '$options') ");
$query = "SELECT * FROM `sessionid` WHERE `sessionid` = '$session' ";
$result = mysql_query($query) or die(mysql_error());
echo '<table class="table"><tbody><form action = "viewcart.php" method = "get">';
$subtotal = 0;
$i=1;
while($row = mysql_fetch_assoc($result)) {
echo '<tr><td></td><td><h3>' . $row['title'] . '</h3></td><td>' . $row['options'] . '</td><td><div class="span3 offset1"><input type="text" name="box[' . $i . '] "value="' . $row['qt'] . '" class="span1"> <input type="submit" class="btn" value = "Refresh"> <h4> $' . $row['price'] . '</h4></td></tr>';
$i++;
$prodtotal= $row['qt'] * $row['price'];
$subtotal= round($subtotal+ $prodtotal, 2);
$_SESSION['subtotal']=$subtotal;
}
echo '</form></tbody></table>';
There are many ways to handle your situation. Here are 3 approaches for you to consider:
If you want to keep the DB session updated with every update on page and you want to do the update through form submission and page refresh then you will need to recognize which form is filling the super global that you are using: The one on the previous page or the one on the current page. I have done this in the past by adding a hidden form field (such as <input type="hidden" name="form_alias" value="update_form" />. You could also consider inserting on the previous page and redirecting on successful insert.
If you want to keep the DB session updated but want to avoid the need for refreshing the page just for a quantity update then you can submit the update through AJAX. (See MahanGM's note.)
If you do not need to update the DB session with every tiny quantity update and you like the idea of putting less stress on the db and server and do not mind doing more client-side (JavaScript) calculations, then you can just update the client-side content dynamically through JavaScript and only update the db upon form submission.
PS - Beware of SQL injection. Your current code is quite vulnerable to it. You are doing nothing to the user-passed data and it can be easily manipulated through the URL since you are using GET instead of POST. If you are not too far along I recommend switching to PDO and using prepare. Otherwise consider using mysql_real_escape_string.

Editting data by ADMIN

I am new to PHP and working on small local webpage and database that takes user information and database stores the same user information .If i Login with ADMIN it shows all data. My requirement is that the loggined user is an admin, then he has a right to edit all the informtion of the users that i stored in the database.And this is to be done using GET method . How it will be working?
Heres some example code purely to demonstrate how to update a table using a GET method form. The code doesn't have any kind of error checking and assumes you already know how to connect to your database (and that its MySQL).
Assuming you've landed on a page which invites you to edit data, which record you're editing is referenced by an 'id' variable on the URL which matches a numerical primary key in your database table.
<?php
$SQL = "SELECT myField1,myField2 FROM myTable WHERE myKeyField = '".intval($_GET['id'])."'";
$QRY = mysql_query($SQL);
$DATA = mysql_fetch_assoc($QRY);
?>
<form method='get' action='pageThatStoresData.php'>
<input type='hidden' name='key' value='<?php echo $_GET['id']; ?>' />
<input type='text' name='myField1' value="<?php echo $DATA['myField1']; ?>" />
<input type='text' name='myField2' value="<?php echo $DATA['myField2']; ?>" />
<button type='submit'>Submit</button>
</form>
So, this will give you a page that takes the data out of your table, displays it in a form with pre-filled values and on submit, will go to a URL like:
http://mydomain.com/pageThatStoresData.php?key=1&myField1=someData&myField2=someMoreData
In that page, you can access variables 'key', 'myField1', 'myField2' via the $_GET method.
Then you just need to update your table within that page:
$SQL = "UPDATE myTable
SET myField1 = '".mysql_real_escape_string($_GET['myField1'])."',
myField2 = ".mysql_real_escape_string($_GET['myField1'])."
WHERE key = '".intval($_GET['key'])."'
";
$QRY = mysql_query($SQL);
PLEASE NOTE: The code above is unsuitable for a straight copy/paste as it doesn't do any error checking etc, its purely a functional example (and typed straight in here so I apologise if there are any typos!).

Categories