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>";
}
Related
I'm learning PHP right now and connecting to MySQL. I'm able to connect to a table called "info" and display the "date", "time", and "data" of each row, along with 2 extra columns that will allow the user to download the respective "data" into a txt and csv. This is where I'm completely lost on how to achieve that.
My understanding is that since it'll be a clickable link, I will have to use "href=" and will link that to a separate php that I create that will download that row's data, right? But then how does that new php file know which row to download from? I'm guessing I need to pass the row number it is to the other file?
Greatly appreciate it if anyone can lead me in the right direction or have examples. Thanks!
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT date, time, data FROM info";
$result = $conn->query($sql);
echo "<table border='1'>";
echo "<tr><td> Date </td><td>Time</td><td>Data</td><td> Download text </td><td> Download csv</td>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["date"]. "</td><td>" . $row["time"]. "</td><td>" .$row["data"] ."</td><td><a href='NEEDTXTFILE.php'>".$row["date"].'.txt'. "</a></td>"."<td><a href='NEEDCSVFILE.php'>".$row["date"].'.csv'. "</a></td> ";
echo "</tr>";
}
echo "</tr>";
echo "</table>";
} else {
echo "0 results";
}
Assuming you select also the id value
$sql = "SELECT id, date, time, data FROM info";
....
you could add the id to your href eg:
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["date"]. "</td><td>" .
$row["time"]. "</td><td>" .
$row["data"] .
"</td><td><a href='NEEDTXTFILE.php?id=" . $row["id"] . "'>".
$row["date"].'.txt'. "</a></td>"."<td><a href='NEEDCSVFILE.php'>".
$row["date"].'.csv'. "</a></td> ";
echo "</tr>";
}
then in your NEEDTXTFILE.php you can obtain the id in $_GET['id']
Ok i am playing around with this idea for a system i am working on. I want to display data from mysql into a table. I can do this easy. What i would like to do is this. For the ID i would like to make it a link where i pass the id to the next page.
<?php
$con=mysqli_connect("example.com","username","password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Address</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Address'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
What i want to do is in the (echo "" . $row['ID'] . "";) I would like to convert it to a link so it would be something like this: example.com/report.php=24 or something like that. What i need to do is find out how to pass the ID and also how to convert the echo to a hyperlink.
Also on the report page it will display all data for id=24 or what ever the id is into a form that i have setup.
Can anyone help me with this.
Try This
echo '
<td>'.$row["ID"].' </td>';
To make a clickable link you use an anchor tag <a></a> In the href attribute you add the form name report.php and follow that with a ? to seperate that from the parameter list. You then add name=value pairs after the ? for the data you wish to pass eg href="report.php?id=24"
So to make the first page contain a clickable link you do something like this
echo '<td><?php echo $row['ID']; ?></td>';
Now in the report.php script you access the passed data by looking at the $_GET array in PHP
<?php
// check incoming params exist
if ( ! isset($_GET['id'] ) {
// missing param, go to an error page for example
header('Location: error.php');
exit;
}
// You can now use $_GET['id'] which will be the id number passed
// any way you want.
// For example using a PDO connection called $pdo
$table = "table1";
$sql = "SELECT * FROM $table WHERE id = :id";
try {
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->FetchAll(); // $rows now contains all the results of the query
}
catch( PDOException $e) {
echo $e-getMessage();
}
foreach ( $rows as $row ) {
// do things with the $row['column_name'] data
}
I always prefer using direct HTML for something like this.
<td>Link Name</td>
Try this -
while($row = mysqli_fetch_array($result))
{
$link = "example.com/report.php?id=".$row['ID'];
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Address'] . "</td>";
echo "</tr>";
}
echo "</table>";
Update post for: Increase in Value button
I made a post asking about how make an increase value button. I got one decent answer, I tried it and it didn't work.
Original:
$result = mysqli_query($con, "SELECT * FROM champion_counters_b WHERE champion_name='" . $search_result . "'");
echo "<table class='champion_counters' border='1'><tr><th>Champion Counter</th><th>Up Votes</th><th>Down Votes</th></tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['champion_counter'] . "</td>";
echo "<td>" . $row['upvotes'] . "</td>";
echo "<td>" . $row['downvotes'] . "</td>";
}
echo "</table>";
Current:
$result = mysqli_query($con, "SELECT * FROM champion_counters_b WHERE champion_name='" . $search_result . "'");
echo "<table class='champion_counters' border='1'><tr><th>Champion Counter</th><th>Up Votes</th><th>Down Votes</th></tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['champion_counter'] . "</td>";
echo "<td><a href='action.php?do=up&id=" . $row['upvotes'] . "'>Upvote [" . $row['upvotes'] . "]</a></td>";
echo "<td><a href='action.php?do=down&id=" . $row['downvotes'] . "'>Downvote [" . $row['downvotes'] . "]</a></td>";
}
echo "</table>";
mysqli_close($con);
?>
action.php:
$action = $_GET['do'];
$id = $_GET['id'];
if ($action=="up") {
$result = mysqli_query($con, "UPDATE champion_counters_b SET" . $id . "=" . $id+1 . "'");
}
elseif ($action=="down") {
$result = mysqli_query($con, "UPDATE champion_counters_b SET" . $id . "=" . $id-1 . "'");
}
else {echo "error: 002 / voting error";}
mysqli_close($con);
?>
As you can see I implemented the changes that were recommended and that could of worked, but they didn't rather than updating the data it did nothing. As when pressing "upvote"/"downvote" it grabbed the current value as $id rather than the position of the data to update it.
tl;dr: I tried a fix from the previous thread, it didn't do anything. Help please?
sorry if I have been unclear, let me give it another try:
You insert a link into your table, which calls an action.php. The action.php updates the database. The information needed for updating are passed as GET-parameters.
For updating the database, you will need to know WHAT to do, and secondly, WHICH database entry is actually affected.
Step by step:
First, you have to insert the links into your table:
$result = mysqli_query($con, "SELECT * FROM champion_counters_b WHERE champion_name='" . $search_result . "'");
echo "<table class='champion_counters' border='1'><tr><th>Champion Counter</th><th>Up Votes</th><th></th><th>Down Votes</th><th></th></tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['champion_counter'] . "</td>";
echo "<td>" . $row['upvotes'] . "</td>";
echo "<td><a href='action.php?do=up&id=" . $row['key'] . "'>Upvote</a></td>";
echo "<td>" . $row['downvotes'] . "</td>";
echo "<td><a href='action.php?do=down&id=" . $row['key'] . "'>Downvote</a></td>";
echo "</tr>";
}
echo "</table>";
On clicking the link, we are sending two pieces of information to the action.php.
The action we have to perform, either up- or downvoting. It tells us WHAT to do.
The id of the element we have to up- or downvote. The id tells us WHICH element is affected, and not the number of votes an element has.
As mentioned in my answer to your previous post, $row['key'] should contain the primary key of your database, e.g. an unique identifier. You should have such an identifier in your database, otherwise you cannot make a reference to a specific database entry. However, as we want to update the vote count for a very specific database entry, we need a possibility to uniquely identify this database entry.
In your action.php, you have to do the following:
$action = $_GET['do'];
$id = $_GET['id'];
if ($action=="up") {
mysqli_query($con, "UPDATE champion_counters_b SET upvotes = upvotes + 1 WHERE key = " . $id . "'");
}
elseif ($action=="down") {
mysqli_query($con, "UPDATE champion_counters_b SET downvotes = downvotes - 1 WHERE key = " . $id . "'"); }
else {echo "error: 002 / voting error";}
mysqli_close($con);
We use the id value to select the database entry we have to update. This is done by WHERE key = $id in the UPDATE-statement. The current vote count is taken from the database itself - there is no need to pass the current vote count in the GET-parameters.
After you have updated your database, you can redirect to the original page and reload your table. Then, the updated vote count should show up.
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.
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>"
?>