Displaying an image with PHP from a database - php

I have a problem displaying images for URLs that are saved in a database.
This is my HTML source code:
<div id="posts">
<img id="images" src="php/getImage.php?id=1">
<footer>
<a href="php/getImage.php?id=1" download><p>Download</p></a>
</footer>
</div>
And my getImage.php file:
<?php
$id = $_GET['id'];
$db = mysqli_connect("host", "username", "password", "DB name");
$sql = "SELECT image FROM images WHERE imageID=$id";
$result=mysql_query($sql);
mysql_fetch_array($result);
echo "images/$result";
?>

You have multiple problems here:
1) STOP using Mysql_ functions and use ONLY mysqli_ functions (or PDO) . Mysql_ PHP funtions are deprecated and no longer supported (and hasn't been for 5+ years!). It is insecure and will only get worse.
2) Your PHP file is simply echo'ing a string, images/someimagename.jpg; this is not what an image file is, you need to output the contents of this filename string.
3) Your current SQL is prone to SQL injection and is currently extremely insecure. Your database can be easily corrupted/abused by nefarious web page visitors.
4) Your mysqli_fetch_array needs to be assigned to a variable for the values in the array to be used.
5) Use single quotes rather than double quotes for your DB authentication so that special characters (such as$) - especially in passwords - are not misinterpreted by PHP.
Solution to the above problems:
<?php
// id is assumed to be an integer value.
// This prevents SQL injection and database compromise by forced
// typecasting of the data to integer.
$id = (int)$_GET['id'];
$db = mysqli_connect('host', 'username', 'password', 'DB name');
$sql = "SELECT image FROM images WHERE imageID=".$id." LIMIT 1";
// only use mysqli_ functions.
$result=mysqli_query($db, $sql);
// assign to a $variable
$output = mysqli_fetch_array($result);
//The [ relative :( ] URL of the resoure requested:
$file = "images/".$output['image'];
// Before the data is output we need to set the correct header so the
// browser knows what sort of file to expect.
$image_mime = image_type_to_mime_type(exif_imagetype($file));
header("Content-type: " . $image_mime);
// Grab and output the raw data in the filepath stored in the URL.
print readfile($file);
// If this is the end of thefile you should not use a closing PHP tag.
// ?>
If you do not have the PHP Exif Extension enabled there are various other (possibly more verbose) ways of ouputting the image type using fileinfo or mime_content_type.
PLEASE NOTE:
Your image URL is relative so, as the file getImage.php is in the php folder, the image requested will be in the php/images/<filename> path. If this is NOT where your images are stored, then you need to adjust your image path URL and make it either correct, or use absolute HTML pathing which is HIGHLY recommended.

The code posted with the question has used mysql_query / mysql_fetch_array which is deprecated to use in PHP anymore. Even with deprecated mysql_* version, this part
mysql_fetch_array($result);
echo "images/$result";
of posted code should be
$row = mysql_fetch_array($result, MYSQL_ASSOC);
echo "images/".$row["image"];
(I haven't tested this code as PHP version in my machine is above 5.5 which doesn't support mysql_* extensions).
Each row requires being fetched from the result ($result) of SQL query. From the fetched row ($row) each cell can be accessed using the column header (image).
Try following code in getimage.php,
<?php
$id = $_GET['id'];
$db = new mysqli("host", "username", "password", "DB name");
$sql = "SELECT image FROM images WHERE imageID=$id";
$result=$db->query($sql);
$row = $result->fetch_assoc();
echo 'images/'.$row['image'];
?>
FYI, mysqli supports both procedural and object-oriented programming paradigm. http://php.net/manual/en/mysqli.quickstart.dual-interface.php

Related

Unable to login with email or mobile

I am trying to login with email or mobile (in PHP and MySQL). But I am unable to login.
Here is my code:
$sql = "SELECT * FROM tb_users WHERE (email='$loginEmailOrMobile' AND password='$loginPassword') OR (mobile_number='$loginEmailOrMobile' AND password='$loginPassword')";
$mysql = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($mysql) == 1)
{
echo "login successful";
$user = mysql_fetch_object($mysql);
echo $user->username;
}
else
{
die(mysql_error());
}
I think you have many problems in your code.
The mysql* extension is deprecated, and removed in PHP 7.
Plain passwords have poor security.
Prepared statements are recommanded when using variables.
You are handling an error when there is not.
You probably have no row (or more that 1) matching with your credentials so it's neither a success nor a MySQL error.
I will not cover all of this points in this answer in order to respect your original code, but I will try to explain many of them.
First, there is a tested and working code that does the job.
<?php
//Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "databaseName");
//These variables may be set from $_POST or anywhere
//it is only an example
$loginEmailOrMobile = 'an-email#example.com';
$loginPassword = '123456';
//!!Vulnerable to SQL injections**
$sql = "SELECT * FROM tb_users WHERE password = '$loginPassword' AND (email='$loginEmailOrMobile' OR mobile_number = '$loginEmailOrMobile')";
$result = $mysqli->query($sql);
//Only if we got 1 result
if (1 === mysqli_num_rows($result)) {
$user = mysqli_fetch_object($result);
echo $user->email;
} else {
die('We have not got only one result');
}
In this code you can see that:
Mysqli is used to perform the queries. It's really recommended to use mysqli instead of mysql for security reasons. Also, I'm using PHP 7 and I have not the mysql extension.
Because the case you were handling with mysql_error() was not en error, I have removed it in order to handling the case. If I get 0, or even 2 results, that's not a MySQL error, but perhaps I have no user or more than 1 with that credentials.
I have updated your SQL query in order to be less redundant but the logic is the same.
Your SQL query is not a prepared statement, I haven't touch it in order to respect your code and not to rewrite it entirely. But I really advise you to have a look at mysqli prepared statements
It seems you are currently using a plain password (unless you have already hashed it). It is recommanded to hash your passwords before inserting them into the database, and compare only the hashes. Please have a look to crypt().

Get values from query and return as array

How could I return the values from this query as an array so that I can perform an action with the array?
$sql = mysql_query("SELECT username FROM `users`");
$row = mysql_fetch_array($sql);
How would I get the code to be like the following? Here, the user1 and user2 would be the usernames of the users selected from the above query.
$userarray = array("user1","user2");
Before I point out best practices, you need working code first. So I'll give you a simple solution first.
To run a query with the mysql extension the function is mysql_query, you can't pass the query text directly to mysql_fetch_array. Nextly mysql_fetch_array doesn't do what you think it does. mysql_fetch_array combines the functionality of mysql_fetch_row and mysql_fetch_assoc together by storing the key names of the resulting columns along with their numeric indexes. The mysql_fetch_array function does not return an array with all rows from your query. To get all rows from the query, you need to run mysql_fetch_array in a loop like so:
$sql = "SELECT username FROM `users`";
$result = mysql_query($sql);
if(!$result){echo mysql_error();exit;}
$rows=array();
while($row = mysql_fetch_array($result))
{
$rows[]=$row;
}
print_r($rows);
Nextly, do note that the mysql_* functions are deprecated because the mysql extension in PHP is no longer maintained. This doesn't mean MySQL databases are deprecated, it just means the database adapter called mysql in PHP is old and newer adapters are available that you should be using instead, such as mysqli and PDO.
Next point, it is bad practice to rely upon short tags as it can be disabled by php.ini settings, always use either <?php ... ?> or <?= ... ?> for easy echoing which isn't affected by short tags.
Please read up on some mysqli or PDO simple examples to get started with one or the other. The mysqli extension is specific for MySQL while PDO (PHP Data Objects) is designed as a generic adapter for working with several kinds of databases in a unified way. Make your pick and switch so you're no longer using the deprecated mysql_* functions.
You would need to use a foreach loop to do it:
$userarray = [];
foreach($row as $single)
{
array_push($userarray, $single['username']);
}
and if can, try to use this MySQLi Class, it's very simple to get what you want from the database.
$db = new MysqliDb ('host', 'username', 'password', 'databaseName');
$userarray = $db->getValue('users', 'username', null);

Garbled UTF-8 characters in PHP

<?php
require ('sql_connect.php');
$query = "select * from `products`";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$imagem = $row['imagem'];
$texto = $row['texto'];
echo "<img src=Images/Products/$imagem> <br> $texto";
}
?>
I have the image and the text of the image that i want to show in my database.
I show the image but i have problems with the text... The text dont show the enters/spaces and the accents.
Image of problem: http://imgur.com/LHg4eK6,C7SZD4M
I want this: http://imgur.com/LHg4eK6,C7SZD4M#1
This is happening because you didn't properly set the encoding to UTF-8 (or another one that contains all characters you want to display). To do this, you need to:
Set the encoding to UTF-8 in the database itself (you can skip this step if you can see the text properly in PhpMyAdmin).
Tell PHP that you're using UTF-8. To do this, run:
mysql_query("SET NAMES utf8");
right after you connect to the database (add this line to the end of your sql_connect.php file).
Please note that you shouldn't use mysql_* functions anymore (see my comment on your question). If you switch to MySQLi, you can run this:
$db->set_charset("utf-8");
to change the charset.
See also:
UTF-8 all the way through
How can I prevent SQL-injection in PHP?

Assign MySQL database value to PHP variable

I have a MySQL Database Table containing products and prices.
Though an html form I got the product name in a certain php file.
For the operation in this file I want to do I also need the corresponding price.
To me, the following looks clear enough to do it:
$price = mysql_query("SELECT price FROM products WHERE product = '$product'");
However, its echo returns:
Resource id #5
instead a value like like:
59.95
There seem to be other options like
mysqli_fetch_assoc
mysqli_fetch_array
But I can't get them to output anything meaningful and I don't know which one to use.
Thanks in advance.
You will need to fetch data from your database
$price = mysql_query("SELECT price FROM products WHERE product = '$product'");
$result = mysql_fetch_array($price);
Now you can print it with
echo $result['price'];
As side note I would advise you to switch to either PDO or mysqli since mysql_* api are deprecated and soon will be no longer mantained
If you read the manual at PHP.net (link), it will show you exactly what to do.
In short, you perform the query using mysql_query (as you did), which returns a Result-Resource. To actually get the results, you need to perform either mysql_fetch_array, mysql_fetch_assoc or mysql_fetch_object on the result resource. Like so:
$res = mysql_query("SELECT something FROM somewhere"); // perform the query on the server
$result = mysql_fetch_array($res); // retrieve the result from the server and put it into the variable $result
echo $result['something']; // will print out the result you retrieved
Please be aware though that you should not use the mysql extension anymore; it has been officially deprecated. Instead you should use either PDO or MySQLi.
So a better way to perform the same process, but using for example the MySQLi extension would be:
$db = new mysqli($host, $username, $password, $database_name); // connect to the DB
$query = $db->prepare("SELECT price FROM items WHERE itemId=?"); // prepate a query
$query->bind_param('i', $productId); // binding parameters via a safer way than via direct insertion into the query. 'i' tells mysql that it should expect an integer.
$query->execute(); // actually perform the query
$result = $query->get_result(); // retrieve the result so it can be used inside PHP
$r = $result->fetch_array(MYSQLI_ASSOC); // bind the data from the first result row to $r
echo $r['price']; // will return the price
The reason this is better is because it uses Prepared Statements. This is a safer way because it makes SQL injection attacks impossible. Imagine someone being a malicious user and providing $itemId = "0; DROP TABLE items;". Using your original approach, this would cause your entire table to be deleted! Using the prepared queries in MySQLi, it will return an error stating that $itemId is not an integer and as such will not destroy your script.

Using content called from MySQL

I am trying to create a simple link. The issue is the file name is going to come from the database.
example: Download
I have not worked much with MYSQL and have pieced together something that is working so far
<?php
$products_id = $_GET['id'];
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$sql = "select * from znc_product_extra_fields where products_id = '" . $products_id . "'";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
echo $row['file_1'];
}
?>
When I run it it does just what I want, it echos the file name that is assigned to that specific row (item number)
But I am lost how to turn this into the link. The only thing I can think is somehow assigning this result to a variable and calling it while creating the link but I do not know how to take this result which is correct and actually use it! How would I take this filename and place in the link
Download
PHP outputs whatever you want it to - text, HTML, XML, etc. So just output the HTML. I think what you want is:
echo "Download";
Although you shouldn't be using the outdated mysql_* functions. Please see PDO (the best option) or mysqli.
To prevent SQL injection, use PDO::quote (if you are using PDO), or mysqli_real_escape_string (if you are using mysqli).
echo 'file;
Your code is vulnerable to MySQL injection. Use real_escape_string
on your GET, POST parameters.
You should use PDO (see tereško comment for reason)

Categories