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
Related
Ok so eventually I will have let's say 100 products in mysql database. The product page pulls all info from database (such as partnumber, material, color, etc...) and inputs it into the areas of the page that I designate it, all this using php. The previous page will show all 100 products and when user click's on one product it'll go to that product page. Just like all websites right...
I don't believe I need to make 100 individual html pages for each product right? Can I make just 1 main html page that is the templet for the 100 different products? Basically when user clicks the image tag of the product(1st example of code) it'll open the main html templet but somehow call to the database on open and load that specific info? Then other products will have the same process but for they're specific data from database. The 1st sample code is one product on the page that'll display all 100 products with the href containing the image that'll get clicked to show user actual product page retrieved dynamically without page reload, into a predestined section. I'm sure there is a name for what I'm looking to do but all the research I've done I haven't found what I'm looking for. Is there a better way then what I'm explaining? Also I hope this makes sense, Thank you for any input.
<td><img class="td-Image" src="image.jpg">
</td>
<td class="td-manufacturer">
<h6>MANUFACTURER</h6>
<p>Lowes</p>
</td>
<td class="td-addComponent">
<p>$104.99</p>
<button class="add-button">ADD</button>
</td>
<td class="td-material">
<h6>MATERIAL</h6>
<p>Aluminum 7075-t6 Forged</p>
</td>
<td class="td-platform">
<h6>PLATFORM</h6>
<p>Large</p>
</td>
<td class="td-america">
<h6>AMERICAN MADE</h6>
<p>YES</p>
</td>
Actual product page where php gets info from database example
<?php
$sql = "SELECT * FROM Parts;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<div class="description">
<h3>Descrption</h3>
<p>
<?php
echo $row['Description'];
?>
</p>
</div>
<?php
}
}
?>
Editor Note: I edited the question to reflect what he want based on thread on my answer below.
In this scenario you would need to pass in a unique identifier i.e product-id and create a query to fetch from the database product info by product-id
$product-id= $_GET['id'];
$strSQL = "SELECT * FROM AR15Parts WHERE id='$product-id'";
$rs = mysql_query($strSQL);
if (!$rs) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_assoc($rs);
//display your data
if($row){
echo $row['field'];
}
Add an unique Id to your products in your mysql database, using the Auto Increment option (A_I checkbox in phpmyadmin). Then you can pass that id into a link to the product page ```href=“individualProduct.php?id=” while rendering all the products on the all products page.
Then in individualProduct.php you can get that id and retrieve the data
$sql = SELECT * FROM Parts WHERE id =?”;
$stmt = mysqli_prepare($sql);
$stmt->bind_param($_GET[“id”]);
$stmt->execute();
$result = $stmt->get_result();
// Do stuff with $result as it is the individual product corresponding to that id
Optimally, you'll need 2 files:
index/list of products
detail information of the selected product
index files (maybe call it index.php)
Here, you need to select products and make it a list:
$stmt = $pdo->query("SELECT * FROM Parts");
while ($row = $stmt->fetch()) {
echo '' . $row['name']."<br />\n";
}
Since you want the detail to be shown to the index/list page, let's add a container area:
<div id="container-detail">
</div>
Add a little javascript code to handle AJAX request:
<script type="text/javascript">
function loadDetail(itemId){
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://website.address/path/to/detail.php?id=" + itemId, true);
xhr.onreadystatechange = function ()
{
if (xhr.readyState==4 && xhr.status==200)
{
document.getElementById("container-detail").innerHTML=xhr.responseText;
}
}
xhr.send();
}
</script>
detail page (let's call it detail.php)
In this screen, we fetch details for only one part, specified by HTTP GET id parameter. The one that's being supplied from index.php (the ?id= part).
$stmt = $pdo->query("SELECT * FROM Parts WHERE id = '" . $_GET['id'] . "'");
$part = $stmt->fetch();
echo "Name: " . $part['name'] . "<br />\n";
echo "Manufacturer: " . $part['manufacturer'] . "<br />\n";
echo "Price: " . $part['price'] . "<br />\n";
That's it, you should get it working with a few adjustments based on the table and template you have.
A little note is that I used PDO mechanism to do the query. This is because mysql_* function has been deprecated for so long that it is now removed from PHP 7.0. Also, the current PHP version has been PHP 8. So, be prepared, a lot of web hosting might gonna remove older PHP versions, moving forward.
I am trying to add a function to my website where it will add filters to a SQL select statement by allowing the user to enter text in some text boxes and clicking the filter button.
I haven't gotten as far as that because I'm having issues with the $_GET function.
The idea is that if the query parameters are set, it will use them in the sql statement and if not, it will just return all the rows.
Below is the displayListings function which is called every time the page is loaded.
Although I'm showing the whole function, I havent implemented most of it because nothing works past the line where I use $_GET.
<?php
function displayListings() {
global $dbConnection;
//checks if the query parameters exist
if (isset($_GET['title'])) {
echo 'got here... :F';//for debugging
var_dump($_GET['title']);//for debugging
$title_filter = $_GET('title');// THIS IS THE LINE THAT THE SCRIPT STOPS AT
var_dump($title_filter);//for debugging
}
//checks if the query parameters exist
if (isset($_GET['artist'])) {
$artist_filter = $_GET('artist');
echo $artist_filter."/n";
}
//checks if the query parameters exist
if (isset($_GET['release'])) {
$release_filter = $_GET('release');
echo $release_filter."/n";
}
echo 'here!';
// connect to the database
if (!connectToDb('musiconline')) {
$_SESSION['errorMsg'] = "Sorry, we could not connect to the database.";
header('location:listItem.php');
exit();
}
// after this point we have an open DB connection
// gets the current highest ID so we know what the next should be.
$sqlQuery = "SELECT listingid, recordtitle, artist FROM vinyl";
$result = $dbConnection->query($sqlQuery);
if (!$result) {
$_SESSION['errorMsg'] = "There was a problem with the database: " . $dbConnection->error;
closeConnection();
header('location:listItem.php');
exit();
}
//gets the results and puts them in a rows array
while($row = $result->fetch_array()){
$rows[] = $row;
}
//iterates through each row of the results (each vinyl)
foreach($rows as $row){
$listingID = $row['listingid'];
$recordTitle = $row['recordtitle'];
$artist = $row['artist'];
echo '
<div class="listing">
<table class="tableception">
<tr><td><img src="uploads/vinyl'.$listingID.'.png" alt="img1" ></td><td>
<table class="listing-table">
<tr><td>Album title: </td><td>'.$recordTitle.'</td></tr>
<tr><td>Artist name: </td><td>'.$artist.'</td></tr>
</table>
</td></tr>
</table>
</div>
' . "\n";
}//END OF FOREACH
/* free result set */
$result->close();
/* close connection */
closeConnection();
}
?>
When I debug the page in my IDE, everything works fine, probably because there are no query parameters in the URL.
The page stops loading after the $_GET line, as seen below.shows screenshot of browser when query parameters exist in URL.
I just cant figure out what I'm doing wrong.
Thanks in advance.
I used curly brackets instead of square brackets in the line.
I had $title_filter = $_GET('title');
instead of $title_filter = $_GET['title'];
Thanks #AymDev for pointing this out to me!
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 } ?>
I'm building a website for the company I work for that is going to eventually replace the CRM we are using. Right now I have created a simple php file that creates a table of simple/basic values (I'm trying to test the concept before I scale it up to the read deal). I am using a WHILE loop to generate the table by pulling data from the server. I was able to make the first column in each row into a clickable link that will open to a new page. On this page, I want to post more detailed data that can be edited. For example, in the display.php file that shows the table created with the while loop I will have a property address, a city name and a person who is working to either buy or sell that property. When the user clicks on the first address, I want it to open into a page that will display information like bedrooms, bathrooms, square footage, subdivision, asking price, etc. It would be nice to have each of those fields editable too, but that's a different thing to tackle. Right now, I'm concerned with being able to click on one property and have it open up with the correct data in the next page. Right now, it successfully opens the page but it only shows the data from the first row no matter which row I click on in the table.
Here is the code that I have for the page that displays the table:
<?php
session_start();
if(isset($_SESSION['id'])) {
$username = $_SESSION['username'];
$userId = $_SESSION['id'];
} else {
header('Location: index.php');
die();
}
$dbCon = mysqli_connect("localhost", "##", "##", "##");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect: " . mysqli_connect_error();
}
$sql="SELECT * FROM leads";
$records=mysqli_query($dbCon,$sql);
?>
<html>
<head>
<title>Display Data</title>
<body>
<table action="" method="post" class="table" id="example">
<tr>
<th>Address</th>
<th>City</th>
<tr>
<?php
while($leads=mysqli_fetch_assoc($records)){
echo "<tr>";
//I'm trying to figure out how to pass the record's ID as a way of keeping track of which record I want to look at when I open it in the next page. I don't know how to put the id in the link so that it carries through to the next page.
echo "<td><a href='showstuff.php?leadid=$leadid'>".$leads['address']."</a></td>";
echo "<td>".$leads['city']."</td>";
echo "</tr>";
}
?>
</tr>
</table>
</body>
</head>
</html>
Here is my code for the page that should open up with a more detailed "profile view" of the data:
<?php
//connect to db
$dbCon = mysqli_connect("localhost", "##", "##", "##");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect: " . mysqli_connect_error();
}
//I tried to incorperate "WHERE leadid = '$_GET['leadid']'" in line 10 to define the lead id that is associated with the record that was selected in display.php and shoould be opened/shared to this page
$sql="SELECT * FROM leads";
$records=mysqli_query($dbCon,$sql);
$leads=mysqli_fetch_assoc($records);
//I tried to create a $_GET variable that calls on the record id that I am trying to pass from the display.php file to this page
$leadid=$_GET['leadid'];
?>
<html>
<head>
<title>Show Stuff</title>
<body>
<h1>Show Stuff Here</h1><br>
<?php
echo "<p>Test</p><br>";
//I only have one piece of information here to test if it works in the first place. Once it does, I'll add the rest of the fields to display
echo "Is ".$leadid=$leads['leadid']." your ID number?";
?>
</body>
</head>
</html>
Lastly, I am using sessions on here since eventually there will be various users with different levels of access to view and edit things. For now, it's really not too functional other than to log in and log out. It's also not very secure. But I'm more focused on figuring out the mechanics of one thing at a time as I build. It's no where near ready to be used. But I'm hopeful that I'll get there soon. You'll have to excuse my simple code, I'm just learning and teaching myself on my spare time since our company refuses to hire someone to actually do this...
You're putting $leadid in the URL parameters in the table, but you never set this variable.
<?php
while($leads=mysqli_fetch_assoc($records)){
echo "<tr>";
$leadid = $leads['leadid'];
echo "<td><a href='showstuff.php?leadid=$leadid'>".$leads['address']."</a></td>";
echo "<td>".$leads['city']."</td>";
echo "</tr>";
}
?>
Then you should be able to use $_GET['leadid'] in showstuff.php to show the information for the lead that they clicked on.
$leadid = intval($_GET['leadid']);
$sql="SELECT * FROM leads WHERE leadid = $leadid";
First, in your table, you have to put like this:
while($leads=mysqli_fetch_assoc($records)){
echo '<tr>';
echo '<td><a href="showstuff.php?leadid='.$leads['id'].'" >'.$leads['address'].'</a></td>';
echo '<td>'.$leads['city'].'</td>';
echo '</tr>';
}
Like this your link leadid will have a value.
Use simple quote ' ' for html value, it's faster and better for PHP. ;)
In your second file, make like this:
$leadid=$_GET['leadid'];
$sql="SELECT * FROM `leads` WHERE `id`='$leadid' ";
$records=mysqli_query($dbCon,$sql);
$leads=mysqli_fetch_assoc($records);
It's better to put for the table and columns names and ' ' for values.
In $leads array, you 'll have all data.
You can "print" it like this:
echo 'The ID is '.$leads['id'].' and the name is '$leads['name'];
I hope it's useful!
Being a huge PHP newbie I find myself stuck here.
I have an HTML table for a videogame store filled with elements taken from my database.
The point is, I want to be able to add a link to the game title. Moreover I want the link to direct to some "gamePage.php", a php page used for every videogame but of course showing different infos for each game (title, console etc).
The fact is that not only I can't add the hyperlink, but I have no clue on how to carry the videogame infos when I click on a link (even managing to add the link, all I would manage to do would be redirecting the user to a blank gamePage.php with no title).
This is the code I use to fill the table (the restore function fills my table):
<html>
<body>
<div>
<table width = "550px" height = "300px" border="2" >
<tr bgcolor="#5f9ea0">
<td>Title</td>
<td>Console</td>
<td>Genre</td>
<td>Price</td>
</tr>
<?php
$conn = #pg_connect('dbname=project user=memyself password=project');
function search(){
<!-- Work in progress -->
}
function restore(){
$query = "SELECT v.Title , c.Consolename , g.Genrename , v.Price
FROM vg_shop.videogame v, vg_shop.console c, vg_shop.genre g
WHERE v.Console=c.IDConsole AND v.Genre=g.IDGenre";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>",
$myrow['title'], $myrow['consolename'], $myrow['genrename'], $myrow['price']);
}
}
<!-- some code -->
</body>
</html>
At first i tried to do this
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>",
$myrow['title'], $myrow['consolename'], $myrow['genrename'], $myrow['price']);
But all I get is a white page, there's some syntax error I don't get.
And, even if it worked, I still can't carry at least the videogame PID through the gamePage link
so, you're managing to go to gamepage.php somehow.
So you need to add some sort of identifier to your link you that you could do some query on the gamepage.php by using that identifier to get info for that particular game.
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td><a href='gamePage.php?id=%s'>%s</a></td><td>%s</td><td>%s</td><td>%s</td></tr>", $myrow['id'], $myrow['title'], $myrow['consolename'], $myrow['genrename'], $myrow['price']);
Note: I assume that you're picking $myrow['id'] from database as well.
now on your gamepage.php do following.
$id = $_GET['id'];
$sql = "SELECT * FROM vg_shop.videogame WHERE `id` = $id";
$result = pg_query($sql);
if($result){
$result = pg_fetch_assoc($result):
//...
// echo "Name: ".$result['Title'];
// other fields
}
$result will have all info about that particular game that was clicked, you can display all as you want.
Cheers :)