Displaying Image From URL Stored in SQL Databse Using PHP - php

I'm trying to display images from a SQL Database (using an URL in the DB) in a table.
I'm still pretty new to this type of implementation so I've been giving it my best shot and trying to do research but haven't found much on using URLs (opposed to using BLOBs or directly adding images to the Database). I definitely WANT to keep my images on a file system. Currently my code only displays the URL (obviously) but I have tried a few things..
I have tried:
-Passing $row["card_image"] to a PHP variable $image and using $image->load()
-Using "<img src="$row["card_image"]">" (I imagined since I was getting a link output still this could work...)
-I have also tried a few other solutions that I've found on Stack Overflow but I believe these have mostly been for use with BLOB data types and so they also failed to produce the output I desire (I.E.
"<img src="data:image/jpeg;base64,'.base64_encode($image->load())'" />"
Here is my current code:
SQL (I have condensed the fields to save space)
CREATE TABLE cards (
card_image VARCHAR(999)
);
insert into cards (card_image)
values ('http://localhost/dbztc/wp-content/uploads/2016/04/1.jpg');
PHP
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
if(!$conn)
{
die("connection failed");
}
//Table
echo "
<table cellpadding=\"0\" cellspacing=\"2\" border=\"0\" width=\"100%\">
<tr bgcolor=\"#666666\">
<td colspan=\"5\" align=\"center\"><b><font color=\"#FFFFFF\">" . $table[0] . "</font></td>
</tr>
<tr>
<td>Image</td>
<td>Card Number</td>
<td>Card Rarity</td>
<td>Card Name</td>
<td>Card Type</td>
<td>Card Style</td>
<td>Card Text</td>
</tr>";
$sqlquery = "SELECT card_image, card_number, card_rarity, card_title, card_type, card_style, card_text FROM cards";
$result = mysqli_query($conn, $sqlquery);
//$image = $row["card_image"];
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<td>" . $row["card_image"] . "</td>" . "<td>" . $row["card_number"]. "</td>" . "<td>" . $row["card_rarity"] . "</td>" . "<td>" . $row["card_title"] . "<td>" . $row["card_type"] . "</td>" . "<td>" . $row["card_style"] . "</td>" . "<td>" . $row["card_text"] . "</td></tr>";
}
} else {
echo "0 results";
}
echo "</table>";
mysqli_close($conn);

Instead of:
<td>" . $row["card_image"] . "</td>
Try:
$image = $row["card_image"]; // the image url
<td><img src='". $image . "'></td>

For anyone who stumbles upon this and may be having this same problem:
For starters, I took the entire URL out of the database entry and replaced it with the Filename only.
Afterwards, I edited my code like this:
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<td>" . "<img src ='../images/" . $row["card_image"] . "'>" . "</td>" . "<td>" . $row["card_number"]. "</td>" . "<td>" . $row["card_rarity"] . "</td>" . "<td>" . $row["card_title"] . "<td>" . $row["card_type"] . "</td>" . "<td>" . $row["card_style"] . "</td>" . "<td>" . $row["card_text"] . "</td></tr>";
echo "<br />";
It now displays perfectly. Just as a note, this was done on a live server opposed to local so that could maybe also have an impact? Not sure, but hopefully this can help someone!

Related

PHP SQL Returning only one result

Im trying to migrate my website from my local wamp project to my live server for testing, everything is working fine on my local site but on my live site the following code only returns one result. There are definitely multiple SQL entries that meet the sql query criteria. Any suggestions?
$opentickets = $db->query("SELECT tID, id, date, userid, category, department FROM ticket WHERE userid = '$_SESSION[id]' AND status='Open'");
if(count($opentickets) > 0) {
echo "<h2>Your open tickets:</h2>";
echo "<table class='table table-striped'>
<tr>
<th>Ticket</th>
<th>Date Submitted</th>
<th>Category</th>
<th>Department</th></tr>";
$o = $opentickets->fetch(PDO::FETCH_ASSOC);
echo "<tr><td><a href='ticket.php?id=" . $o['tID'] . "'>" . $o['tID'] . </td>";
echo "<td>" . $o['date'] . "</td>";
echo "<td>" . $o['category'] . "</td>";
echo "<td>" . $o['department'] . "</td></tr>";
echo "</table>";
}
else
{
echo "<h2>You have no open tickets</h2>";
}
You are not itterating over the results of your query, you are just fetching the first row...
Please reference to the examples on the PHP Website on how to do this.
I have just changed your code below, please check for the manuals for more information
while($o = $opentickets->fetch(PDO::FETCH_ASSOC)){
echo "<tr><td><a href='ticket.php?id=" . $o['tID'] . "'>" .$o['tID'] . </td>";
echo "<td>" . $o['date'] . "</td>";
echo "<td>" . $o['category'] . "</td>";
echo "<td>" . $o['department'] . "</td></tr>";
}

Neither tablesorter nor dataTables working with ajax

I have tried both, tablesorter and datatables in order to get sorting functionalities. With both, I'm able to see the sorting arrows (and filter box, pages... with dataTables; although they don't work neither), and they change, but the data are not sorted.
Here is the ajax (with dataTables it's the same but using 'dataTable' instead of 'tablesorter'.
$.ajax({
type: "GET",
url: "search.php",
data: {data : encrypted.data, salt: enc_salt},
success: function(enc_response){
var response = decrypt_cryptojs(enc_response, encrypted.salt);
var data = JSON.parse(response);
$("#search_result").html(data);
// Initialise tablesorter
$('#search_table').tablesorter();
}
});
I create the table with php:
if (mysqli_num_rows($result) > 0) {
$message .= "<table id='search_table' class='tablesorter'>
<thead><tr>
<th id='search_user'>Usuario</th>
<th id='search_name'>Nombre</th>
<th id='search_surnames'>Apelidos</th>
<th id='search_email'>Correo</th>
<th id='search_role'>Rol</th>
<th id='search_access'>Acceso</th>
<th id='search_center'>Centro</th>
<th id='search_edit'></th>
<th id='search_delete'></th>
</tr></thead>";
while ($row = mysqli_fetch_row($result)) {
// Define $id
$id = $row[7];
// Replace space(" ") whith "&#32" to avoid errors inside functions
$user = str_replace(" ", "&#32", $row[0]);
$name = str_replace(" ", "&#32", $row[1]);
$surnames = str_replace(" ", "&#32", $row[2]);
$center = str_replace(" ", "&#32", $row[6]);
$message .= "<tbody><tr>
<td>" . $row[0] . "</td>" .
"<td>" . $row[1] . "</td>" .
"<td>" . $row[2] . "</td>" .
"<td>" . $row[3] . "</td>" .
"<td>" . $row[4] . "</td>" .
"<td>" . $row[5] . "</td>" .
"<td>" . $row[6] . "</td>" .
"<td>" .
"<input type='image' src='../resources/edit.png' id='edit_" . $row[0] . "' class='edit' onclick=edit_user(\"$user\",\"$name\",\"$surnames\",'$row[3]','$row[4]','$row[5]',\"$center\",'$id') title='Editar'></button>" .
"</td>" .
"<td>" .
"<input type='image' src='../resources/delete.png' id='delete_" . $row[0] . "' class='delete' onclick=delete_user('$user','$row[4]') title='Eliminar'></button>" .
"</td>
</tr>";
}
$message .= "</tbody></table>";
$message .= "<div id='modify_panel'></div>";
}
And after that:
// Encode the message using json
$response = json_encode($message);
// Encrypt the response and send it.
$enc_response = encrypt_cryptojs($response, $salt);
echo $enc_response;
With datatables I can see message saying that I have an invalid json response.
"#search_result" is in a php file that is included into another php file.
What I'm doing wrong?
Thank you.
EDIT: I've found the stupid mistake, I was generating several tbodys. If I move the tag outside the while, it works. Sorry.
It looks like the problem is likely in the encoding and processing of the JSON.
JSON cannot be merely a string. It needs to be wrapped in an array or object, so when you use php json_encode make sure it's getting an array
// Encode the message using json
$response = json_encode(array($message));
Note: I don't know php that well, so this example might be wrong.
Now in the javascript, make sure to get the data from the first element of the array
var data = JSON.parse(response)[0];
Now the data should be ready to be added as HTML.
$("#search_result").html(data);

Expand Table Row with Additional information Fetched from Database

Here is a little demonstration of what I want achieved.
What I want, is a clickable row with additional information fetched from the database.
I've seen some examples with Jquery, but those have some kind of static information in the expanded area. I want to load in this additional information, only after the row is clicked - so I wont have to load in too much information that might not be used.
Now, inside the expanded area, I need the additional information to be fetched like:
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['manufacturer'] . "</td>";
echo "<td>" . $row['describtion'] . "</td>";
echo "<td>" . $row['rdate'] . "</td>";
echo "<td>" . $row['locked'] . "</td>";
echo "</tr>";
}
But only if a specific row is clicked.
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("phone", $con);
$result = mysql_query("SELECT * FROM info");
echo "<table border='1'>
<tr>
<th>Model</th>
<th>Software</th>
<th>Carrier</th>
<th>Price</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['model'] . "</td>";
echo "<td>" . $row['os'] . "</td>";
echo "<td>" . $row['carrier'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
I have really done extensive searching, but that didn't get me closer to a solution.
Would it be better if I added HTML to the code, and somehow fetched the data inside the td tags?
I ended up using Datagrid.
It has the exact functionality I was looking for, and alot of tutorials to get you started.
http://www.jeasyui.com/tutorial/datagrid/datagrid21.php

SQL removing data from an array depending on field value

I'm still quite new to this and have come across a problem I have been looking through a lot of tutorials and cannot figure a way to get over the problem.
I have a select query getting data out of my sql database however I need the data to be custom for each user who accesses it, so need to add a further query, I have a cookie read in with the user value '$user' and there is a collumn in the database that isnt put into the table however need to check that if the collumn 'privacy' has a value set as '1' and the $user is not the investigator of that row discard and do not put into the table. however populate with all data that isn't set to privacy='1' or is set to privacy=1 and the investigator='$user'
$sql="SELECT * FROM evidence WHERE $evidencevariable = '".$evidencespecify."'";
$result = mysql_query($sql);
if($result === FALSE) {
die(mysql_error());}
echo "<table class='sortable' border='1' id='table'>
<thead><tr>
<th>Id</th>
<th>Case Id</th>
<th>Investigator</th>
<th>Evidence Type</th>
<th>Created</th>
<th>Modified</th>
<th>LS</th>
<th>PS</th>
<th>Length</th>
<th>Importance</th>
<th>Information</th>
</tr></thead><tbody>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Id'] . "</td>";
echo "<td>" . $row['Case_ID'] . "</td>";
echo "<td>" . $row['Investigator'] . "</td>";
echo "<td>" . $row['Evidence_Type'] . "</td>";
echo "<td>" . $row['Created'] . "</td>";
echo "<td>" . $row['Modified'] . "</td>";
echo "<td>" . $row['LS'] . "</td>";
echo "<td>" . $row['PS'] . "</td>";
echo "<td>" . $row['Length'] . "</td>";
echo "<td>" . $row['Importance'] . "</td>";
echo "<td>" . $row['Information'] . "</td>";
echo "</tr>";
}
echo "</tbody></table>";
How can I get around this problem do I need to add more to the select statement at the beginning or is there a way of querying the array to remove the data before its put into the table?
Any help would be appreciated!
It seems you can easily modify the sql to something like:
$sql="SELECT * FROM user WHERE $evidencevariable='$evidencespecifiy' AND (Privacy=0 or (Privacy=1 AND investigator='$user'))";

Using PHP forms in mysql queries

Another (basic) question here. I need to know how to use html forms to filter the results of a mysql query using PHP. I have been looking at w3schools and I can see how using $_POST on one page can output to another page. But I cannot see exactly how to put the $_POST into my query. For example I have one page as below:
<form action="orderlist.php" method="post">
OrderNo: <input type="int" name="order_no" />
<input type="Submit" />
</form>
This is a page where the user can enter an order_no and click submit, which links to the 'orderslist.php' page. On that page I have the following code:
$result = mysql_query("SELECT * FROM orders");
echo "<table border='5'>
<tr>
<th>order_no</th>
<th>ord_date</th>
<th>est_completion_date</th>
<th>status</th>
<th>invoice_date</th>
<th>inv_amount</th>
<th>name</th>
<th>fName</th>
<th>lName</th>
</tr>";
// -- Use 'while' to check each row in $result in turn:
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['order_no'] . "</td>";
echo "<td>" . $row['ord_date'] . "</td>";
echo "<td>" . $row['est_completion_date'] . "</td>";
echo "<td>" . $row['status'] . "</td>";
echo "<td>" . $row['invoice_date'] . "</td>";
echo "<td>" . $row['inv_amount'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['fName'] . "</td>";
echo "<td>" . $row['lName'] . "</td>";
echo "</tr>";
}
echo "</table>";
This outputs everything from 'orders' into a table, but I want it to only output the row with the order_no that the user entered on the previous page. How do I do this? Is it something like:
$result = mysql_query("SELECT * FROM orders WHERE order_no = $_POST[order_no]");
Thank a lot
For starters, you should switch to PDO or mysqli -- the mysql_* functions are in the process of deprecation.
On to your question: yes, that's how you do it, with a WHERE clause. However, it is very (very very very) insecure to concatenate a variable directly out of $_POST without sanitation.
That said, at a minimum you should do this:
mysql_query('SELECT * FROM orders WHERE order_no = '.mysql_real_escape_string($_POST[order_no]));
Another thing... don't use SELECT *. You should always list the columns you expect to get from the database -- that way, if there is a problem (like the columns have changed), the query can let you know. With SELECT * you get back a magical grab-bag of data -- you have no idea what it is, and more importantly, if it has the values your code relies on.
So, putting it together:
$pdo = new PDO("mysql:host=localhost;dbname=database", '-username-', '-password-');
$sth = $pdo->prepare('
SELECT
`order_no`,
`ord_date`,
`est_completion_date`,
`status`,
`invoice_date`,
`inv_amount`,
`name`,
`fName`,
`lName`
FROM
orders
WHERE
order_no = :order_no
');
$sth->execute(array(':order_no'=>$_POST[order_no]));
while ($order= $sth->fetch()) {
echo "<tr>";
echo "<td>" . $order->order_no . "</td>";
echo "<td>" . $order->ord_date . "</td>";
echo "<td>" . $order->est_completion_date . "</td>";
echo "<td>" . $order->status . "</td>";
echo "<td>" . $order->invoice_date . "</td>";
echo "<td>" . $order->inv_amount . "</td>";
echo "<td>" . $order->name . "</td>";
echo "<td>" . $order->fName . "</td>";
echo "<td>" . $order->lName . "</td>";
echo "</tr>";
}
Edit: One last note, the input you're using is not valid; type="int" is not a recognized input type. Here's a list of types for HTML 4, and a list for HTML 5:
As you can see, HTML 5 does have a new input type "number". It is not fully adopted, but if you wanted to use it:
<input type="number" name="order_no" />
Be aware, however, that not all browsers will restrict the input to numeric: http://caniuse.com/#feat=input-number
Documentation
mySql SELECT - http://dev.mysql.com/doc/refman/5.0/en/select.html
mysql_query (DEPRECATED) - http://php.net/manual/en/function.mysql-query.php
PDO - http://www.php.net/manual/en/book.pdo.php
PDO::prepare - http://www.php.net/manual/en/pdo.prepare.php
PDOStatement::fetch - http://www.php.net/manual/en/pdostatement.fetch.php
PDOStatement::execute - http://www.php.net/manual/en/pdostatement.execute.php
Without injection vulnerability (require 'mysql_connect' before) :
if(isset($_POST['order_no']))
{
$orderNo = mysql_real_escape_string($_POST['order_no']);
$result = mysql_query("SELECT * FROM orders WHERE order_no = $orderNo");
echo "<table border='5'>";
echo " <tr>";
echo " <th>order_no</th>";
echo " <th>ord_date</th>";
echo " <th>est_completion_date</th>";
echo " <th>status</th>";
echo " <th>invoice_date</th>";
echo " <th>inv_amount</th>";
echo " <th>name</th>";
echo " <th>fName</th>";
echo " <th>lName</th>";
echo " </tr>";
if(mysql_num_rows($result) == 0)
{
echo '<tr><td colspan="9">Order not found</td></tr>';
}
else
{
while($row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo " <td>" . $row['order_no'] . "</td>";
echo " <td>" . $row['ord_date'] . "</td>";
echo " <td>" . $row['est_completion_date'] . "</td>";
echo " <td>" . $row['status'] . "</td>";
echo " <td>" . $row['invoice_date'] . "</td>";
echo " <td>" . $row['inv_amount'] . "</td>";
echo " <td>" . $row['name'] . "</td>";
echo " <td>" . $row['fName'] . "</td>";
echo " <td>" . $row['lName'] . "</td>";
echo "</tr>";
}
}
echo "</table>";
}
Try this:
$orderNumber = mysql_real_escape_string($_POST['order_no']);
$result = mysql_query("SELECT * FROM orders WHERE order_no = $orderNumber");
This takes the value of $_POST['order_no'] and somewhat sanitizes it. You then apply the value of $orderNumber to MySQL.
However, you're much better off using PDO or MySQLi. Both protect you (if used correctly) from SQL injection. Currenly, your code is VERY prone to SQL injection.
Your form should be something like this:
<form action="orderlist.php" method="post">
OrderNo: <input type="text" name="order_no" />
<input type="Submit" value="Submit"/>
</form>
To get any value that is typed by user in the form you should use type="text".
There is nothing like type="int" in standard HTML.
Don't get confused, the Input TYPE in HTML is not the same as one you use in Programming languages to declare Data type. Here TYPE is just to let the browser know that its a text field / Radio Button etc.
To understand Valid Input Types better read this w3.org recommendation on HTML forms.
On orderlist.php you can query to retrieve the required data:
if(isset($_POST['order_no'])) {
$orderNo = mysql_real_escape_string($_POST['order_no']);
$result = mysql_query("SELECT * FROM orders WHERE order_no = $orderNo");
while($row = mysql_fetch_array($result)) {
//code to print table.
}
}
Note:
This type of code is Vulnerable to easy attacks, and it is never recommended to put user input directly into SQL query, it should always be filtered first.

Categories