PHP showing image is not working - php

Hello i am having a site which shows users their own profile picture. But i am unable to do so, I have built a code but it is not working & giving an error as Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in /home/u522159750/public_html/users/myaccount.php on line 156 i.e. the line $sql = mysqli_query($link, "SELECT id, name, avatar FROM users WHERE id="'.$id.'" ") ;Can anyone suggest me what could be the possible reasons. The code for showing image is as follow---
<p>
<?php
//We check if the users ID is defined
$db_host = "xxxxxxxxxxxx";
$db_username = "xxxxxxxxxxxxxx";
$db_password = "xxxxxxxxx";
$db_database = "xxxxxxxxxxxxxx";
$link = mysqli_connect($db_host,$db_username,$db_password) or die("Cannot connect");
mysqli_select_db($link, $db_database) or die("Cannot select the database");
$sql = mysqli_query($link, "SELECT id, name, avatar FROM users WHERE id="'.$id.'" ") ;
while($result = mysqli_fetch_object($sql)):
<img src="<?php echo $result->avatar; ?>" alt="<?php echo $result->name; ?>" width="200" height="300" />
?> </p>
<?php endwhile; ?>

The part where you intend to output the link with the image, is html and should either be outside of the php part, or printed, as below.
<?php
//We check if the users ID is defined
$db_host = "xxxxxxxxxxxx";
$db_username = "xxxxxxxxxxxxxx";
$db_password = "xxxxxxxxx";
$db_database = "xxxxxxxxxxxxxx";
$link = mysqli_connect($db_host,$db_username,$db_password) or die("Cannot connect");
mysqli_select_db($link, $db_database) or die("Cannot select the database");
$sql = mysqli_query($link, "SELECT id, name, avatar FROM users WHERE id="'.$id.'" ") ;
while($result = mysqli_fetch_object($sql)) {
print ' <img src="'.$result->avatar.'" alt="'.$result->name.'" width="200" height="300" />';
}
?>
</p>

after viewing at the browser, check the url src of each image, is it at the right path? and make sure the image is existed at the src path.

i will not show you a code or an example but this sugestions might be useful :
what does the avatar column in db takes ? does it take the image name or name.extension
or location/name.extension
if it takes only the name : then you must define the location in php example
echo '<a href="#" > <IMG src="location/'.$avatar.'.jpg" alt="..."
hight="200"width="200"/></a>';
but note : in this case all the avatars must be the same extension ( *.jpg )
if it takes the name.extension then you have just to define the location only
if it takes location/name.extension then you problem is not the $avatar
but still can be the avatar's name itself be sure to do not leave avatars names contains
white spaces or non english alphabet characters. you have to renam them.

Related

PHP Super Basic Content Management Advice Please

I'm using XAMPP and PHP for a basic website.
I've already done most of it apart from the Content Management part.
I have a basic form where you upload a picture and add all the details necessary. I need help with keeping the format the same, because there are currently three houses on there with prices and details that are coded in HTML.
How do I echo the details out in the similar format?
Security is not an issue, because there isn't any sensitive information being used and it's not going to be used publicly. All I need to know is how to format the details and pictures in a similar way?
I have attached pictures so that you can better understand what I need help with as well. Here is the code:
<?php
$servername="localhost";
$username="root";
$password="";
$dbname="content_management";
$tbl_name="houses";
$housepic ="housepic";
$houseprice ="houseprice";
$housetype ="housetype";
$houseloc = "houseloc";
$housedesc = "housedesc";
$conn = mysqli_connect($servername, $username, $password, $dbname );
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql="INSERT INTO $tbl_name (picture, price, type, location, description) VALUES ('$housepic','$houseprice','$housetype','$houseloc','$housedesc')";
if (mysqli_query($conn, $sql)) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
<?php
$host="localhost";
$username="root";
$password="";
$db_name="content_management";
$tbl_name="houses";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "SELECT * FROM $tbl_name";
$result=mysql_query($sql);
while ( $row = mysql_fetch_assoc($result) ) {
echo "<img src='" . $row['picture'] . "'>";
echo $row['price'];
echo $row['type'];
echo $row['location'];
echo $row['description'];
}
?>
<div class="housepost">
<img src="img/houses/house_01.jpg">
<h2>£350,000</h2>
<p>2 bedroom detached house for sale</p>
<p>Deanfield Avenue, Henley-on-Thames</p>
<p>Set in the heart of Henley-on-Thames and just a short walk from Henley train station is this rarely available and spacious three bedroom apartment. Offered to the market with no onward chain the property benefits from off road parking.</p>
</div>
<div class="housepost">
<img src="img/houses/house_02.jpg">
<h2>£475,000</h2>
<p>2 bedroom detached bungalow for sale</p>
<p>Fair Mile, Henley-on-Thames</p>
<p>Set in the heart of the town centre in a quiet backwater this delightful single storey detached home is rarely available and well presented.</p>
</div>
<div class="housepost">
<img src="img/houses/house_03.jpg">
<h2>£600,000</h2>
<p>3 bedroom cottage for sale</p>
<p>Remenham Row, Henley-on-Thames</p>
<p>The English Courtyard Association and The Beechcroft Trust - synonymous with the very best in retirement housing since the 1980s. An extremely attractive three-bedroom cottage with landscaped riverside gardens in this much sought after location.</p>
</div>
<?php echo '<div class="housepost">
<img>$row <img>
<h2></h2>
<p></p>
<p></p>
<p>$row</p>
</div>' ?>
</div>
I have no idea what I'm doing with PHP and I'm surprised I made it this far but I have a beginner understanding. You can see the three hardcoded HTML divs in the code, and the last div is my failed experiment attempt with PHP. If you look at the house picture, you can see the format I want the PHP script to display the information as. (Currently refreshing the page automatically creates a record with the form box titles which I need to fix as well)
Please ask questions if you need me to clarify, and if you could help me that'd be really appreciated. I'm sure the answer is super simple, it just took me a while to explain all of this.
This is the database thing I am using:
This is the format of the house in a div that I need PHP to automatically create each time a house is uploaded:
First of all I don't understand what you mean by similar format. But I guess you need to do something like this
<?php
//Remove these variables and place them in a file like config.php
$servername="localhost";
$username="root";
$password="";
$dbname="content_management";
$tbl_name="houses";
$housepic ="housepic";
$houseprice ="houseprice";
$housetype ="housetype";
$houseloc = "houseloc";
$housedesc = "housedesc";
//Make a function with all this block like function inserhome
$conn = mysqli_connect($servername, $username, $password, $dbname );
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//Send a variable named $_REQUEST["doinsert"] from the referer page to check if to insert or not
if($_REQUEST["doinsert"] == true){
$conn = mysqli_connect($servername, $username, $password, $dbname );
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql="INSERT INTO $tbl_name (picture, price, type, location, description) VALUES ('$housepic','$houseprice','$housetype','$houseloc','$housedesc')";
if (mysqli_query($conn, $sql)) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
//Make a function like function selecthomes
mysql_connect($servername, $username, $password)or die("cannot connect");
mysql_select_db($db_name)or die("cannot select DB");
$sql = "SELECT * FROM $tbl_name";
$result=mysql_query($sql);
/*Change made to print all tables using mysql_fetch_assoc. I would
recommend using pdo instedof mysql_fetch_assoc functions since they are
deprecated. check http://php.net/manual/en/book.pdo.php
check the deprecation http://php.net/manual/en/function.mysql-fetch-assoc.php*/
while ( $row = mysql_fetch_assoc($result) ) { ?>
<div class="housepost">
<img src="<?php echo $row['picture'] ?>">
<h2><?php echo $row['price'] ?></h2>
<p><?php echo $row['type'] ?></p>
<p><?php echo $row['location'] ?></p>
<p><?php echo $row['description'] ?></p>
</div>
<?php } ?>
Secondly you also said:
Currently refreshing the page automatically creates a record with the
form box titles which I need to fix as well
Well it is obvious that this script will always insert a new record because each time you do an insert at the beginning of the php file, so inevitably it will insert a new record.
One thing you need to check is if the record is already inserted.
I added some functionality to demonstrate how to check to insert the record or not. It's best you should pass a variable from the url like http://mypage/inserthouse.php?doinsert=true or you can make a form from the referrer page and pass the variable from a hidden field.
You can make two buttons. One will only display the house records and the other will insert and then display the records with the newly inserted.
So the first button will link to http://mypage/inserthouse.php?doinsert=true
and the seconds http://mypage/inserthouse.php?doinsert=false or http://mypage/inserthouse.php
I suggest you should create a function for each action and check wither you need to execute an insert or not. Make the question, When should I insert a new record?
Also you will not need the variable name $tbl_name. It doesn't matter in your code and it makes the script longer.
You also need to use an include file for your variables,
$servername="localhost";
$username="root";
$password="";
$dbname="content_management";
$tbl_name="houses";
$housepic ="housepic";
$houseprice ="houseprice";
$housetype ="housetype";
$houseloc = "houseloc";
$housedesc = "housedesc";
Your code looks like you need to read some object oriented programming for php. Give this a shot, http://www.codecademy.com/courses/web-beginner-en-bH5s3/0/1
I would also recommend using a framework instead of making it your self.
Your skills are not there yet to make your own cms. Go with MVC and Object oriented patters.
Check the zend framework it is very nice and easy to use.
I hope I helped
this is an easy and fast way to accomplish what your looking for.
i figure your problem isn't understanding PHP, DB and HTML basics, but putting it all together - so:
read the code comments CAREFULLY to understand all steps and relationships between all those 3 things.
after you get it, you can follow this link: php_file_upload to learn how to upload the picture (which is a bit more complicated, but is a good test for your learning).
this is the code (all in the same page!!!):
<!-- HTML form to add a new house -->
<form method="post">
<!-- this is only giving and existing url, notice you should change this
if you want to upload an actual pic -->
<input type="text" name="housepic">
<br>
<input type="text" name="houseprice">
<br>
<input type="text" name="housetype">
<br>
<input type="text" name="houseloc">
<br>
<input type="text" name="housedesc">
<br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
//init DB vars
$servername="localhost";
$username="root";
$password="";
$dbname="content_management";
$tbl_name="houses";
//conect to db
$conn = mysqli_connect($servername, $username, $password, $dbname );
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
/* if request method is: "post", a form was submitted.
get the submitted form params, and update DB */
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
/* notice you should add here error handling, case user didn't fill
all params */
$housepic = ( isset($_POST["housepic"]) ) ? $_POST["housepic"] : "";
$housepic = ( isset($_POST["houseprice"]) ) ? $_POST["houseprice"] : "";
$housepic = ( isset($_POST["housetype"]) ) ? $_POST["housetype"] : "";
$housepic = ( isset($_POST["houseloc"]) ) ? $_POST["houseloc"] : "";
$housepic = ( isset($_POST["housedesc"]) ) ? $_POST["housedesc"] : "";
// update DB
$sql="INSERT INTO $tbl_name (picture, price, type, location, description) VALUES ('$housepic','$houseprice','$housetype','$houseloc','$housedesc')";
if (mysqli_query($conn, $sql)) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
/* we'll always get to this part.
notice, if a form was already submitted, we've just updated our DB
accordingly, so the houses list is already updated */
while ( $row = mysql_fetch_assoc($result) ) {
/* good practice: grab your params before,
for a nicer and reusable code */
$picture = $row['picture'];
$price = $row['price'];
$type = $row['type'];
$location = $row['location'];
$description = $row['description'];
/********************************************************************
this is the part you are asking about.
notice that echoing the HTML tags content is done
inside the WHILE loop,
which of course will be always in the same format...
*********************************************************************/
echo "
<div class=\"housepost\">
<img src=\"{$picture}\">
<h2>{$price}</h2>
<p>{$type}</p>
<p>{$location}</p>
<p>{$description}</p>
</div>";
}
/* don't forget to close your DB connection */
mysqli_close($conn);

PHP unlink() not working to delete files

I am have been trying to setup this code to delete a row on the mysql database as well as the photo that was uploaded with it. It is working GREAT to remove the row data, but it will not get rid of the photo, and I cannot figure out what I am doing wrong. To simplify things, im using the variable $id which is the number of the row entered in the form which triggers this php file:
<?php
$host="localhost"; // Host name
$username="blahblah_plans"; // Mysql username
$password="password"; // Mysql password
$db_name="blahtbl_name"; // Database name
$tbl_name="plans"; // Table name
// Connect to server and select databse.
$conn = mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// get value of id that sent from address bar
$id=$_GET['idnum'];
$compositesql="SELECT composite FROM plans WHERE ID ='$id'";
$compositeresult = mysql_query($compositesql) or die(mysql_error());
$compositefilename = "/composite/" + $compositeresult;
$unlink = unlink($compositefilename);
if($unlink) {
echo 'Successfully deleted file: ';
echo $compositefilename;
} else {
echo 'Error deleting file: ';
echo $compositefilename;
}
// Delete data in mysql from row that has this id
$sql="DELETE FROM $tbl_name WHERE ID ='$id'";
$result = mysql_query($sql);
if($result){
header("location:planentry.php");
}
else {
echo "ERROR";
}
?>
<?php
// close connection
mysql_close();
?>
Make sure the path is right, $compositefilename = "/composite/" + $compositeresult; should be the path in the server, it most likely to be
$compositefilename = PATH_TO_YOUR_WEB_ROOT . "/composite/" . $compositeresult;
And php does not use + to concat strings.
The problem is that $compositeresult contains a resource rather than a result set. This line is what's causing it:
$compositeresult = mysql_query($compositesql) or die(mysql_error());
To fix that, store the resource on a variable, then store the result set on another variable, like this:
$compositequery = mysql_query($compositesql) or die(mysql_error());
$compositeresult = mysql_fetch_array($compositequery) or die(mysql_error());
Also, I highly recommend that you start using mysqli or PDO instead of mysql, since it's safer. Also, as xdazz said, PHP's concatenation operator is the dot, not the plus sign. So your $compositefilename should be declared as (note that $compositeresult is an array of data and therefore should have its correct key explicitly written):
$compositefilename = "/composite/" . $compositeresult['composite'];

Displaying PNG images from MySQL

I'm trying to display an image from a MySQL database and my code works fine if the image is a JPG, but if I modify the content-type to display a PNG, it doesn't work...
How do I make it work for PNG??
<?php
// configuration
require("../includes/config.php");
header('Content-type: image/JPG');
$username = "xxxxx";
$password = "*****";
$host = "localhost";
$database = "database";
#mysql_connect($host, $username, $password) or die("Can not connect to database: ".mysql_error());
#mysql_select_db($database) or die("Can not select the database: ".mysql_error());
$query = mysql_query("SELECT * FROM images");
while($row = mysql_fetch_array($query))
{
echo $row['image'];
}
?>
Also, is it possible to display the image along with its name and description?
Thanks!
If you don't mind not supporting older browsers, you can use data urls to display your images and a description http://en.wikipedia.org/wiki/Data_URI_scheme.
<figure>
<img src="data:image/png;base64,<?php echo base64_encode($row['image']); ?>" alt="Your alternative text" />
<figcaption>Some more description</figcaption>
</figure>
Saving images in a database is not very useful in almost all cases. You should be carefull with upper and lower letters in the mimetype, see http://de.selfhtml.org/diverses/mimetypen.htm (it's german, but you will be able to read the list). And as a last advice - look at the mysqli_* functions http://www.php.net/manual/en/book.mysqli.php.
// Edit: Just an idea, but if you have multiple images in the database your image might be broken, because you just put them all into one image. This will not work! With your code, you can only display one image at once.

How to show image using php?

I am just starting to use html, php, and mysql. I've successfully logged into my database using php, and formed a query. I now want to go a step further and show a picture instead of just strings or numbers.
The variable 'result' will be returning a string that has a url to an image i want to display on this webpage. How would I do this?
<html>
<head>
<title>My First Question</title>
</head>
<body>
<?php
$dbhost = 'someURL.com';
$dbname = 'user';
$dbuser = 'user';
$dbpass = 'password';
$mysql_handle = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Error Connecting To Database Server");
mysql_select_db($dbname, $mysql_handle)
or die("Error selecting database: $dbname");
echo 'Successfully connected to database!';
$first = 'bobbie';
$query = sprintf("SELECT image FROM Player
p WHERE name='%s'", mysql_real_escape_string($first));
$result = mysql_query($query);
mysql_close($mysql_handle);
?>
</body>
</html>
Inside PHP, This will turn your SQL response into a usable variable.
$result = mysql_fetch_assoc(mysql_query($query));
Outside of your PHP tags, Echo the URL from the table into the SRC of an IMG element.
<img src="<?= $result['url_column_name'] ?>"/>
This will create a new IMG element with the source being the URL that you have fetched from your SQL query.
Short tags are also a way of echoing PHP variables in HTML.
<?= $var1, $var2 ?>
is the equivalent of using
<?php echo $var; echo $var2; ?>
This is a simple case of echoing the relevant HTML. You'll also have to fetch the results after you execute the query -
$result = mysql_query($query);
$data = mysql_fetch_assoc($result);
echo '<img src="'.$data['image'].'" />;
For added security, a good practice would be to escape any possible unwanted HTML content in your images path - htmlspecialchars($data['image']).
It should also be noted here that you are using a very old deprecated method to access your database. You might want to think about updating your code to use more modern PDO methods.
So what? simply use it as a source to your image
<?php $imgname = mysqli_fetch_array($connection, $result); ?>
<img src="<?php echo $imgname['image_column_name']; ?>" />
And btw use mysqli_() or PDO instead of using mysql_() as community is not maintaining it anymore
Once you update your mysql to mysqli you can echo the image's url in an html img tag as so:
echo '<img src="'.$result['image'].'"/>';
<?php
$dbhost = 'someURL.com';
$dbname = 'user';
$dbuser = 'user';
$dbpass = 'password';
$mysql_handle = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Error Connecting To Database Server");
mysql_select_db($dbname, $mysql_handle)
or die("Error selecting database: $dbname");
$first = 'bobbie';
$query = sprintf("SELECT image FROM Player
p WHERE name='%s'", mysql_real_escape_string($first));
$result = mysql_query($query);
mysql_close($mysql_handle);
header("Location: $result");
?>
should work

How do I save text from a textarea into a MySQL database with PHP when a Save button is clicked?

I have a textarea in HTML where a logged in user can enter and save notes. I use the following script to retrieve the saved notes from the database
<?php
function notes() {
$password = "fake_password";
$connect = mysql_connect("localhost", "user", $password) or die("Couldn't connect to the database!");
mysql_select_db("db_name") or die("Couldn't find the database!");
$query = mysql_query("SELECT * FROM users WHERE notes!=''");
$numrows = mysql_num_rows($query);
if ($numrows != 0) {
while ($row = mysql_fetch_assoc($query)){
$notes = $row['notes'];
}
echo $notes;
}
}
?>
That works all fine and dandy but now - how do I save the changes the user made to the notes (textarea) when a Save button is clicked?
EDIT:
Here is the form itself:
<div class="row-fluid">
<div class="span12">
<br />
<center><textarea class="input-xxlarge" rows="15"><?php include('includes/func.php'); notes(); ?></textarea>
<br />
<button class="btn btn-primary">Save Changes</button>
</center>
</div>
</div>
First: You should use PDO to connect to your database, not mysql. Mysql is being deprecated, and is prone to SQL Injection attacks and therefore NOT safe to use in web applications.
With that caveat, I will reply using mysql since that is what you are using.
It's not too difficult. Of course without the table structure, or the code from your form, the below has to use example field names, and assumes you store the user id in a $_SESSION variable:
<?php
function savenotes() {
// The database connection code should be moved to a central function/location rather than called in every function
$password = "fake_password";
$connect = mysql_connect("localhost", "user", $password) or die("Couldn't connect to the database!");
mysql_select_db("db_name") or die("Couldn't find the database!");
// Retreive notes from form
$notes = $_POST['notes']; // Assumes field is called notes, and you used method=POST
// Assuming a user can only update their own notes, and that you are storing the user id somewhere
$userid = $_SESSION['userid'];
$query = mysql_query("UPDATE users SET notes ='" . mysql_real_escape_string($notes) . "' WHERE userid = " . (int)$userid);
}
}
?>

Categories