How to show images onto browser? it's giving me errors - javascript

i've successfully uploaded my image into folder and successfully saved my path into database now as i tried to show pic into browser it's showing error:
Warning: mysql_query() expects parameter 2 to be resource, object given in C:\Users\Raj\PhpstormProjects\image\upload_file.php on line 6
Warning: mysql_num_rows() expects parameter 1 to be resource, null given in C:\Users\Raj\PhpstormProjects\image\upload_file.php on line 7
File name not found in database
here is my code for form:
<?php
// Assigning value about your server to variables for database connection
$hostname_connect= "localhost";
$database_connect= "photo";
$username_connect= "root";
$password_connect= "Bhawanku";
$connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR);
#mysql_select_db($database_connect) or die (mysql_error());
if($_POST)
{
// $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.
if ($_FILES["file"]["error"] > 0)
{
// if there is error in file uploading
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
// check if file already exit in "images" folder.
if (file_exists("images/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{ //move_uploaded_file function will upload your image. if you want to resize image before uploading see this link http://b2atutorials.blogspot.com/2013/06/how-to-upload-and-resize-image-for.html
if(move_uploaded_file($_FILES["file"]["tmp_name"],"images/" . $_FILES["file"]["name"]))
{
// If file has uploaded successfully, store its name in data base
$query_image = "insert into acc_images (image, status, acc_id) values ('".$_FILES['file']['name']."', 'display','')";
if(mysql_query($query_image))
{
echo "Stored in: " . "images/" . $_FILES["file"]["name"];
}
else
{
echo 'File name not stored in database';
}
}
}
}
}
?>
<html>
<body>
<form action="upload_file.php" method="post"enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
and here is my code for showing pics:
<?php
$con=mysqli_connect("localhost","root","Bhawanku","photo");
// Check connection
$query_image = "SELECT * FROM acc_images";
// This query will show you all images if you want to see only one image pass acc_id='$id' e.g. "SELECT * FROM acc_images acc_id='$id'".
$result = mysql_query($query_image, $con);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result))
{
echo '<img alt="" src="images/'.$row["image"].'">';
}
}
else
{
echo 'File name not found in database';
}
?>

In the second script, you're connecting as mysqli but then using mysql_query, mysql_num_rows and mysql_fetch_array. MySQLi and MySQL aren't interchangeable.
$result = mysqli_query($query_image, $con);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
echo '<img alt="" src="images/'.$row["image"].'">';
}
}
else
{
echo 'File name not found in database';
}
You should consider changing the first script to MySQLi too, and use prepared statements instead of concatenating variables into the query.

In first row you use mysqli extension, but in all other - mysql.
Try to change:
<?php
$con=mysql_connect("localhost","root","Bhawanku");
mysql_select_db("photo", $con);
// Check connection
$query_image = "SELECT * FROM acc_images";
// This query will show you all images if you want to see only one image pass acc_id='$id' e.g. "SELECT * FROM acc_images acc_id='$id'".
$result = mysql_query($query_image, $con);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result))
{
echo '<img alt="" src="images/'.$row["image"].'">';
}
}
else
{
echo 'File name not found in database';
}
?>

Related

Is there a way to pass value of a Button on click to another php file?

My aim is to get the lec_id which is the Button value when the button is clicked and pass it to chapters.php where I use the button value for a SQL query.
Below is part of my code for index.php
<?php
$con = mysqli_connect("localhost", "root", "", "lectureHub");
if(!$con) {
die("Could not connect to MySql Server:" . mysqli_error());
}
$query = "select * from lectures";
$result = mysqli_query($con, $query);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$lec_id = $row['lec_id'];
$lec_name = $row['lec_name'];
$lec_number = $row['lec_number'];
$lec_views = $row['lec_views'];
echo "<button id=linkButton name={$row['lec_name']} value={$row['lec_id']} type='button' class='btn btn-outline-primary lecture' onclick='buttonClicked(this)'>
{$row['lec_name']}
</button> ";
}
} else {
echo "0 results";
}
?>
my button onclick function
function buttonClicked(btn) {
btn.click_counter = (btn.click_counter || 0) + 1;
document.getElementById("num_clicks_feedback").textContent = `btn ${btn.getAttribute('name')} has been clicked ${btn.click_counter} times`;
localStorage.setItem("lecId", btn.getAttribute('value'));
location.href = 'index.php?action=lec_hub/chapters';
}
I want to use the Button value here in chapters.php for a SQL query.
<html>
<head></head>
<body>
<?php
echo "<p id='lecId'></p>";
$con = mysqli_connect("localhost", "root", "", "lectureHub");
if(!$con) {
die("Could not connect to MySql Server:" . mysqli_error());
}
$query = "select * from chapters where <<this is where i want to use lecId>> ";
?>
<script>
function getValue(){
var lecId = localStorage.getItem("lecId");
document.getElementById("lecId").innerHTML = lecId;
var resetValue= 0;
localStorage.setItem("lecId", resetValue)
}
getValue()
</script>
</body>
</html>
Welcome to Stack Overflow! As Barmar stated in their comment, you can pass data to a PHP file using URL parameters, or more commonly known as GET parameters. Here's how you do it.
From your file with your button in it, you can create a form like this one:
<form action="chapters.php" method="get">
<input type="text" name="data" /> <!-- This is the value that will be passed -->
<input type="submit" value="Button" /> <!-- This is your button -->
</form>
And then from your PHP file, you can get that passed data like this:
echo $_GET["data"]
$_GET is a global PHP array that contains all of the URL parameters sent to the file. you can pass multiple values as GET parameters to a file. You can read all about the $_GET variable here. I hope this helps!

Adding and displaying multiple images [duplicate]

I have experience doing this with single file uploads using <input type="file">. However, I am having trouble doing uploading more than one at a time.
For example, I'd like to select a series of images and then upload them to the server, all at once.
It would be great to use a single file input control, if possible.
Does anyone know how to accomplish this?
This is possible in HTML5. Example (PHP 5.4):
<!doctype html>
<html>
<head>
<title>Test</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="my_file[]" multiple>
<input type="submit" value="Upload">
</form>
<?php
if (isset($_FILES['my_file'])) {
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i < $fileCount; $i++) {
?>
<p>File #<?= $i+1 ?>:</p>
<p>
Name: <?= $myFile["name"][$i] ?><br>
Temporary file: <?= $myFile["tmp_name"][$i] ?><br>
Type: <?= $myFile["type"][$i] ?><br>
Size: <?= $myFile["size"][$i] ?><br>
Error: <?= $myFile["error"][$i] ?><br>
</p>
<?php
}
}
?>
</body>
</html>
Here's what it looks like in Chrome after selecting 2 items in the file dialog:
And here's what it looks like after clicking the "Upload" button.
This is just a sketch of a fully working answer. See PHP Manual: Handling file uploads for more information on proper, secure handling of file uploads in PHP.
There are a few things you need to do to create a multiple file upload, its pretty basic actually. You don't need to use Java, Ajax, Flash. Just build a normal file upload form starting off with:
<form enctype="multipart/form-data" action="post_upload.php" method="POST">
Then the key to success;
<input type="file" name="file[]" multiple />
do NOT forget those brackets!
In the post_upload.php try the following:
<?php print_r($_FILES['file']['tmp_name']); ?>
Notice you get an array with tmp_name data, which will mean you can access each file with an third pair of brackets with the file 'number' example:
$_FILES['file']['tmp_name'][0]
You can use php count() to count the number of files that was selected. Goodluck widdit!
Full solution in Firefox 5:
<html>
<head>
</head>
<body>
<form name="uploader" id="uploader" action="multifile.php" method="POST" enctype="multipart/form-data" >
<input id="infile" name="infile[]" type="file" onBlur="submit();" multiple="true" ></input>
</form>
<?php
echo "No. files uploaded : ".count($_FILES['infile']['name'])."<br>";
$uploadDir = "images/";
for ($i = 0; $i < count($_FILES['infile']['name']); $i++) {
echo "File names : ".$_FILES['infile']['name'][$i]."<br>";
$ext = substr(strrchr($_FILES['infile']['name'][$i], "."), 1);
// generate a random new file name to avoid name conflict
$fPath = md5(rand() * time()) . ".$ext";
echo "File paths : ".$_FILES['infile']['tmp_name'][$i]."<br>";
$result = move_uploaded_file($_FILES['infile']['tmp_name'][$i], $uploadDir . $fPath);
if (strlen($ext) > 0){
echo "Uploaded ". $fPath ." succefully. <br>";
}
}
echo "Upload complete.<br>";
?>
</body>
</html>
in the first you should make form like this :
<form method="post" enctype="multipart/form-data" >
<input type="file" name="file[]" multiple id="file"/>
<input type="submit" name="ok" />
</form>
that is right . now add this code under your form code or on the any page you like
<?php
if(isset($_POST['ok']))
foreach ($_FILES['file']['name'] as $filename) {
echo $filename.'<br/>';
}
?>
it's easy... finish
<form action="" method="POST" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="file[]" multiple/>
<input type="submit" name="submit" value="Upload Image" />
</form>
Using FOR Loop
<?php
$file_dir = "uploads";
if (isset($_POST["submit"])) {
for ($x = 0; $x < count($_FILES['file']['name']); $x++) {
$file_name = $_FILES['file']['name'][$x];
$file_tmp = $_FILES['file']['tmp_name'][$x];
/* location file save */
$file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */
if (move_uploaded_file($file_tmp, $file_target)) {
echo "{$file_name} has been uploaded. <br />";
} else {
echo "Sorry, there was an error uploading {$file_name}.";
}
}
}
?>
Using FOREACH Loop
<?php
$file_dir = "uploads";
if (isset($_POST["submit"])) {
foreach ($_FILES['file']['name'] as $key => $value) {
$file_name = $_FILES['file']['name'][$key];
$file_tmp = $_FILES['file']['tmp_name'][$key];
/* location file save */
$file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */
if (move_uploaded_file($file_tmp, $file_target)) {
echo "{$file_name} has been uploaded. <br />";
} else {
echo "Sorry, there was an error uploading {$file_name}.";
}
}
}
?>
If you want to select multiple files from the file selector dialog that displays when you select browse then you are mostly out of luck. You will need to use a Java applet or something similar (I think there is one that use a small flash file, I will update if I find it). Currently a single file input only allows the selection of a single file.
If you are talking about using multiple file inputs then there shouldn't be much difference from using one. Post some code and I will try to help further.
Update:
There is one method to use a single 'browse' button that uses flash. I have never personally used this but I have read a fair amount about it. I think its your best shot.
http://swfupload.org/
If you use multiple input fields you can set name="file[]" (or any other name). That will put them in an array when you upload them ($_FILES['file'] = array ({file_array},{file_array]..))
partial answer: pear HTTP_UPLOAD can be usefull
http://pear.php.net/manual/en/package.http.http-upload.examples.php
there is a full example for multiple files
i have created a php function which is used to upload multiple images,
this function can upload multiple images in specific folder as well it can saves the records into the database
in the following code
$arrayimage is the array of images which is sent through form
note that it will not allow upload to use multiple but you need to create different input field with same name as will you can set dynamic add field of file unput on button click.
$dir is the directory in which you want to save the image
$fields is the name of the field which you want to store in the database
database field must be in array formate
example
if you have database imagestore and fields name like id,name,address then you need to post data like
$fields=array("id"=$_POST['idfieldname'], "name"=$_POST['namefield'],"address"=$_POST['addressfield']);
and then pass that field into function $fields
$table is the name of the table in which you want to store the data..
function multipleImageUpload($arrayimage,$dir,$fields,$table)
{
//extracting extension of uploaded file
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $arrayimage["name"]);
$extension = end($temp);
//validating image
if ((($arrayimage["type"] == "image/gif")
|| ($arrayimage["type"] == "image/jpeg")
|| ($arrayimage["type"] == "image/jpg")
|| ($arrayimage["type"] == "image/pjpeg")
|| ($arrayimage["type"] == "image/x-png")
|| ($arrayimage["type"] == "image/png"))
//check image size
&& ($arrayimage["size"] < 20000000)
//check iamge extension in above created extension array
&& in_array($extension, $allowedExts))
{
if ($arrayimage["error"] > 0)
{
echo "Error: " . $arrayimage["error"] . "<br>";
}
else
{
echo "Upload: " . $arrayimage["name"] . "<br>";
echo "Type: " . $arrayimage["type"] . "<br>";
echo "Size: " . ($arrayimage["size"] / 1024) . " kB<br>";
echo "Stored in: ".$arrayimage['tmp_name']."<br>";
//check if file is exist in folder of not
if (file_exists($dir."/".$arrayimage["name"]))
{
echo $arrayimage['name'] . " already exists. ";
}
else
{
//extracting database fields and value
foreach($fields as $key=>$val)
{
$f[]=$key;
$v[]=$val;
$fi=implode(",",$f);
$value=implode("','",$v);
}
//dynamic sql for inserting data into any table
$sql="INSERT INTO " . $table ."(".$fi.") VALUES ('".$value."')";
//echo $sql;
$imginsquery=mysql_query($sql);
move_uploaded_file($arrayimage["tmp_name"],$dir."/".$arrayimage['name']);
echo "<br> Stored in: " .$dir ."/ Folder <br>";
}
}
}
//if file not match with extension
else
{
echo "Invalid file";
}
}
//function imageUpload ends here
}
//imageFunctions class ends here
you can try this code for inserting multiple images with its extension this function is created for checking image files you can replace the extension list for perticular files in the code

Passing a PHP variable with fetched data to a JavaScript variable returns NULL or empty

I have an issue with returning the value of a PHP variable in JS. It returns NULL or empty instead of returning the age.
Approach:
Passing PHP variable with data to a JS variable in a separate file. Display JS variable in an alert(). Data was fetched from the database using fetch_assoc() in a while loop. Without using Ajax!
Proposed plan:
Enter a name.
Submit.
PHP fetches the age associated with that name.
age is stored in a PHP variable dbage.
Passed into JS variable to alert user what their age is.
I am trying to pass $dbage from sampletest.php to user in sample.php which will onsubmit display an alert saying: "Your age is blah".
blah is $dbage, which contains the age. This is for testing. Once I understand why this isn't working, I can move on to sending these JS variables to functions that will do calculations and return back to the DB.
What I have tried so far..
Trying to catch echo using ob_start() but that returned NULL as well.
Example:
ob_start();
echo $dbage;
$output = ob_get_contents();
ob_end_clean();
Making $dbage a global variable. Returns empty.
Echo variable outside the while loop but that returned NULL.
Example:
$dbage = '';
while( $row = $result->fetch_assoc()) {
$dbage = $row['age'];
}
echo $dbage;
Any suggestions, corrections are appreciated.
sample.php (index file)
<?php
include 'sampletest.php';
session_start();
?>
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<div id="id03">
<form class="modal-content" action="sampletest.php" method="post" onsubmit="myFunction()">
<div class="container">
<input type="text" id="name" placeholder="Enter name" name="name">
<div class="clearfix">
<button type="submit" class="loggedinbtn" name="load"/>Load
</div>
</div>
</form>
</div>
<script>
function myFunction() {
var user = '<?php echo(json_encode($dbage)); ?>';
alert("This is a php varible " + user);
}
</script>
</body>
</html>
sampletest.php
if(isset($_POST['load'])){
require 'config.php';
$name = $_POST['name'];
$age = $_POST['age'];
if(empty($name)) {
echo "Enter a number";
}elseif(!preg_match('/^[a-z ]+$/i', $name)){
echo "Enter a letter, no numbers";
}else{
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
header("location: sample.php?Connect-database=failed");
exit();
}
$sql = "SELECT name, age FROM results WHERE name= '$name';";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while( $row = $result->fetch_assoc()) {
$dbage = $row['age'];
}
}
else{
echo "0 results";
}
$conn->close();
}
}
your action in the form should be set to sample.php, i think is the first problem. then get rid of the javascript all together.
<form class="modal-content" action="sample.php" method="post">
then change:
<script>
function myFunction() {
var user = '<?php echo(json_encode($dbage)); ?>';
alert("This is a php varible " + user);
}
</script>
to just
<script>
var user = <?php echo $dbage; ?>;
alert("This is a php varible " + user);
</script>
submitting html forms to PHP does not require javascript at all.
From what I can see is that the actual query that you're sending is { name= '$name' }, try { name=' " . $name . " ' }.

PHP Signup from returns to wrong URL instead of index, Database error?

I currently have a loginsystem where a user is able to register and login as a user.
When the user is logged in they should be able to upload a profile image.
The problem that i have is that when i press the Signup button, i gets rediretec to this URL (http://localhost/php51/login.php) Instead of this (http://localhost/php51/index.php).
The thing is that when the user has been registered, then the user should pop up on index.php and show a default profile pic for the user.
Instead i just get a blank page on (http://localhost/php51/login.php).
This is my database with the columns:
I have two tables in my Database called (loginsystem)
the two tables are:
table "profileimg" with the columns (id, status, userid)
and the table "users" with columns (user_email, user_id, user_name, user_password, user_phone, user_zip)
This is my code:
INDEX.php
<?php
session_start();
include_once 'dbh.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<?php
// Check if there is users
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['user_id'];
$sqlImg = "SELECT * FROM profileimg WHERE userid='$id'";
$resultImg = mysqli_query($conn, $sqlImg);
while ($rowImg = mysqli_fetch_assoc($resultImg)) {
echo "<div>";
if($rowImg['status'] == 0) {
echo "<img src='uploads/profile".$id.".jpg'";
} else {
echo "<img src='uploads/profiledefault.jpg'";
}
echo $row['name'];
echo "</div>";
}
}
} else {
echo "No registered users :";
}
//Her checker vi for om man er logget ind,
//og viser herefter upload FORM
if (isset($_SESSION['id'])) {
if ($_SESSION['id'] == 1) {
echo " You are logged in!";
}
//If the user is logged in, we allow the user to upload a profile image
echo "<form action = 'upload.php' method='POST' enctype = 'multipart/form-data'>
<input type = 'file' name = 'file'>
<button type = 'submit' name = 'submit'>UPLOAD FILE</button>
</form>";
} else {
echo " You are not logged in!";
echo "<form action='login.php' method='POST'>
<input type='text' name='name' placeholder='Name'>
<input type='text' name='phone' placeholder='phone'>
<input type='text' name='email' placeholder='email'>
<input type='text' name='zip' placeholder='zip'>
<input type='password' name='password' placeholder='password'>
<button type ='submit' name='submitSignup'>Signup</button>
</form>";
}
?>
<!--We use HTML forms when we want to upload images or files-->
<!--The form HAS to be set as a POST method, and it needs the "enctype" attribute, which specifies that the content we are submitting using the form is a file-->
<p> Login as user </p>
<form action="login.php" method="POST">
<button type="submit" name="submitLogin"> Login </button>
</form>
<p> Logout as user </p>
<form action="logout.php" method="POST">
<button type="submit" name = "submitLogout">Logout</button>
</form>
</body>
</html>
LOUGOUT.php
<?php
session_start();
session_unset();
session_destroy();
header("Location: index.php");
UPLOAD.php
<?php
//First we check if the form has been submitted
if (isset($_POST['submit'])) {
//Then we grab the file using the FILES superglobal
//When we send a file using FILES, we also send all sorts of information regarding the file
$file = $_FILES['file'];
//Here we get the different information from the file, and assign it to a variable, just so we have it for later
//If you use "print_r($file)" you can see the file info in the browser
$fileName = $file['name'];
$fileType = $file['type'];
//The "tmp_name" is the temporary location the file is stored in the browser, while it waits to get uploaded
$fileTempName = $file['tmp_name'];
$fileError = $file['error'];
$fileSize = $file['size'];
//Later we are going to decide the file extensions that we allow to be uploaded
//Here we are getting the extension of the uploaded file
//First we split the file name into name and extension
$fileExt = explode('.', $fileName);
//Then we get the extention
$fileActualExt = strtolower(end($fileExt));
//Here we declare which extentions we want to allow to be uploaded (You can change these to any extention YOU want)
$allowed = array("jpg", "jpeg", "png", "pdf");
//First we check if the extention is allowed on the uploaded file
if (in_array($fileActualExt, $allowed)) {
//Then we check if there was an upload error
if ($fileError === 0) {
//Here we set a limit on the allowed file size (in this case 500mb)
if ($fileSize < 500000) {
//We now need to create a unique ID which we use to replace the name of the uploaded file, before inserting it into our rootfolder
//If we don't do this, we might end up overwriting the file if we upload a file later with the same name
//Here we create a unique ID based on the current time, meaning that no ID is identical. And we add the file extention type behind it.
$fileNameNew = uniqid('', true).".".$fileActualExt;
//Here we define where we want the new file uploaded to
$fileDestination = 'uploads/'.$fileNameNew;
//And finally we upload the file using the following function, to send it from its temporary location to the uploads folder
move_uploaded_file($fileTempName, $fileDestination);
//Going back to the previous page
header("Location: index.php");
}
else {
echo "Your file is too big!";
}
}
else {
echo "There was an error uploading your file, try again!";
}
}
else {
echo "You cannot upload files of this type!";
}
}
SIGNUP.php
<?php
include_once 'dbh.php';
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$zip = $_POST['zip'];
$password = $_POST['password'];
$sql = "INSERT INTO users (name, phone, email, zip, password)
VALUES ('$name', '$phone', '$email', '$zip', '$password')";
mysqli_query($conn, $sql);
$sql = "SELECT * FROM users WHERE name = '$name' AND phone='$phone'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$userid = $row['user_id'];
$sql = "INSERT INTO profileimg (userid, status)
VALUES ('$userid', 1)";
mysqli_query($conn, $sql);
header("Location: index.php");
}
} else {
echo "Error";
}
DBH.PHP
<?php
$conn = mysqli_connect("localhost", "root", "", "loginsystem");
LOGIN.PHP
<?php
session_start();
if (isset($_POST['submitLogin'])) {
$_SESSION['id'] = 1;
header("Location: index.php");
}
In your file index.php you need to change the line
echo "<form action='login.php' method='POST'>
to
echo "<form action='signup.php' method='POST'>
Right now you're sending your signup data to the wrong place

image not displaying in my form in php

I am having issues displaying image on the website i am developing. It a website that users can change their profile picture, as well as their basic profile information. bellow is my sample code.
profile.php
<?php
$studpix=$row_rsp['pix'];
$propix='<img class=
"profile-user-img img-responsive img-circle" src="...
/Student /imageupload/blank.png"
alt="profile picture">';
if($propix!=NULL)
{
$propix='<img class="profile-user-img
img-responsive img-circle" src="Student/imageupload/'.$studpix.'"
alt="profile picture">';
};
$profile_pic_btn =
' Profile pics';
$avatar_form = '<form id="avatar_form"
enctype="multipart/form-data" method="post" action="photoup.php">';
$avatar_form .= '<h4>Change your picture</h4>';
$avatar_form .= '<input type="file" name="avatar" required>';
$avatar_form .= '<p><input type="submit" value="Upload"></p>';
$avatar_form .= '</form>';
?>
<?php echo $propix?><?
php echo $avatar_form?><?php echo $profile_pic_btn;?>
//other codes goes here
imageupload.php
<?php
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]
["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
echo "ERROR: That image has no dimensions";
exit();
}
$db_file_name = rand(100000000000,999999999999).".".$fileExt;
if($fileSize > 1048576) {
echo "ERROR: Your image file was larger than 1mb";
exit();
} else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
echo "ERROR: Your image file was not jpg, gif or png type";
exit();
} else if ($fileErrorMsg == 1) {
echo "ERROR: An unknown error occurred";
exit();
}
$sql = "SELECT pix FROM studentdetails WHERE email='%s'";
$query = mysqli_query($myconn, $sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
if($avatar != ""){
$picurl = "../Student/imageupload/$avatar";
if (file_exists($picurl)) { unlink($picurl); }
}
$moveResult = move_uploaded_file(
$fileTmpLoc, "../Student /imageupload /$db_file_name");
if ($moveResult != true) {
echo "ERROR: File upload failed";
exit();
}
include_once("../image_resize.php");
$target_file = "../Student/imageupload/$db_file_name";
$resized_file = "../Student/imageupload/$db_file_name";
$wmax = 200;
$hmax = 300;
img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
$sql = "UPDATE studendetails SET pix='%s' WHERE email='%s' LIMIT 1";
$query = mysqli_query($myconn, $sql);
mysqli_close($myconn);
header("location: profile.php");
exit();
}
?>
Your help will be appreciated.
Try to debug your code step by step.
1. Check whether the file gets uploaded correctly and to the correct folder.
2. Check whether the data is updated correctly in the database.
3. Try to open the file by URL directly in the browser.
4. Check whether your HTML code is outputted correctly on the webpage and debug the outputted source code.
5. Make sure that your HTML code works properly.
There may be more steps to take, but this might give you some direction.

Categories