forgive me I just learned php this week, so I'm not sure I'm doing this all right.
It starts out accessing the DB, and the categories table for headers; it then takes that info and creates the header, pricing, and catalog links.
Then within that while loop after it completes the first part it's supposed to run a second while loop to access the products table to list all the products with the category_id that matches the cat_id from the categories table.
When it prints out it should be
Header
Pricing PDF
Item Dimensions Image Image
Item Dimensions Image Image
Item Dimensions Image Image
etc
Header
Pricing PDF
Item Dimensions Image Image
etc....
And so far the first while loop works but the second isn't. Is there a correct way to pass the variable? Can I just not access a second table while in a while loop for the first table? I dunno...I've tried a few things, and nothing is working well
<?php
//connect to server
$con = mysql_connect('localhost','username','password');
//test connection
if (!$con)
{
die ('Could not connect: ' . mysql_error());
}
//access primary DB
mysql_select_db("main_db", $con);
//place table into variable
$categories = mysql_query("SELECT * FROM categories");
//begin table build
while($row = mysql_fetch_array($categories))
{
//set shading variable
$table_row = 0;
//set current set
$cur_set = $row['cat_id'];
//create document link and header
echo "<a name='" . $row['cat_name'] . "'><h3>" . $row['cat_title'] . "</h3></a>";
//create table and table formatting cell
echo "<table id='productTable'><tr id='tableHead'>";
//table width formattting here
echo "<td style='width:165px;'></td>";
echo "<td style='width:235px;'></td>";
echo "<td style='width:155px;'>";
//link and icons to category catalog
echo "<a href='catalog/" . $row['cat_pdf'] . ".pdf'><img src='data/pdflogo.png' alt='pdf button' /></a>";
//link and icons to category pricing sheet
echo "<a href='catalog/" . $row['cat_pricing'] . ".pdf'><img src='data/pricinglogo.png' alt='pricing button' /></a>";
//finish formatting
echo "</td></tr>";
//place table into variable
$products = mysql_query("SELECT * FROM products WHERE category_id='" . $row['cat_id'] . "'");
//begin table build
while($table = mysql_fetch_array($products));
{
//create up row
echo "<tr id='tr" . $table_row . "'>";
//create first cell
echo "<td>" . $table['prod_name'] . "</td>";
//create second cell
echo "<td>" . $table['prod_dim'] . "</td>";
//create third cell
echo "<td>";
//create third cell, first image
echo "<a href='catalog/" . $table['prod_img1'] . ".jpg'>" . "<img src='data/jpglogo.png' alt='image button' />" . "</a>";
//create third cell, second image
echo "<a href='catalog/" . $row2['prod_img2'] . ".jpg'>" . "<img src='data/jpglogo.png' alt='image button' />" . "</a>";
//finish formatting
echo "</td></tr>";
//cycle row
if ($table_row == 0)
{
$table_row = 1;
}
else
{
$table_row = 0;
}
//end table
echo "</table>";
}
}
//close connection
mysql_close($con);
?>
Thanks in advance
It would be more streamlined to perform an INNER JOIN on both tables
SELECT
A.cat_id,A.cat_name,A.cat_title,A.cat_pdf,A.cat_pricing,
B.prod_name,B.prod_img1,B.prod_img2
FROM categories A INNER JOIN products B ON A.cat_id = B.category_id;
You can iterate on A.cat_id
This is my proposed suggestion (braces might be off, but here is what the iteration on cat_id should look like). Please change the style for starting and stopping tags.
<?php
//connect to server
$con = mysql_connect('localhost','username','password');
//test connection
if (!$con)
{
die ('Could not connect: ' . mysql_error());
}
//access primary DB
mysql_select_db("main_db", $con);
//place table into variable
$categories = mysql_query("SELECT A.cat_id,A.cat_name,A.cat_title,A.cat_pdf,A.cat_pricing,B.prod_name,B.prod_img1,B.prod_img2 FROM categories A INNER JOIN products B ON A.cat_id = B.category_id");
$current_catid = -1;
//begin table build
while($row = mysql_fetch_array($categories))
{
if ( $current_catid != $row['cat_id'] )
{
if ( $current_catid > -1 ) { echo "</table>"; }
$current_catid != $row['cat_id']
//set shading variable
$table_row = 0;
//set current set
$cur_set = $row['cat_id'];
//create document link and header
echo "<a name='" . $row['cat_name'] . "'><h3>" . $row['cat_title'] . "</h3></a>";
//create table and table formatting cell
echo "<table id='productTable'><tr id='tableHead'>";
//table width formattting here
echo "<td style='width:165px;'></td>";
echo "<td style='width:235px;'></td>";
echo "<td style='width:155px;'>";
//link and icons to category catalog
echo "<a href='catalog/" . $row['cat_pdf'] . ".pdf'><img src='data/pdflogo.png' alt='pdf button' /></a>";
//link and icons to category pricing sheet
echo "<a href='catalog/" . $row['cat_pricing'] . ".pdf'><img src='data/pricinglogo.png' alt='pricing button' /></a>";
//finish formatting
echo "</td></tr>";
}
//create up row
echo "<tr id='tr" . $table_row . "'>";
//create first cell
echo "<td>" . $table['prod_name'] . "</td>";
//create second cell
echo "<td>" . $table['prod_dim'] . "</td>";
//create third cell
echo "<td>";
//create third cell, first image
echo "<a href='catalog/" . $table['prod_img1'] . ".jpg'>" . "<img src='data/jpglogo.png' alt='image button' />" . "</a>";
//create third cell, second image
echo "<a href='catalog/" . $row2['prod_img2'] . ".jpg'>" . "<img src='data/jpglogo.png' alt='image button' />" . "</a>";
//finish formatting
echo "</td></tr>";
//cycle row
if ($table_row == 0)
{
$table_row = 1;
}
else
{
$table_row = 0;
}
//end table (Fix this, might produce extra table tag)
echo "</table>";
}
//close connection
mysql_close($con);
?>
You are loading relative data, so a short answer is no, because of the overhead you will probably have if you would select them with joins.
Also, try to limit the overhead created by the * by selecting only what you want and not everything.
Also follow Truth's recommendations, for new mysql(i) calls. Once you get a hang with sql and php, you can move to other types of database calls (using object oriented code -- or activerecord), but please try to understand how mysql calls are being done first.
Related
My wife's family is big into jigsaw puzzles and I am using PHP and MySQL to build them a site so they can see what puzzles they already own. This should prevent issues of buying the same puzzle twice.
When someone adds a puzzle, I will get them to upload an image of the box art that will then be stored as a blob in the database. I have all the puzzles in the database appearing in a styled table and I am happy with how it looks, but there is one more piece of functionality that I would like to have.
The table displays the uploaded blob/image, and I use CSS to reduce it to thumbnail size - a future revision will show a true thumbnail to save data but that comes later, for now a CSS reduced blob/image is fine.
What I want to do is also have the thumbnail image be a link that can be clicked to open the image full size, but I don't know how to grab a URL from a blob stored in MySQL and hoping someone can help. What I currently have is below. Thanks in advance for your help!
$conn = new mysqli($configs->host, $configs->username, $configs->password, $configs->database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT puzzles.name, puzzles.photo, manufacturers.name as manufacturer, owners.name as owner FROM puzzles LEFT JOIN manufacturers ON puzzles.manufacturer = manufacturers.id LEFT JOIN owners ON puzzles.owner = owners.id ORDER BY puzzles.id";
$result = $conn->query($sql);
?>
<?php
echo '<table id="puzzleTable">
<tr>
<th>Puzzle Name</th>
<th>Manufacturer</th>
<th>Owner</th>
<th>Puzzle Photo</th>
<th>Options</th>
</tr>';
while ($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['manufacturer'] . "</td>";
echo "<td>" . $row['owner'] . "</td>";
echo "<td><a href='NEED BLOB IMAGE URL HERE'><img src='data:image/jpeg;base64,".base64_encode($row['photo'])."'/></a></td>";
echo "<td><a href='#'>Edit</a> | <a href='#'>Delete</a></td>";
}
echo "</tr></table>";
You should create a link to a php page. A parameter for the ID of the record related to the database should be sent to it. In the php page, set the header like this: header("Content-type: imageType).
mysql blob using php
for build your app that return your URL and you can show this image, you should to do a insert in your db with your local storage folder or internet URL. In new column. Blob return only object image, but I recommend you that not use blob, think that if your app it grows, you db will be very weight and will delay in return data.
you can to do:
query for url internet
$sql = "INSERT INTO puzzles(column, column, column, url)
VALUES ('xxx', 'xxx', 'xxx', 'https://urlInternet')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
query for url local
$sql = "INSERT INTO puzzles(column, column, column, url)
VALUES ('xxx', 'xxx', 'xxx', '/images/'.$_POST["img"])";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
When you return your data:
while ($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['manufacturer'] . "</td>";
echo "<td>" . $row['owner'] . "</td>";
echo "<td><a href='".$row['URL']"'><img src='data:image/jpeg;base64,".base64_encode($row['photo'])."'/></a></td>";
echo "<td><a href='#'>Edit</a> | <a href='#'>Delete</a></td>";
}
I am unable to locate the answer on here. Hopefully someone can help.
I want the table to display a running total of Xproducts to Xcost.
I get the data from an SQL database and have been stuck on this for months.
<!-- begin snippet: js hide: false console: true babel: false
language: lang-css -->
<?php
//Create a table to fill in
echo("<table border=1>");
echo("<tr><th>Image</th><th>Name</th><th>Product Description</th><th>Inventory</th><th>Cost</th><th>Order</th><th>Total</th></tr>");
require_once("serverCode/connect.php");
$sql = "Select * FROM products;";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()) {
// Jquery associate number with the textbox for each product
// dynamic on the fly (after is simpler )
$id = $row['productsID'];
/*Start columns*/ echo("<tr>");
/*Image column*/ echo("<td><img src='images/" . $id . ".jpg'" . "</td>");
/*Name column*/ echo("<td>" . $row['productsName'] . "</td>");
/*Image column*/ echo("<td>" . $row['productsDesc'] . "</td>");
/*Inv column*/ echo("<td>" . $row['productsInv'] . "</td>");
/*Cost column*/ echo("<td>" . $row['productsCost'] . "</td>");
/*orderAmt column*/ echo("<td><input type=text name = 'product_$id'></td>");
/*Subtotals column*/ echo("<td>" "</td>");
/*end columns*/ echo("</tr>");
}
echo("<tr><th></th><th></th><th></th><th></th><th></th><th></th><th>FINALTotal</th></tr>");
/*end table*/ echo("</table>")
?>
<!-- end snippet -->
I don't think I posted the data right, but hopefully, this helps
Below is a picture of what it looks like
I have highlighted where subtotals should go and final total as well.
enter image description here
Hi Lily and welcome to stackoverflow.
Your code is a mess, I tried to fix it somewhat, but I didn't check everything. Please try this one:
<?php
require_once("serverCode/connect.php");
//Create a table to fill in
echo "<table border=1>";
echo "<tr><th>Image</th><th>Name</th><th>Product Description</th><th>Inventory</th><th>Cost</th><th>Order</th><th>Total</th></tr>";
$sql = "Select * FROM products;";
$result = $mysqli->query($sql);
// add a variable to store the running subtotal in:
$subtotal = 0;
while($row = $result->fetch_assoc()) {
// add the cost of the current product to $subtotal
// and make sure it is a float value:
$subtotal += floatval($row['productsCost']);
$id = $row['productsID'];
echo "<tr>"; // Start columns*/
echo "<td><img src=\"images/$id.jpg\"/></td>"; // Image column
echo "<td>" . $row['productsName'] . "</td>"; // Name column
echo "<td>" . $row['productsDesc'] . "</td>"; // Image column
echo "<td>" . $row['productsInv'] . "</td>"; // Inv column
echo "<td>" . $row['productsCost'] . "</td>"; // Cost
echo "<td><input type=\"text\" name=\"$id\"></td>"; // orderAmt column
// output the subtotal:
echo "<td>$subtotal</td>"; // Subtotals column
echo "</tr>"; // end columns
}
echo "<tr><th></th><th></th><th></th><th></th><th></th><th></th><th>FINALTotal</th></tr>";
echo "</table>"; // end table
?>
Outside the while-loop you declare a variable $subtotal. Within the loop you add the currect product cost to it (+= operator) and print it to the table. I have added comments where this happens.
Furthermore I would recommend you to find a php tutorial and learn the language before you start bigger projects. Have fun!
For a project I am building a flash game website, and I would like to know how to reuse this piece of code:
$result = $conn->query("SELECT DISTINCT `category` FROM beoordeling");
<?php
echo "<div class='row list jumbotron'>";
while($data = $result->fetch_assoc()) {
echo "<div class='col-md-3'><a href='category.php?id=" . $data['category'] . "' class='thumbnail'><h4>" . ucfirst($data['category']) . " games</h4>";
echo "<img src='" . $imgLocation . $data['category'].".jpg' class='img-rounded' alt='" . $data['category'] . "' width='304' heigth='182'>";
echo "</a></div>";
}
echo "</div>";
?>
I need to be able to use the $data['category'] again for dynamicly filling my menu with all of the games categories. If I just try to use the while loop again but then only one will work. The other one stays empty. Thanks alot!
You need to adjust the result pointer to point to the beginning of the result set so that you could use it again. Make use of mysqli_result::data_seek() method for this.
Here's the reference:
mysqli_result::data_seek()
So your code should be like this:
<?php
$result = $conn->query("SELECT DISTINCT `category` FROM beoordeling");
echo "<div class='row list jumbotron'>";
while($data = $result->fetch_assoc()) {
echo "<div class='col-md-3'><a href='category.php?id=" . $data['category'] . "' class='thumbnail'><h4>" . ucfirst($data['category']) . " games</h4>";
echo "<img src='" . $imgLocation . $data['category'].".jpg' class='img-rounded' alt='" . $data['category'] . "' width='304' heigth='182'>";
echo "</a></div>";
}
echo "</div>";
// adjust the result pointer to point to the beginning of the result set
$result->data_seek(0);
// now you can use the result set again
// for example, you can iterate through it using while loop again
?>
I currently have 2 different sections for this program, the first half takes the users input from a web page and then transfers it over onto a PHP side which will access MySQL and display the requested information.
Example: If I enter AX12 for the ID it will display information for that ID which does infact exist, but if I enter AX13 (which doesn't) it will display blank information, so I'm wondering if someone can show me how I can validate this once the information has been transferred over onto the PHP side. So if it detects that the information you've submitted does not exist simply display a message saying "ID DOES NOT EXIST" or something along those lines.
Here's the code for the PHP side if you need it for more information.
<?php
$part_number = $_GET['txtInput'];
$part_description;
$units_on_hand;
$item_class;
$warehouse_number;
$unit_price;
$query;
$result_set;
$connection;
$record;
echo "<html>";
echo "<head>";
echo "<title>SQL Application</title>";
echo "<style type = 'text/css'>body{text-align: center; background-color: #CC3333; color: #660000; font-size: 30;}</style>";
echo "</head>";
echo "<body>";
echo "<center><h1>SQL Application</h1></center>";
echo "<br />";
echo "<br />";
echo "<br />";
$connection = #mysql_connect("localhost","m_stanicic","")
or die ("\n\n PROBLEM CONNECTING TO DATABASE! \n" . mysql_error() . "\n\n");
mysql_select_db("m_stanicicdb");
$query = "select * from part where part_number = '" . $part_number . "'";
$result_set = mysql_query($query)
or die ("\n\n PROBLEM WITH QUERY! . \n" . mysql_error() . "\n\n");
$record = mysql_fetch_assoc($result_set);
if($part_number == "")
{
//
}
else
{
$part_description = $record['part_description'];
$units_on_hand = $record['units_on_hand'];
$item_class = $record['item_class'];
$warehouse_number = $record['warehouse_number'];
$unit_price = $record['unit_price'];
echo "<center>";
echo "<table border='1' width=400 style ='table-layout:fixed' cellpadding='5' cellspacing='0'>";
echo "<col width = 200>";
echo "<col width = 200>";
echo "<tr>";
echo "<th colspan='2'>DETAILS OF THE PART YOU REQUESTED</th>";
echo "</tr>";
echo "<tr>";
echo "<td>part_description</td>";
echo "<td>" . $part_description . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>units_on_hand</td>";
echo "<td>" . $units_on_hand . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>item_class</td>";
echo "<td>" . $item_class . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>warehouse_number</td>";
echo "<td>" . $warehouse_number . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>unit_price</td>";
echo "<td>$" . $unit_price . "</td>";
echo "</tr>";
echo "</table>";
echo "</center>";
mysql_close($connection);
}
echo "<br />";
echo "<br />";
echo "<br />";
echo "<input type = 'button' value = 'RETURN' style = 'width: 75px; height: 75px;' onclick = \"javascript:window.location.href = 'jdpset1_4.html'\">";
echo "</body>";
echo "</html>";
You aren't validating anywhere that the result did return any data at all. Right after your call to mysql_query(), you should use mysql_num_rows() to see how many rows were returned by your query -- if mysql_num_rows($result_set) is zero, your query returned no data.
Notice how $part_number is never modified by mysql_query(), mysql_fetch_array() or any of those functions; so it will never be empty unless it started as such (rendering your current if almost useless).
You can check the output of your query $record...
if (count($record)==0) {
echo "the ID you entered does not exist! Try again...";
} else {
// code to output the part's details...
}
put the if (count... part instead of ...
if($part_number == "")
from your code i notice 2 things
$query = "select * from part where part_number = '" . $part_number . "'";
as your part number is a string, i recommend you to use LIKE not =
$query = "select * from part where part_number LIKE '" . $part_number . "'";
another is inspect your record is returning in multidimensional array like
$record = Array([0]=>array('part_description'=>A123...)).
then you must assign like so
$part_description = $record[0]['part_description'];
i hope it helps you
I have done a little bit of research on this, but currently I'm stuck.
My situation:
My database has a serverName, and serverBanner for each entry. When I do this following code:
function listBanner() {
include("mysql.php");
$votes = "serverVotes";
$results = mysql_query("SELECT * FROM toplist ORDER BY $votes ASC");
while($row = mysql_fetch_array($results)){
echo " " . "<img src=" . $row['serverBanner'] . " height=60 width=460 />";
}
}
If you noticed, it is pulling all the info from toplist table. I need to pull all the info from toplist table, but make it so that I can put each on if them in a table row. Right now if I did that, it would put each banner in the same table row.
Also, how would I go about implementing this into a table?
Do you mean:
<?php
echo "<tr>";
while($row = mysql_fetch_array($results)){
echo "<td>" . $row['serverName'] . "</td>";
echo "<td>" . "<img src=" . $row['serverBanner'] . " height=60 width=460 />"."</td>";
}
echo "</tr>"
?>