Create dynamic category menu in PHP - php

I'm new to coding and PHP and I want to create an online shop for a school project. I want simple code that selects categories in my DB shows them on a home page and when click on it select all things in that category and shows them. I wrote code that can create buttons for each category that are in my database but I have no idea how write code that when the user clicks on a button selects that category.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$servername = "localhost";
$username = "root";
$password = "123456789";
$dbname = "shopdb";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT category FROM good ";
$result = $conn->query($sql);
echo "category: ";
while($row = $result->fetch_assoc()) {
echo "<button>$row[category]</button>" ;
}
$conn->close();
?>

If you want to use only php you can redirect the use after he clicks the category.
while($row = $result->fetch_assoc()) {
$category = $row["category"];
echo "<a href=’?category=$category’>$category</a>" ;
}
Make the link look like a button with css.
So when the user clicks on the link it redirects him to the same page he is currently but it adds the
?category in the end of it. home.php?category=clothes.
In the same page use $_GET to get the ?category value from the url.
And make a query to get your items for the category.
if(isset($_GET[’category’])){
$category = $_GET[’category’];
$sql = mysqli_prepare(”SELECT * FROM items WHERE category = ?”);
$sql->bind_param(”ss”, $category);
$sql->execute();
while($row = $sql->fetch_assoc()) {
echo $row[”name”];
}
}
And you should do this before you close your mysqli connection.
You may need to change the query because i don’t know your tables and you could maby wrap the while loop inside a div or something. But i hope you get the basic idea.
If you want it to look more fancy you could do the same with jQuery and Ajax since you have the jQuery tag.
Make a click function for your category buttons. You should add classes on them. <button class=’category’>$row[category]</button>.
Make another file for your ajax requests to get your items for the category.
$(”.category”).click(function() {
var category = $(this).text();
$.ajax({
url: ”items.php?category=” + category,
type: ”GET”,
success: function(items) {
console.log(items);
}
});
});
In your items.php or whatever you named it you can basically do the same php code that i wrote earlier.
Get the category name from the url with $_GET[’category’] and use it to search the items from your database.
The items variable that we have as parameter in the ajax success function, now contains everything that items.php echo out.
Now continue to handle the data in the items variable and display it.

You must pass your php variable in your html code. After in your html code try this.
<?php while( $row = $result->fetch_assoc() ) { ?>
<button><?php echo $row[category] ?></button>
<?php } ?>

Related

Generate new post WordPress based on MySQL database

I have created a Wordpress page to show dynamic content based on MySQL database. The content will be shown based on the URL parameter.
Ex: https://domainname.com/hotel-details/?hotelcode=First-Hotel
Is it possible to generate a new post for each database row?
So, instead of using an URL parameter like one above, the URL could be: https://domainname.com/hotel-details/First-Hotel
I created this dynamic page by inserting a PHP code to a Wordpress page (I use Advanced Ads plugin to insert the code)
<?php
if (isset($_GET['hotelcode']))
{
$hotelcode = $_GET['hotelcode'];
}
else
{
$hotelcode = "";
}
include 'dbconnect.php'; // MySQL DB connection
$dbconnect = mysqli_connect($host, $user, $password, $database);
$dbresult = mysqli_query($dbconnect, "
SELECT *
FROM HotelDatabase
WHERE HotelSlug='$hotelcode'
");
foreach ($dbresult as $row);
$HotelName= $row['HotelName']; $HotelDetail= $row['HotelDetail'];
$Image= $row['Image']; $Review= $row['Review'];
?>
<?php if($dbresult->num_rows == 0)
{
echo "<h1 style='text-align: center;'>No Data Found</h1>
}
else
{
echo "
<br><br>
<h1 style='text-align: center; color: blue;'>$Hotel Name</h1>
<img src='$Image'><br>
$HotelDetail<br>
$Review
";
}
?>
I have no problem to display the content on the page, what I want is, show the content on the new generated pages for each database row instead of using a unique URL parameter.
Change
https://domainname.com/hotel-details/?hotelcode=First-Hotel
to
https://domainname.com/hotel-details/First-Hotel

How to grab the id of the search result came from

What you are seeing is my code that displays images as a search result. I have an anchor down there so when you click on the picture it sends you to a TEST page.
I want to have a page set up that will display the rest of the row entries that are associated with that picture:
(Picture) Player: Steve Sax
Card Type: Donruss
Year: 1989
Value: $2.00
How do I grab the "id" in the row of the search result and then echo it in a table that shows up on the TEST page?
<?php
$servername = "*********";
$username = "*********";
$password = "*********";
$dbname = "*********";
$username1=$_SESSION['activeusername'];
$userid = $_SESSION['activeid'];
$userid = $_SESSION['activeid'];
$itemid = $_SESSION['activeid'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM useritems JOIN (users, iteminfo) on (users.id=useritems.UserID AND iteminfo.ID=useritems.ItemID) AND userid='2'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<a href='test1.php'><div id='frame'>
<div id='splash-image' style='background: url(".$row['imagename']."); background-size:cover;'></div>
<div id='text'>
<table >
<tr></tr>
</table>
</div>
</div>";
}
} else {
echo "You Have No Items In Your Closet!!!";
}
mysqli_close($conn);
?>
Pass the id with get as:
echo "<a href='test1.php?id=". $row['id']."'>
And get it on the landing page as:
$id=$_GET['id'];
echo $id;
Assuming the id you want is the item's id, you would echo out
$row['ItemID']
If you wanted to include this ID into your href as a GET parameter you could do something like:
echo "<a href='test1.php?ItemID=" . $row['ItemID'] ."'>...</a>";
Then, in your test1.php, you can retrieve the Item ID for use in your query (after sanitizing it!) by accessing the $_GET global.
$ItemID = $_GET['ItemID'];
If you just wanted the result set row number (not tied to user id or item id), you could echo out something like:
$counter++
or take a look at MySQL - Get row number on select

How to populate multiple items on a different page using a search bar?

Hi I was wondering if anyone could help. I have just developed a search bar for my site which will be on every page loaded using an include function so they will all be the same. The code can read my database perfectly but I am at a lose on how to send more than one result to another page in the format that I need. The problem is that I post 2 to 3 variables to the next page in the url for each link of this sort and if the search bar returns more than 1 result then each result will need 2 to 3 variables to populate the next page.
Link example
Movies Home
Here is the search bar code.
<?php
if(isset($_POST['search_term'])){
$search_term = $_POST['search_term'];
if (!empty($search_term)) {
$query = "SELECT title FROM database WHERE title LIKE '%".mysql_real_escape_string($search_term)."%'";
$query_run = mysql_query($query);
$query_num_rows = mysql_num_rows($query_run);
$result = mysql_query($query_num_rows);
if ($query_num_rows >= 1) {
echo $query_num_rows.' results found:<br>';
while ($query_row = mysql_fetch_assoc($query_run)){
echo $query_row ['title']. '<br>';
}
}
else{
echo 'No results found.';
}
}
}
?>
This code currently echos on the current page. I am hopeing to pass it to a results page and populate multiple items depending on how many results were found in the search bar. Here is an example of the code that I would be hopeing to populate from the search bar on the target page.
<?php
if (isset($var1)){
$subject_set = mysql_query("Select * FROM database WHERE genre like '%".$info."%' and media = '".$med."' ORDER BY ".$sort." ", $connection);}
else{
$subject_set = mysql_query("Select * FROM media", $connection);
}
if (!$subject_set){
die("Database connection failed: " . mysql_error());
}
htlm code</div>
<?php } ?>
I was thinking that if I was even able to pass the results id's using an array and then retrieve the corrosponding results from the database on the target page.
Sorry I am still quite a novice at this type of coding and I hope I did not confuse anyone with what I am trying to say. Thank you for your time and hopefully I can get this problem sorted. Thanks again.
If you want to display the results on other pages, consider putting them in SESSION variables.
<?php
session_start ( ); // at top of page
...
$theIndex=0;
while ($query_row = mysql_fetch_assoc($query_run)){
echo $query_row ['title']. '<br>';
$_SESSION['searchResult'][$theIndex] =$query_row ['title'];
$theIndex++;
}
Then on your the page where you want to display the results, loop through the SESSION['searchResult'] and echo it out...
<?php
session_start ( ); // at top of page
$theResults = $_SESSION['searchResult'];
foreach ($theResults as $key=>$value){
echo htmlentities($value) . "<br>";
}

PHP mysql not showing up admin panel feature

so i've been up for a long time working on this. So basically want I need to do is make an add, update, delete user table. Right now i'm currently just working on a table that shows what I have in my database and options to edite, delete, or add.
I have 2 tables in my database.
Links Table with the fields of : PID, LinkName, AnchorText, CategoryID, CategoryName
linkCategory table with the fields of : CategoryID, CategoryName
here's what I have so far.... and it's not showing up at all. No errors or anything.
<?php
// acquire shared info from other files
include("dbconn.inc.php"); // database connection
include("shared.php"); // stored shared contents
// make database connection
$conn = dbConnect();
print $HTMLHeader;
print $PageTitle;
?>
<script>
function confirmDel(title, pid) {
// javascript function to ask for deletion confirmation
url = "admin_delete.php?pid="+pid;
var agree = confirm("Delete this item: <" + title + "> ? ");
if (agree) {
// redirect to the deletion script
location.href = url;
}
else {
// do nothing
return;
}
}
</script>
<?php
// Retrieve the product & category info
$sql = "SELECT Links.PID, Links.AnchorText, linkCategory.CategoryName FROM Links, linkCategory where Links.CategoryID = linkCategory.CategoryID order by linkCategory.CategoryName";
$stmt = $conn->stmt_init();
if ($stmt->prepare($sql)){
$stmt->execute();
$stmt->bind_result($PID, $Title, $CategoryName);
$tblRows = "";
while($stmt->fetch()){
$Title_js = htmlspecialchars($Title, ENT_QUOTES); // convert quotation marks in the product title to html entity code. This way, the quotation marks won't cause trouble in the javascript function call ( href='javascript:confirmDel ...' ) below.
$tblRows = $tblRows."<tr><td>$Title</td>
<td>$CategoryName</td>
<td><a href='admin_form.php?pid=$PID'>Edit</a> | <a href='javascript:confirmDel(\"$Title_js\",$PID)'>Delete</a> </td></tr>";
}
$output = "<table border=1 cellpadding=4>\n
<tr><th>Title</th><th>Category</th><th>Options</th></tr>\n".$tblRows.
"</table>";
$stmt->close();
} else {
$output = "Query to retrieve product information failed.";
}
$conn->close();
?>
<?= $SubTitle_Admin ?>
<br>
| Add a new item |<br>
<?php echo $output ?>
<?php print $PageFooter; ?>
</body>
</html>
This is my first page, I still have to put in the PHP for edit, update, and delete... but can't even get my main page to show up. A bit lengthy, but I need to get this done. If anyone could help me out, or point me the right direction... I would be grateful. Here is a link to what it should look like http://omega.uta.edu/~cyjang/ctec4321/lab/productList2/admin_productList.php. When I try to pull my own up it's a blank page... like this: http://omega.uta.edu/~dxh6110/4321/in%20class/linksadmin/admin_productList.php

Displaying output of php within jquery colorbox ... getting undefined index error

I hope someone can help me, I have created a simple html form with drop down menu's, the drop down menus are populated from a mysql data base, the user must select from two drop downs and this will then display the data ( both selections make the sql query)
This all works correctly within the HTML however I am trying to jazz it up a bit and have the output display within a jquery colorbox (popup).
I am not sure how to format the syntax for the jquery function .. this is what I have so far
<script>
$(document).ready(function(){
$(".inline").colorbox({inline:true, width:"50%"});
$("input#formsubmit").colorbox({href: function(){
var url = $(this).parents('form').attr('action');
return url;
}, innerWidth:920, innerHeight:"86%", iframe:true});
});
</script>
This correctly launches the colorbox pop up and fires the php "action" from my form but the $_POST attributes are not sent across and I just get an unidentified index error from mysql.
Can some one please help me ?
Im sure its something simple, but I cant figure it out.
Many thanks
Adding PHP ...
<?php
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("verify") or die(mysql_error());
$result = mysql_query("SELECT Entitlement FROM products WHERE ProductName = '$_POST[product]' AND CustomerType = '$_POST[customer]'")
or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['Entitlement'] ;
echo "<br />";
}
?>
Can you please tell how may this code works with you :)
<?php $result = mysql_query("SELECT Entitlement FROM products WHERE ProductName = '$_POST[product]' AND CustomerType = '$_POST[customer]'");?>
You have 2 error the first one the single quote beside the index in your post variable and must be like this $_POST['product'],$_POST['customer'] then the second error is that you must encapsulate your variable inside the string as following {$_POST['product']},{$_POST['customer']}
Try these work around then tell me the result :)
try this
<?php
// Checking for valid post data
if (isset($_POST['product']) && isset($_POST['customer']) && !empty($_POST['product']) && !empty($_POST['customer'])) {
// Cleaning post data
$proudct = mysql_escape_string($_POST['product']);
$customer = mysql_escape_string($_POST['customer']);
// db connnection
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("verify") or die(mysql_error());
// Quering
$result = mysql_query("SELECT Entitlement FROM products WHERE ProductName = '$proudct' AND CustomerType = '$customer'") or die(mysql_error());
// Printing result
while ($row = mysql_fetch_array($result)) {
echo $row['Entitlement'];
echo "<br />";
}
}
?>

Categories