PHP download a specific row from database table - php

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']

Related

Getting URL for Image stored in MySQL as a blob

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>";
}

How to update a specific sql row from a html table

So I have a HTML table that grabs SQL data and shows the data in the HTML table. I have a button in the HTML table aswell witch reredicts to update.php. Here I want the row that the user pressed the button in updates the column "paid" to "Paid". Screenshot of the HTML table: https://emildeveloping.com/screenshots/outredden-pardonableness-amharic.png
The thing is that I can't get it working that it updates just that specific row, it updates all rows right now.
Ive tried searching around for same questions but haven't found any solutions.
This is the PHP code:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "emildeveloping2";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE purchases SET paid='Paid'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
This is the PHP snippet of the HTML Table
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table id='purchases' class='purchases'><tr class='header'><th>Invoice ID</th><th>Customer ID</th><th>Product</th><th>Name</th><th>Email</th><th>Adress</th><th>Security Number</th><th>City</th><th>Zip Code</th><th>Country</th><th>Cost</th><th>Payment Plan</th><th>Status</th><th>Options</th></tr>";
// Visa datan
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["customerid"]. "</td><td>" . $row["product"]. "</td><td>" . $row["name"]. "</td><td>" . $row["email"]. "</td><td>" . $row["adress"]. "</td><td>" . $row["securitynumber"]. "</td><td>" . $row["city"]. "</td><td>" . $row["zipcode"]. "</td><td>" . $row["country"]. "</td><td>" . $row["cost"]. "</td><td>" . $row["paymentplan"]. "</td><td>" . $row["paid"]. "</td><td><a class='fas fa-check-square' href='update.php'></a></td></tr>";
}
echo "</table>";
} else {
echo "There is no active calls.";
}
I want just a specific row to update where id = id.
You need to update two things:
Add the id of the row you want to update as a GET argument in the link so it is passed to PHP script:
<a class='fas fa-check-square' href='update.php?row_id='.$row["id"].'>
Now if you check the links, each of them should be unique: update.php?row_id=1, update.php?row_id=2, etc.
Handle this added url parameter in the PHP script so it is used to select desired
row in database table:
$sql = "UPDATE purchases SET paid='Paid' WHERE id=".$_GET['row_id'];
If you get it working use http://php.net/manual/en/mysqli.prepare.php prepare method instead of query, so your code is not prone to sql injecton.
Something like this:
$mysqli->prepare("UPDATE purchases SET paid='Paid' WHERE id=?")) {
$stmt->bind_param("i", $_GET['row_id']);
$stmt->execute();
Another thing would be using POST requests instead of GET links to prevent CSRF vulnerability.

$.get gives no error but doesn't work

I'm trying to create an employee management system, and right now I managed to create a table populated with some database content.
Now what I want is to delete the selected row on click of a button situated at the end of every row.
To do that I'm trying to use the Jquery $.get method, which calls a file named delete.php, that will do the job, and then animate and remove the row from the html.
The problem is: the animation starts, but the php file doesn't remove the record from the database! I even tried to console.log for errors, but as you can see in the below screenshot, it just gives me the html code of the page instead of an error code...
screenshot
here's the code I used to generate the table:
<?php
$sql = "SELECT * FROM dipendente";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table class='table table-striped table-hover'>".
"<thead>".
"<tr>".
"<td>id</td>".
"<td>nome</td>".
"<td>cognome</td>".
"<td>impiego</td>".
"<td>permessi</td>".
"<td>contratto</td>".
"<td>inizio</td>".
"<td>fine</td>".
"<td>edit</td>".
"</tr>".
"</thead>";
echo "<tbody>";
// output data of each row
while($row = $result->fetch_assoc()) {
$id = $row["id"];
echo "<tr id=".$row["id"].">".
"<td>" . "#". $row["id"]. "</td>" .
"<td contenteditable='false'>" . $row["nome"]. "</td>".
"<td contenteditable='false'>" . $row["cognome"] . "</td>".
"<td contenteditable='false'>" . $row["impiego"] . "</td>".
"<td contenteditable='false'>" . $row["permessi"] . "</td>".
"<td contenteditable='false'>" . $row["contratto"] . "</td>".
"<td contenteditable='false'>" . $row["inizio"] . "</td>".
"<td contenteditable='false'>" . $row["fine"] . "</td>".
"<td>" .
"<span class='glyphicon glyphicon-pencil' aria-hidden='true'></span>" .
" " .
"<span class='glyphicon glyphicon-remove-sign' aria-hidden='true'></span>" .
"<a href='#' id='$id' class='delete'><span class='glyphicon glyphicon-trash' aria-hidden='true'></span></a>".
" ".
"<span class='glyphicon glyphicon-ok-sign' aria-hidden='true'></span>".
"</td>".
"</tr>";
}
echo "</tbody>";
echo "</table>";
} else {
echo "0 results";
}
here is my jquery code:
$(".delete").click(function(){
var del_id = $(this).attr("id");
var tr = $(this).parent().parent();
console.log(del_id);
console.log(tr);
$.get("php/delete.php", { id: del_id } , function(error){
//console.log(error);
tr.fadeOut("1s",function(){
$(this).remove();
});
});
});
and there's my delete.php code:
<?php
$id = $_GET['del_id'];
$dbc = mysqli_connect('localhost', 'root', 'root', 'gestione_personale') or die('Connection error!');
$query = "DELETE FROM dipendente WHERE id = '$id'";
mysqli_query($dbc, $query) or die('Database error!');
header('location:../index.php');
Am I doing something wrong?
Based on what I see I'm going to give this answer. But you really need to get off using mysqli_* with the way you're using it. The answer I'm giving you is in prepare statement which is much more secure than the way you're using it.
$dbc = mysqli_connect('localhost', 'root', 'root', 'gestione_personale') or die('Connection error!');
$query = $dbc->prepare("DELETE FROM dipendente WHERE id = ?");
$query->bind_param("i", $_GET['id']);
if($query->execute()){
header('location:../index.php');
}else{
die('Database error!')
}
Hope this works for you.
Try access in URL delete.php passing del_id as arg, like this: delete.php?del_id=1
Then you'll see if the record is deleted or if you get some error, also check if php display_errors is enabled.

php mysql table creation on web browser need to add in headings

//replace the following with your details. Dbname is your username by default.
$con = mysqli_connect("info20003db.eng.unimelb.edu.au","geehwank","2058","geehwank");
// Check connection
if (mysqli_connect_errno()) {
echo "Could not connect to MySQL for the following reason: " . mysqli_connect_error();
}
/* this lists the name and release date of all action movies */
echo "<table border='1'>";
$result = mysqli_query($con,"SELECT name, release_date FROM Movie WHERE genre = 'action'");
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td><td>" . $row['release_date'] . "</td>";
echo "</tr>";
}
mysqli_close($con);
This code is from my uni
and it reads in tables from mysql
and displays them in a table
im a php noob
ive been trying to add headnings to the table called
name, releasedate
how can i do this in code??
can anyone help??
Here you go:
echo "<table border='1'><thead><tr><th>Name</th><th>Release Date</th></tr></thead><tbody>";
$result = mysqli_query($con,"SELECT name, release_date FROM Movie WHERE genre = 'action'");
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td><td>" . $row['release_date'] . "</td>";
echo "</tr>";}
mysqli_close($con);
?>
</tbody></table>
Try as below :
<html>
<head><title>Lab F</title></head>
<body>
<h1> Lab F - SELECT Example</h1>
<p>
This PHP code runs an SQL query, and displays the answers in an HTML table.
</p>
<p>
<br>
<?php
//replace the following with your details. Dbname is your username by default.
$con = mysqli_connect("info20003db.eng.unimelb.edu.au","geehwank","2058","geehwank");
// Check connection
if (mysqli_connect_errno()) {
echo "Could not connect to MySQL for the following reason: " . mysqli_connect_error();
}
/* this lists the name and release date of all action movies */
echo "<table border='1'>";
$result = mysqli_query($con,"SELECT name, release_date FROM Movie WHERE genre = 'action'");
echo "<tr><td>Name</td><td>Release Date</td></tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td><td>" . $row['release_date'] . "</td>";
echo "</tr>";}
mysqli_close($con);
?>
</table>
</body>
</html>

PHP / MySQL: How to store Select results in array

I am new to PHP and MySQL and hope someone can help me with this.
I have a MySql db with a table "TranslationsMain" and the following PHP query.
This returns all the items from column "German" (incl. the corresponding ID) from the db table and works correctly so far.
Instead of echoing the whole list (I just did this here for testing), **how can I store the results in an array in a way that each item within the array is stored with its value and a unique ID + how I can I echo specific items from this array by referring to their ID ?
Example:
I would like to echo the item value for ID "xyz" from this array (without calling the db again since this will be needed for multiple items on the page).
My PHP:
<?php
require_once("includes/header.php");
$tblTranslations = "TranslationsMain";
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM " . $tblTranslations;
$translations = $conn->query($sql);
// for testing only
if($translations->num_rows > 0){
echo "<table><tr><th>ID</th><th>Translation</th></tr>";
while($translation = $translations->fetch_assoc()){
echo "<tr><td>" . $translation["ID"] . "</td><td>" . $translation["German"] . "</td></tr>";
}
echo "</table>";
}else{
echo "0 results";
}
$conn->close();
?>
Update:
What I am looking for here is how to create a two dimensional array and how to fetch from it.
Many thanks in advance,
Mike
if($translations->num_rows > 0){
$result_arr = array();
echo "<table><tr><th>ID</th><th>Translation</th></tr>";
while($translation = $translations->fetch_assoc()){
echo "<tr><td>" . $translation["ID"] . "</td><td>" . $translation["German"] . "</td></tr>";
$result_arr[] = $translation;
}
echo "</table>";
}else{
echo "0 results";
}
// now you can iterate $result_arr
foreach($result_arr as $row){
echo "<tr><td>" . $row["ID"] . "</td><td>" . $row["German"] . "</td></tr>";
}

Categories