PHP MYSQL Next and Previous Product Buttons - php

I have a dynamic page that pulls the categories from the database. this page is categories.php?CTGID=####, CTGID standing for the category number. Each product then has an ID assigned to it.
When they click on the product within the category it goes to a page Products.php?ID=###. What I want to create is when they are within the Product page there is a next and previous button.
What I would essentially need it to do is get the CTGID of the current product ID then the next button would be the ID of the next product withing that Category ID.
<?php
$db=mysql_connect ("localhost",[username],[password]) or die(mysql_error());
mysql_select_db("rentals");
$rentID = $_GET['ID'];
//Strip html
$strip_ID = strip_tags($rentID);
$html = htmlentities($strip_ID, ENT_QUOTES);
$escape = addslashes($html);
$table="online_rental_db";
$sql = "SELECT * FROM $table WHERE ID=$escape";
$query = mysql_query($sql) or die(mysql_error());
$rentals = mysql_fetch_assoc($query);
$description = ucwords(strtolower($rentals['Description']));
$image = $rentals['Image'];
$download = $rentals['PDF'];
$ID = $rentals['ID'];
$CTGID = $rentals['CTGID'];
$category = $rentals['Category'];
$video = $rentals['Video'];
$bytes = filesize("rentals/".$download);
$model = $rentals['Model'];
$made = ucwords(strtolower($rentals['Manufacturer']));
$productnum = $rentals['Productnum'];
then on the page I just echo out what I need in what area. I have read some articles on the next and previous buttons, but decided I might need some extra advice!

Not sure what you've tried, but in the past I've implemented getting next/previous values from the DB with the following queries:
$curId = 42; // current product id
$curCat = 1; // current category
$sqlPrev = 'SELECT `id` FROM `table`
WHERE `id` < '$curId' AND `catId` = '$curCat'
ORDER BY `id` DESC LIMIT 1;
$sqlNext = 'SELECT `id` FROM `table`
WHERE `id` > '$curId' AND `catId` = '$curCat'
ORDER BY `id` ASC LIMIT 1;
// execute each query
If you get no result back from one of the two queries, it means you are on the first or last item in that category so there is no prev/next button in that case.
Hope that helps.

Related

Don't query SQL string if value is empty

I have two drop down menu's and when you select a value the value is saved in a session and passed trough AJAX to update a div. I have this working.
The reason I save the value in a session is because I need the database query to be dynamically filled (constructed). At this moment I have the following code:
<?php
$q = $_GET['q'];
$_SESSION['theme'] = $q;
$i = $_SESSION['category'];
$query = "SELECT COUNT(".$q.") c FROM MirrorWebProductsExpanded WHERE Subcategorie = '".$i."'";
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_assoc($result);
echo "
<a href='http://example.nl/search/'>" . $row['c'] . "</a>";
?>
This counts all items from $q which is the value of the first drop down menu.
And WHERE Subcategorie = '".$i."', $i is the value from the second drop down menu.
But, now the problem. If the second value is empty (I haven't selected an option from that drop down menu) the query still add's this part to the query, like:
$query = "SELECT COUNT(".$q.") c FROM MirrorWebProductsExpanded WHERE Subcategorie = ''";.
This makes the count from the first drop down menu always show 0. Is there away to only add the WHERE Subcategorie = '".$i."' when the second drop down menu has a value?
I'm still kind of new to MySQL so please be nice...
Use a query without WHERE clause. Then check if $i is not null, empty or whitespace. If so, add WHERE clause to your query.
$query = "SELECT COUNT(".$q.") c FROM MirrorWebProductsExpanded";
if($i != "")
$query = $query." WHERE Subcategorie = '".$i."'";

How to select Single ID in MYSQL

I have a table citizens with a field id, title and link. If I use these codes it will display all the content of id, what I need is when I click the first id id it should display the content of the row. I tried to remove the loop and change the array to assoc but when I select the second id it will always display the 1 id.
mysql_select_db("do",$con1);
$sql = "SELECT * FROM citizens ORDER BY id DESC";
$myData = mysql_query($sql,$con1);
while($record = mysql_fetch_array($myData)){
echo $record['div'];
If you want to get single record from database with id=1, try following:
$myID = 1;
mysql_select_db("do",$con1);
$sql = "SELECT * FROM citizens WHERE id = $myID ORDER BY id DESC";
$myData = mysql_query($sql, $con1);
$record = mysql_fetch_row($myData);
echo $record['div'];

How to Unlink a File from Website's Folder when MSSQL Table Row is Deleted Using PHP

I am trying to make the link <a href='{$_SERVER['PHP_SELF']}?del=true&orderid={$row['orderid']}' style='color:black;' onclick='return show_confirm();'>Delete</a>
delete the specific row from the MSSQL table using the while function. Currently, the bottom code works fine and deletes the specific row from the table, but I would now like it to unlink a file from the sharedstorage folder. The file that gets unlinked has it's filename stored in the name column for that table row. Each table row has a name column that contains a unique file's name from the file that is located in the sharedstorage folder.
My problem in simple terms is when a table row gets deleted, the file for that row in my website's sharedstorage folder remains and does not get deleted with the row.
Here is the code for when the delete link is hit for that specific row:
// delete from table
if ($_GET['del'] == 'true') {
// cast id as int for security
$id = (int) $_GET['orderid'];
// delete row from table
$sql = "DELETE FROM shareddrive WHERE orderid = '$id'";
$result = mssql_query($sql, $conn) or die(mssql_get_last_message());
// select the info, ordering by usort
$sql = "SELECT orderid, name, type FROM shareddrive ORDER BY orderid";
$result = mssql_query($sql, $conn) or die(mssql_get_last_message());
// initialize a counter for rewriting usort
$job_pos_sortt = 1;
// while there is info to be fetched...
while ($r = mssql_fetch_assoc($result)) {
$job_poss = $r['orderid'];
// update the usort number to the one in the next number
$sql = "update shareddrive SET orderid = '$job_pos_sortt' WHERE name = '$job_poss'";
$update = mssql_query($sql, $conn) or die(mssql_get_last_message());
// inc to next avail number
$job_pos_sortt++;
} // end while // end if del
}
All help is greatly appreciated.
// delete from table
if ($_GET['del'] == 'true') {
// cast id as int for security
$id = (int) $_GET['orderid'];
// delete row from table
$file = mssql_fetch_array(mssql_query("select name from shareddrive where orderid = $id"));
unlink($file[0]);
$sql = "DELETE FROM shareddrive WHERE orderid = '$id'";
$result = mssql_query($sql, $conn) or die(mssql_get_last_message());
// select the info, ordering by usort
$sql = "SELECT orderid, name, type FROM shareddrive ORDER BY orderid";
$result = mssql_query($sql, $conn) or die(mssql_get_last_message());
// initialize a counter for rewriting usort
$job_pos_sortt = 1;
// while there is info to be fetched...
while ($r = mssql_fetch_assoc($result)) {
$job_poss = $r['orderid'];
// update the usort number to the one in the next number
$sql = "update shareddrive SET orderid = '$job_pos_sortt' WHERE name = '$job_poss'";
$update = mssql_query($sql, $conn) or die(mssql_get_last_message());
// inc to next avail number
$job_pos_sortt++;
} // end while // end if del
}

How do I update a row in MySQL using php?

How do I update the row $pageviews by +1 each time someone visits my page. The table name is news and the row to be updated is $pageviews whose default value is +1. Should I use the update function? And how do I implement it? Below is my code. Can you show a demonstration using these data?
$data = mysql_query("SELECT * FROM news") or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
$id = $info['id'];
$pageviews = $info['pageviews'];
}
All you want to do is to increment pageviews value each time that page renders. All you need for that:
1) Get the current value
2) Run UPDATE query updating current value + 1
To do so, you can write a function that would look like as,
function inc_page_views($id) {
$res = mysql_query(sprintf("SELECT * FROM `news` WHERE `id` ='%s'", mysql_real_escape_string($id)));
$data = mysql_fetch_array($res);
// Target view count
$target = $data['pageviews'];
$query = sprintf("UPDATE `news` SET `pageviews` = '%s' WHERE `id` ='%s'", $target + 1, $id);
return mysql_unbuffered_query($query);
}
And then, when rendering a page, you can simply call inc_page_views(..here page id..) and it will do the rest
use this query
mysql_query("Update news SET pageviews = pageviews + 1 ");
or
store the current page id in $current_page_id.
mysql_query("Update news SET pageviews = pageviews + 1 where id = '$current_page_id' ");

There has got to be a more efficient way to do this

Basically I am trying to trim the images table down to 3,500 rows of unsaved or unfiltered images. Unsaved and unfiltered refer to other tables in the DB. A user can save an image as well as mark an image safe for work etc... I would like to keep all images in the saves table as well as the filter table.
Ultimately, The images table will get trimmed down to (3,500 unsaved/unfiltered images) + ("X" saved)+("X" unfiltered). The link between saves/filters/images is the auto_incremented id given to the record in the images table. So saves has an image_id field that gets the key of the record in the images table. same with the filters table
//connect to database
$connect = xxxxxxxxxxx;
//GET ALL IMAGES FROM `images` Table - NEWEST FIRST (`id` is auto_increment)
$sql = mysql_query("SELECT * FROM `images` ORDER BY `id` DESC") or die(mysql_error());
$x = 0;
while($row = mysql_fetch_array($sql)){
//GET CURRENT IMAGES ID AND URL
$id = $row['id'];
$file = $row['url'];
//SEE IF IMAGE IS IN THE saves Table
$saves = mysql_query("SELECT `id` FROM `saves` WHERE `img_id` = '".$id."'") or die(mysql_error());
if(mysql_num_rows($saves) == 0){$saved = FALSE;}
else {$saved = TRUE;}
//SEE IF IMAGE IS IN THE filters Table
$filter = mysql_query("SELECT `id` FROM `filter` WHERE `img_id` = '".$id."'") or die(mysql_error());
if(mysql_num_rows($filter) == 0){$filtered = FALSE;}
else {$filtered = TRUE;}
//If the image has not been saved or filtered then put it in a que for deletion
if(!$saved || !$filtered){
$IdQue[$x] = $id;
$FileQue[$x] = $file;
$x++;
}//END if
}//END while
//Process the delete que: Delete node from database, delete file on server. Keep 3,500 of the newest images.
for($i=3500; $i<$x; $i++){
mysql_query("DELETE FROM `images` WHERE id='".$IdQue[$i]."' LIMIT 1") or die("line 33".mysql_error());
if(file_exists($FileQue[$i])){
unlink($FileQue[$i]) or die("file Not deleted");
}//END if
}//END for
echo ($i-3500)." files deleted<br/>";
//terminate connection
mysql_close($connect);
this should get you going somewhere, not a complete code though:
first, strip selecting ids down to 2 queries:
$missing_from_filters = SELECT id FROM images WHERE img_id NOT IN (SELECT img_id FROM filter)
$missing_from_saves = SELECT id FROM images WHERE img_id NOT IN (SELECT img_id FROM saves)
then, get ids that are in both arrays
$to_delete = array_intersect($missing_from_filters,$missing_from_saves);
run one query to remove them all
$remove_query = 'DELETE FROM images WHERE img_id IN ( '.implode(',',$to_delete).') LIMIT 3500';

Categories