Sorry for my English.
I'm learning PHP and I try to create a small member area, I think it's a good way to learn.
In my member area, some members are "verified" and some are not.
How can I display different pics based on data stored in Mysql using PHP?
What I want is to display "Picture1" if "1" is the value stored in a MySQL column and "Picture2" if "2" is the value, etc... You are "unverified member" so you see picture 1, verified member see picture 2...
I know how to SELECT data using MySQLi but I can't find what I have to do next?
Thank you.
Lets assume that you have a database named as db and table as tb with columns name and verify. Name is string and verify is Boolean. Also verify stored 1 if user is verified and 0 it isn't.
so, you can do it by iteration statements (either by using if else or by switch statements)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query="SELECT * FROM `tb`";
$sql=$conn->query($query);
if($sql->num_rows>0)
{
while($row=$sql->fetch_assoc())
{
//display name
echo $row['name'];
//check if user is verified or not
//using if else statement
if($row['verify']=="0")
{
echo '<img src="./picture1.jpg">';
}
else
{
echo '<img src="./picture2.jpg">';
}
//using switch case
switch($row['verify'])
{
case(0):
{
echo '<img src="./picture1.jpg">';
}
case(1);
{
echo '<img src="./picture2.jpg">';
}
}
//remember i have used both methods hence it will show the image twice , i did it just you possible ways , you choose any one from it.(if else or switch case)
}
}
$conn->close();
?>
There's a few ways. If it will always follow a number system... use this:
$picture = "Picture" . $verified;
// example: $picture = "Picture1", if $verified = 1
Lots of ways to concatenate...
$pic = "Picture$verified.png";
$picture = "Picture" . $verified . ".jpeg";
It will just depends on how you have it setup..
switch($verified){
case 1:
$picture = "Picture1";
break;
case 2:
$picture = "Picture2";
break;
case default:
$picture = "Picture1";
break;
}
Another way...
if($verified == 1){ $picture = "Picture1"; } else { $picture = "Picture2"; }
The reason for the switch statement, or this if/else statement is that it can account for verified being equal to 0, null, or another non 1 or 2 value that may be stored in the database for whatever reason. With the first example, if $verified (verified column = to 1 or 2) has an odd value, the picture# may not actually be real.
Now, of course this is just to handle the different ways. You would have to make sure it lines up properly with your actual image...
$picture = "Picture1"; // would be dynamic to code above
$ext = ".png"; // optional, could be added into the $picture variable above easily too
$filePath = "/images/user_uploads/"; // make sure path is correct
$filePathName = $filePath . $picture . $ext;
// see? We combine path/pictureName/extension to create an image URL
if(file_exists($filePathName) !== false){ // make sure exists
$imageCode = "<img src='$filePathName' alt='Not Found'>";
} else {
// file does not exist! ut oh!
}
It depends on how your images map to the values in your database, but assuming you have a simple relationship like:
1: /images/1.jpg
2: /images/2.jpg
Simply grab the data from your database and map it to a variable (in my example it's $image), and then concatenate it with the filepath inside an echo statement inside of an <img src> attribute:
<img src="<?php echo '/images/' $image . '.jpg'; ?>"/>
This will output:
<img src="/images/1.jpg"/>
<img src="/images/2.jpg"/>
Based on the chosen image.
Now you just have to set that variable to the right value based on your conditional:
<?php
if ($authenticated) {
$image = 1;
}
else {
$image = 2;
}
?>
<img src="<?php echo '/images/' $image . '.jpg'; ?>"/>
Or more succinctly with a ternary:
<?php ($authenticated ? $image = 1 : $image = 2) ?>
<img src="<?php echo '/images/' $image . '.jpg'; ?>"/>
Try this:
<img src="<?php echo "/pictures/Picture{$number}.jpg"; ?>" />
Related
I do not understand what is happening with my variables, the values all vanish / become empty within the function. I don't have anything within the function. I believe that I am doing the 'checks' correctly '==' and the assignments correctly '='. Regardless of what i try, i continue to get the 'file doesn't exist result'. and if i var_dump to see what the value of $cID or $check, they come back as empty ''.
function gt_masthead($cID='3', $check=false, $str=''){ //assign value to var
$check == file_exists('./' . $cID . 'bg-userProfile.jpg'); //file exists?
//echo '<h1> / ' . $cID . ' / ' . $check . ' </h1>';
dumpVar($cID); //test
if($check == 1){
// file exists, show
$str = '<img class=" img-fluid" style="width: 100%;" src="./3bg-userProfile.jpg" alt="Card image cap">';
}else{
// file does not exist, show default
$str = '<img class=" img-fluid" style="width: 100%;" src="./img_logoMarvel.gif" alt="Card image cap">';
}
return $str;
}
Try this code instead:
<?php
function gt_masthead($cID, $image = "bg-userProfile.jpg", $default = "img_logoMarvel.gif") { //assign value to var
//check if given image file exists
if(file_exists("./{$cID}{$image}")) {
//if it does exist, set the displayImage variable to the path of the image.
$displayImage = "./{$cID}{$image}";
} else {
//if it does not exist, set the displayImage variable to the path of the default image
$displayImage = "./{$default}";
}
//Add the displayImage path to an image element, and return that element.
$str = "<img class='img-fluid' style='width:100%;' src='{$displayImage}' alt='Card image cap'>";
return $str;
}
?>
The usage of this code is pretty simple. You call it like this:
gt_masthead("cID number", "image name"); - you can also use variables here, just drop the quotes.
Alternatively, you can also use a 3rd variable to dynamically set the default image if the searched one does not exist.
gt_masthead("cID number", "image name", "default image name");
I commented the code to try to explain what is going on. If you have any questions please ask
Here is a more standard way to write the function, I know the squiggly braces sometimes confused people, but the code is basically the same.
<?php
function gt_masthead($cID, $image = "bg-userProfile.jpg", $default = "img_logoMarvel.gif") { //assign value to var
//check if given image file exists
if(file_exists("./".$cID.$image)) {
//if it does exist, set the displayImage variable to the path of the image.
$displayImage = "./".$cID.$image;
} else {
//if it does not exist, set the displayImage variable to the path of the default image
$displayImage = "./".$default;
}
//Add the displayImage path to an image element, and return that element.
$str = "<img class='img-fluid' style='width:100%;' src='".$displayImage."' alt='Card image cap'>";
return $str;
}
?>
so far I've successfully moved an uploaded image to its designated directory and stored the file path of the moved image into a database I have.
Problem is, however, is that the img src I have echoed fails to read the variable containing the file path of the image. I've been spending time verifying the validity of my variables, the code syntax in echoing the img src, and the successful execution of the move/storing code, but I still get <img src='' when I refer to the view source of the page that is supposed to display the file path contained in the variable.
I believe the file path is stored within the variable because the variable was able to be recognized by the functions that both moved the image to a directory and the query to database.
My coding and troubleshooting experience is still very adolescent, thus pardon me if the nature of my question is bothersomely trivial.
Before asking this question, I've searched for questions within SOF but none of the answers directly addressed my issue (of the questions I've searched at least).
Main PHP Block
//assigning post values to simple variables
$location = $_POST['avatar'];
.
.
.
//re-new session variables to show most recent entries
$_SESSION["avatar"] = $location;
.
.
.
if (is_uploaded_file($_FILES["avatar"]["tmp_name"])) {
//define variables relevant to image uploading
$type = explode('.', $_FILES["avatar"]["name"]);
$type = $type[count($type)-1];
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$rdn = substr(str_shuffle($chars), 0, 15);
//check image size
if($_FILES["avatar"]["size"] > 6500000) {
echo"Image must be below 6.5 MB.";
unlink($_FILES["avatar"]["tmp_name"]);
exit();
}
//if image passes size check continue
else {
$location = "user_data/user_avatars/$rdn/".uniqid(rand()).'.'.$type;
mkdir("user_data/user_avatars/$rdn/");
move_uploaded_file( $_FILES["avatar"]["tmp_name"], $location);
}
}
else {
$location = "img/default_pic.jpg";
}
HTML Block
<div class="profileImage">
<?php
echo "<img src='".$location."' class='profilePic' id='profilePic'/>";
?><br />
<input type="file" name="avatar" id="avatar" accept=".jpg,.png,.jpeg"/>
.
.
.
View Source
<div class="profileImage">
<img src='' class='profilePic' id='profilePic'/><br />
<input type="file" name="avatar" id="avatar" accept=".jpg,.png,.jpeg"/>
.
.
.
Alright, I've finally found the error and was able to successfully solve it!
Simply declare a avatar session variable to the $location variable after updating the table, update the html insert by replacing all $location variables with $_SESSION["avatar_column"] and you are set!
PHP:
$updateCD = "UPDATE users SET languages=?, interests=?, hobbies=?, bio=?, personal_link=?, country=?, avatar=? WHERE email=?";
$updateST = $con->prepare($updateCD);
$updateST->bind_param('ssssssss', $lg, $it, $hb, $bio, $pl, $ct, $location, $_SESSION["email_login"]);
$updateST->execute();
$_SESSION["avatar"] = $location; //Important!
if ($updateST->errno) {
echo "FAILURE!!! " . $updateST->error;
}
HTML:
<div class="profileImage">
<?php
$_SESSION["avatar"] = (empty($_SESSION["avatar"])) ? "img/default_pic.jpg" : $_SESSION["avatar"] ;
echo "<img src='".$_SESSION["avatar"]."' class= 'profilePic' id='profilePic'> ";
?>
.
.
.
Thank you!
try this code
<?php
error_reporting(E_ALL);
ini_set('display_errors','on');
$location = ""; //path
if($_POST && $_FILES)
{
if(is_uploaded_file())
{
// your code
if(<your condition >)
{
}
else
{
$location = "./user_data/user_avatars/".$rdn."/".uniqid(rand()).'.'.$type;
if(!is_dir("./user_data/user_avatars/".$rdn."/"))
{
mkdir("./user_data/user_avatars/".$rdn."/",0777,true);
}
move_uploaded_file( $_FILES["avatar"]["tmp_name"], $location);
}
}
else
{
$location = "img/default_pic.jpg";
}
}
?>
Html Code :-
<div>
<?php
$location = (empty($location)) ? "img/default_pic.jpg" : $location ;
echo "<img src='".location."' alt='".."'> ";
?>
</div>
If it helpful don't forget to marked as answer so another can get correct answer easily.
Good Luck..
Iv try to display BLOB-1B content or image in PHP, I have an app in Android that take an image then upload to my host mysql I have no problem with upload now its time to display in PHP, here is my code.
//config.php
public function _owners_img($stall_id){
$request ="SELECT `img` FROM `img_stall` WHERE `stall_id` = '$stall_id' LIMIT 1";
$result_query = $this->con->query($request);
while($data = $result_query->fetch_assoc()){
$result_data = $data['img'];
}
if (!empty($result_data)) {
return $result_data;
}else {
return false; }
}
//owner_img.php
include_once 'config.php';
$db = new database($con);
$db->dbconnect();
$owner = 3;
echo "<dt><strong>Stall Image:</strong></dt><dd>" .
'<img src="data:image/jpeg;base64,'.
base64_encode($db->_owners_img($owner)).
'" width="290" height="290">' . "</dd>";
but the problem is Am only getting small image icon or image not found. how do I fix this?
I'm new to php. I have a sample mysql db in that I have a table named testdb with columns id(INT) and image(BLOB). I have uploaded an image into testdb. Uploaded successfully. The following is the php code. The variable $conn contains the connection details. I have a html page which redirects to this php page on submitting.
<?php
$name = $_FILES["sample"]["name"];
echo $name . "<br/>";
$tmp_name = $_FILES["sample"]["tmp_name"];
echo $tmp_name . "<br/>";
$size = $_FILES["sample"]["size"];
echo $size . "<br/>";
$contents = file_get_contents($tmp_name);
$htmlen = htmlentities($contents);
$cont = mysql_real_escape_string($contents);
$query = "INSERT INTO testdb(image)
VALUES ('$cont')";
$dbquery = mysql_query($query, $conn);
if($dbquery){
echo "successfully inserted";
}
else{
echo "could not inserted" . mysql_error();
}
?>
I am trying to get the image with the following code. But it is showing string characters rather than the image. As far as I know this should work fine.
<?php
$query = "SELECT image, id
FROM testdb ";
$dbquery=mysql_query($query , $conn);
if(! $dbquery){
echo "Could not selected the data from database. " . mysql_error();
}
while( $row = mysql_fetch_array($dbquery) ){
$decodeimg = html_entity_decode($row["image"]);
echo "<img src= $decodeimg/><br/> hellow orld <br/>";
}
?>
Could anyone help me with this. Thanks in advance.
Instead of storing the actual image in your database (which is redundant because it is probably stored on your server too); why don't you just store the PATH to the image as a string, query the string from your db and then append it to the 'src' attribute with php.
I am also got the same error when show the BLOB image from DB. I just use the decoding method for this problem....
$photo=$myrow['image'];
echo '<img src="data:image/jpeg;base64,' . base64_encode( $photo ) . '" width="150" height="150" />
I am refactoring some old code, including rewriting basic mysql queries to use PDO.
The following works brilliantly in all browsers and for all image types:
$query = 'SELECT image FROM image WHERE imageid=' . $image_id;
$result = mysql_query($query, $db_conn); querycheck($result);
header("Content-type: image");
echo mysql_result($result, 0);
Unfortunately, however I rewrite it using PDO, it doesn't work. I've been through the entire PDO documentation and the standard web search, but none of the advice/solutions work.
How can one easily fetch and image from MySQL using PDO and display it?
Edit 1:
Matthew Ratzloff gives what should be the obvious answer below, but it does not work.
Here is the actual code that I test using PDO (and I have tried many variants/parameters):
$connectstring_temp = 'mysql:host=' . $A . ';dbname=' .$B;
$dbh_temp = new PDO($connectstring_temp, $login, $password);
#$dbh_temp->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
#$dbh_temp->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,true);
$sql = "SELECT image FROM image WHERE imageid=" . $image_id;
$query = $dbh_temp->prepare($sql);
$query->execute();
$query->bindColumn(1, $image, PDO::PARAM_LOB);
$query->fetch(PDO::FETCH_BOUND);
header("Content-Type: image");
echo $image;
I've kept the same syntax, although for the final code $image_id needs to be passed as a parameter. The code above does NOT work. PDO works fine for all other queries of all types.
You need to paramaterize the imageid value and bind the parameter to PDO::PARAM_LOB:
$sql = "SELECT image FROM image WHERE imageid=:id";
$query = $db_conn->prepare($sql);
$query->execute(array(':id' => $image_id));
$query->bindColumn(1, $image, PDO::PARAM_LOB);
$query->fetch(PDO::FETCH_BOUND);
header("Content-Type: image");
echo $image;
Of course, you'll also want to specify the complete, correct content type (e.g., image/png).
My personal approach to Image Blobs is using a php file to serve the image, in combination with a GET argument... It's 100% effective and it doesn't involve file creation... For instance, the file to serve the image from the blob would be:
image.php:
<?php
$db = new PDO('mysql:host=localhost;dbname=anything; charset=utf8', 'account','password');
if (isset($_GET['imageid'])) {
$result = $db->prepare("SELECT image FROM image where imageid = ?");
if ($result->execute(array($_GET['imageid']))) {
$row=$result->fetch();
echo $row['pic']; //this prints the image data, transforming the image.php to an image
}
} // you can put an "else" here to do something on error...
?>
This can be called from you main script... For instance:
<?php
$db = new PDO('mysql:host=localhost;dbname=anything; charset=utf8', 'account','password');
//... some code to do your job, where you get your imageid from
$imageid=...
?>
<img src="./image.php?imageid=<?php echo $imageid;?>">
You can use this code to get image from database using PDO:
public function getImage($id){
$sql = "SELECT * FROM images WHERE id = ?";
$sth = $this->dbh->prepare($sql);
$sth->bindParam(1,$id);
$sth->execute();
$num = $sth->rowCount();
if( $num ){
$row = $sth->fetch(PDO::FETCH_ASSOC);
header("Content-type: ".$row['type']);
print $row['image'];
exit;
}else{
return null;
}
}
type - data type(column name) such as image/png or image/gif
image - image data(column name) stored in table as LOB
$this->dbh connection handler
It works for me but now I need to find out how to use it with JS because result of this function is passed to JavaScript code - so called ajax
This code displays all the images in the dabase so you can change it and make it do what you want it to do
getMessage();
}
?>
<?php
#the folder where the images are saved
$target = "image_uploads/";
$image_name = (isset($_POST['image_name']));
$query = ("SELECT user_id ,image_name FROM tish_images");
$image_show= $con-> prepare($query);
$image_show->execute();
while($record =$image_show->fetch(PDO::FETCH_ASSOC)) {
#this is the Tannery operator to replace a pic when an id do not have one
$photo = ($record['image_name']== null)? "me.png":$record['image_name'];
#display image
echo '<img src="'.$target.$photo.'">';
echo $record['user_id'];
}
?>