If user uploads wrong file then if statement resetting $name to blank. What is the problem in following code?
if(isset($_POST['submit'])){
$conn= new mysqli('localhost','root','','dilip');
if(!$conn){
die("Not connect".mysqli_error);
}
$stm = $conn->prepare("Insert into comment (Name, email, Message, Image) values (?, ?, ?, ?)");
$stm->bind_param('ssss',$name,$email,$message,$image);
$name = $_POST['name'];
$message = $_POST['readerInput'];
$email = $_POST['email'];
$image='upload/comment/default.jpg';
$time = date("s");
//if(isset($_FILES['image'])){
if(is_uploaded_file($_FILES['image']['tmp_name'])){
$tmp_image = $_FILES['image']['size'];
$finfo = new finfo(FILEINFO_MIME_TYPE);
$file = $finfo->file($_FILES['image']['tmp_name']); //This line checks MIME Type of uploaded image
if($file!=='image/jpeg' && $file !=='image/gif' || $tmp_image > 1024*1024*2){ //1024*1024*2 = 2MB
echo "Upload your Profile Image in jpg/gif format and lower than 2mb. Otherwise continue without Image.";
}
else{
$photo = move_uploaded_file($_FILES['image']['tmp_name'],'upload/comment/'.$name.$time.'.jpg');
$image = 'upload/comment/'.$name.$time.'.jpg';
echo '<script> alert("Your file is accepted.")</script>';
$stm->execute();
$message = 'Your Comment';
$name = 'Your Name';
$email = 'Your eMail';
}
}else{
$stm->execute();
$message = 'Your Comment';
$name = 'Your Name';
$email = 'Your eMail';
}
}
Please try with below snippet. You are preparing insert statement before variable initialization and image upload code. I have moved code below file upload code.
if(isset($_POST['submit'])){
$flag = 0;
$conn= new mysqli('localhost','root','','dilip');
if(!$conn){
die("Not connect".mysqli_error);
}
$name = $_POST['name'];
$message = $_POST['readerInput'];
$email = $_POST['email'];
$image='upload/comment/default.jpg';
$time = date("s");
//if(isset($_FILES['image'])){
if(is_uploaded_file($_FILES['image']['tmp_name'])){
$tmp_image = $_FILES['image']['size'];
$finfo = new finfo(FILEINFO_MIME_TYPE);
$file = $finfo->file($_FILES['image']['tmp_name']); //This line checks MIME Type of uploaded image
if($file!=='image/jpeg' && $file !=='image/gif' || $tmp_image > 1024*1024*2){ //1024*1024*2 = 2MB
echo "Upload your Profile Image in jpg/gif format and lower than 2mb. Otherwise continue without Image.";
$flag = 1;
}else{
$photo = move_uploaded_file($_FILES['image']['tmp_name'],'upload/comment/'.$name.$time.'.jpg');
$image = 'upload/comment/'.$name.$time.'.jpg';
echo '<script> alert("Your file is accepted.")</script>';
}
}
$stm = $conn->prepare("Insert into comment (Name, email, Message, Image) values (?, ?, ?, ?)");
$stm->bind_param($name,$email,$message,$image);
if($flag==0){
$stm->execute();
}
}
Related
I create a html page which have two file that i want to store these 2 different file i.e., Image and Signature in two different folder i.e., profile and signature folder. but Signature file stored in profile folder and Image file cant stored any of them. Please help me out.
here is my code
<?php
require 'config.php';
if(isset($_POST['submit'])){
$imagename = $_FILES["Image"]["name"];
$imagetemp = $_FILES["Image"]["tmp_name"];
$imagefolder = "Upload/profile/".$imagename;
move_uploaded_file($imagetemp, $imagefolder);
echo "<img src='$imagefolder' height='100px' width='100px'";
$signname = $_FILES["Signature"]["name"];
$signtemp = $_FILES["Signature"]["tmp_name"];
$signfolder = "signature/".$signname;
move_uploaded_file($signtemp, $signfolder);
echo "<img src='$signfolder' height='100px' width='100px'";
$Name = $_POST['Name'];
$gender = $_POST['gender'];
$phone = $_POST['phone'];
$location = $_POST['location'];
$Qualification = $_POST['Qualification'];
$Speciality = $_POST['Speciality'];
$Experience = $_POST['Experience'];
$License_No = $_POST['License_No'];
$Email = $_POST['Email'];
$Password = $_POST['Password'];
//$Image = $_POST['Image'];
//$Signature = $_POST['Signature'];
$sql = ("INSERT INTO doctor (Doctor_Name, gender, Phone, Location, Qualification, Speciality, Experience, License_No, Email, Password) value('$Name', '$gender', '$phone', '$location', '$Qualification', '$Speciality', '$Experience', '$License_No', '$Email', '$Password')");
$insertquery= mysqli_query($con, $sql);
if($insertquery){
echo "data inserted";
}
else{
echo "ERROR: $sql <br> $con->error";
}
$con->close();
}
I have tried a number of methods but my code still doesn't show images from the database on my website. When I click upload, I get an output of only the file name and file details but no photos are shown.
Here is my code that has to display the images.
<main>
<section align='center'>
<h1 id="rcorner2"align='center'style="font-size:30px; position:fixed;">Photo Library</h1>
<br><br>
<div class="wrapper">
<!--h2 align='left'>Photos</h2-->
<div class="photo-container">
<?php
include_once 'dbh.php';
$sql = "SELECT * FROM photos ORDER BY orderPhotos DESC";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "Error updating photo library!";
}else{
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
echo '<a href="#">
<div style="background-image: url(../libraries/photos/'.$row["imageFullName"].');"></div>
<h3>'.$row["filetitle"].'</h3>
<p>'.$row["filedescription"].'</p>
</a>';
}
}
?>
</div>
</div>
</section>
</main>
Connection to database
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "portal uploads";
$conn = mysqli_connect($servername, $username, $password, $dbname);
?>
And here is the database connection from the html form.
<?php
if(isset($_POST['upload'])) {
$newFileName = $_POST['filename'];
if(empty($newFileName)){
$newFileName = "photo";
}else{
//Replacing spaces in filename with underscores
$newFileName = strtolower(str_replace(" ", "-", $newFileName));
}
$filetitle = $_POST['filetitle'];
$filedescription = $_POST['filedescription'];
$file = $_FILES['file'];
$fileName = $file["name"];
$fileType = $file["type"];
$fileTempName = $file["tmp_name"];
$fileError = $file["error"];
$fileSize = $file["size"];
$fileExt = explode(".", $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array("jpg", "jpeg", "png");
//Error handling for allowed file types
if(in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if($fileSize < 10000000) {
//Make file unique through naming
$imageFullName = $newFileName . "." . uniqid("", true) . "." . $fileActualExt;
$fileDestination = "../libraries/photos/" . $imageFullName;
include_once "dbh.php";
//Checking for error handling when fields have been left empty
if(empty($filetitle) || empty($filedescription)) {
header("location:photos_edit.php?upload=empty");
exit();
} else {
$sql = "SELECT * FROM photos;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed!";
}else{
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$rowCount = mysqli_num_rows($result);
$setPhotoOrder = $rowCount + 1;
$sql = "INSERT INTO photos (filetitle, filedescription, imageFullName, orderPhotos) VALUES (?, ?, ?, ?);";
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed!";
}else{
mysqli_stmt_bind_param($stmt, "ssss", $filetitle, $filedescription, $imageFullName, $setPhotoOrder);
mysqli_stmt_execute($stmt);
move_uploaded_file($fileTempName, $fileDestination);
header("location: photos_edit.php?upload=success");
}
}
}
}else{
echo "Photo is too big!";
exit();
}
}else{
echo "An error ocurred while uploading your image!";
exit();
}
}else{
echo "File type not supported";
exit();
}
}
?>
For example, if you use this code, you can load an image from DB (MySQL) :)
<?php
$connection =mysql_connect("localhost", "root" , "");
$sqlimage = "SELECT * FROM userdetail where `id` = '".$id1."'";
$imageresult1 = mysql_query($sqlimage,$connection);
while($rows = mysql_fetch_assoc($imageresult1))
{
echo'<img height="300" width="300" src="data:image;base64,'.$rows['image'].'">';
}
?>
I am having the following registration script,where I the first name,email etc are inserted in the database via simple html form.
<?php
include("connect.php");
$error = "";
$response[]=array();
if(isset($_POST['submit'])){
$firstName = $_POST['fname'];
$lastName = $_POST['lname'];
$email = $_POST['email'];
$password = $_POST['password'];
$passwordConfirm = $_POST['passwordConfirm'];
$image = $_FILES['image']['name'];
$temp_image = $_FILES['image']['tmp_name'];
$imageSize = $_FILES['image']['size'];
//echo $firstName."<br/>".$lastName."<br/>".$email."<br/>".$password."<br/>".$passwordConfirm."<br/>".$image."<br/>".$imageSize."<br/>";
if(strlen($firstName)<3){
$error = "First name is too short";
}else if(strlen($lastName)<3){
$error = "Last name is too short";
}else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error = "Please enter valid email address";
}else if(strlen($password)<8){
$error = "Password must be greater than 8 characters";
}else if($password !== $passwordConfirm){
$error = "Password does not match";
}else if($image == ""){
$error = "Please upload your image";
}else{
$insertQuery = "INSERT INTO users(firstName,lastName,email,password,image) VALUES('$firstName','$lastName','$email','$password','$image')";
$result = mysqli_query($con,$insertQuery);
if($result){
//upload image in images forlder
$sql = "SELECT * FROM users";
$selectQuery = mysqli_query($con,$sql);
if($selectQuery){
while($row = mysqli_fetch_assoc($selectQuery)){
$response[] = $row;
}
}
if(move_uploaded_file($temp_image,"images/$image")){
$error = "You are successfully regirestered";
}else{
$error = "Image is not uploaded";
}
}
}
}
?>
<?php
echo $error."<br/>";
echo json_encode($response);
?>
All I am doing is validating the form,inserting data and finally selecting all data from the database so they can be represented as a JSON format.
The JSON I am getting is this.
[[],{"id":"37","firstName":"Theo","lastName":"Tziomakas","email":"theo899#gmail.com","password":"testingpass","image":"56a5e6dc-d102-4f9a-bd5b-e6a217e5ad97.png"}]
how can I take the empty array
[]
out of the JSON response ie.
[{"id":"37","firstName":"Theo","lastName":"Tziomakas","email":"theo899#gmail.com","password":"testingpass","image":"56a5e6dc-d102-4f9a-bd5b-e6a217e5ad97.png"}]
Also how can I generate a JSON like this?
{"status":"success","message":"Successfully registered"}
To remove the erroneous [] at the beginning of the JSON structure change this line
$response[]=array();
To
$response = array();
To generate a JSON structure like this
{"status":"success","message":"Successfully registered"}
I would do this
$j = new stdClass();
$j->status = 'success';
$j->message = 'Successfully registered';
$string = json_encode($j);
I have a form which when submitted, checks this query ->
if(isset($_POST['update']) && !empty($_POST['name']) && !empty($_POST['reg_name']))
I want to echo a message "Please fill up all the required fields." if the required fields are not filled up.
In short, it should highlight the field name which is not filled up.
The Full Code:
include ('database/abcd.php');
if ($con->connect_error)
{
die("Connection failed: " . $con->connect_error);
}
if(isset($_POST['update']))
{
$error = array();
if(empty($_POST['name']))
$error[] = 'Please fill name field';
if(empty($_POST['reg_name']))
$error[] = 'Pleae fill reg_name field';
if(count($error) < 1)
{
$name = $_POST['name'];
$reg_name = $_POST['reg_name'];
$established = $_POST['established'];
$industry = $_POST['industry'];
$about = $_POST['about'];
$website = $_POST['website'];
$mail = $_POST['mail'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$city = $_POST['city'];
$facebook = $_POST['facebook'];
$wiki = $_POST['wiki'];
$twitter = $_POST['twitter'];
$google = $_POST['google'];
$member_username = $_SESSION['username'];
$process="INSERT INTO notifications (member_username, process, icon, class) VALUES ('$_POST[member_username]','$_POST[process]','$_POST[icon]','$_POST[class]')";
if (!mysqli_query($con,$process))
{
die('Error: ' . mysqli_error($con));
}
$sql = "UPDATE `company_meta` SET `name` = '$name', reg_name = '$reg_name', wiki = '$wiki', established = '$established', industry = '$industry', about = '$about', website = '$website', mail = '$mail', phone = '$phone', address = '$address', city = '$city', facebook = '$facebook', twitter = '$twitter', google = '$google' WHERE `member_username` = '$member_username'";
if ($con->query($sql))
{
header('Location: edit.php');
}
}
else
{
$errors = implode(',' $error);
echo $errors;
}
$con->close();
}
I think what you are pass in name or reg_name is check first .may be name or reg_name can content white space so that it not showing message otherwise above code is working correctly..
if(isset($_POST['update'])) // This first check whether it is an update call
{
$error = array(); // Here we initialize an array so that we can put the messages in it.
if(empty($_POST['name'])) // If the name field is empty, push a message in $error array.
$error[] = 'Please fill name field';
if(empty($_POST['reg_name'])) // Same as above field
$error[] = 'Pleae fill reg_name field';
if(count($error) < 1) // Now this checks if the $error array has no value. If it has value it means that either or both of the above fields are empty and the else block will be executed.
{
// Submit your form
}
else
{
$errors = implode(',' $error);
echo $errors;
}
}
else
{
// Update not triggered.
}
I've looked around and haven't found particularly what I'm after.
I have quite a few forms with text input and file uploads.
I've figured how to upload a file, give it a unique ID and get it into my web server folder. Pretty smooth sailing. However, I would like to also get that fancy new ID into my MySQL database.
I've separated my upload.php page with text forms going to the database
<?php
//Connecting and Sending data to the database follows
$dbc = mysqli_connect('localhost', 'root', 'root', 'surfboardhub')
or die('Error connecting to MySQL server');
//Get values from
$location = "";
$price = "";
$thick = "";
$width = "";
$height ="";
$model = "";
$brand = "";
$email = "";
$category = "";
if(isset($_POST['location'])){ $location = $_POST['location']; }
if(isset($_POST['price'])){ $price = $_POST['price']; }
if(isset($_POST['thick'])){ $thick = $_POST['thick']; }
if(isset($_POST['width'])){ $width = $_POST['width']; }
if(isset($_POST['height'])){ $height = $_POST['height']; }
if(isset($_POST['model'])){ $model = $_POST['model']; }
if(isset($_POST['brand'])){ $brand = $_POST['brand']; }
if(isset($_POST['email'])){ $email = $_POST['email']; }
//if(isset($_POST['image'])){ $imagename = $_POST['imagename']; }
//if(isset($_POST['mime'])){ $mime = $_POST['mime']; }
$query = "INSERT INTO uploads (location, price, thick, width, height, model, brand, email,category)
VALUES ('$location', '$price','$thick','$width','$height', '$model', '$brand', '$email','$category')";
$result = mysqli_query($dbc,$query)
or die('Error querying database.');
mysqli_close($dbc);
and then my bit to get the file to its new location in my web server.
$name = $_FILES['image']['name'];
$extension = strtolower(substr($name, strpos($name, '.') + 1));
$type = $_FILES['image']['type'];
$tmp_name = $_FILES['image']['tmp_name'];
if (isset($name)) {
if (!empty($name)) {
if (($extension=='jpg'||$extension=='jpeg'||$extension=='png'||$extension=="gif")&&$type=='image/jpeg'||$type=='image/png'||$type=='image/gif') {
$location = 'uploads/';
$location = $location . uniqid();
if (move_uploaded_file($tmp_name, $location.$name)) {
echo 'uploaded!';
}
else {
echo 'There was an error.';
}
} else {
echo 'File must be jpg/jpeg, png, or gif.';
}
} else {
echo 'Please choose a file';
}
}
?>
Basically, I need to get that new unique ID to go to where the text information is going, because they're all being submitted at once. And I'd like to be able to figure out who uploaded what if need be. If it didn't have a unique ID I can get it to work, but for some reason having that uniqid trips me up. Thoughts? Much obliged.
Save the uniqid() to a PHP variable and then you can use it in more than one place:
First, create an ID:
<?php
$ID = uniqid();
?>
Then, save your file, using your new $ID variable:
<?php
$name = $_FILES['image']['name'];
$extension = strtolower(substr($name, strpos($name, '.') + 1));
$type = $_FILES['image']['type'];
$tmp_name = $_FILES['image']['tmp_name'];
if (isset($name)) {
if (!empty($name)) {
if (($extension=='jpg'||$extension=='jpeg'||$extension=='png'||$extension=="gif")&&$type=='image/jpeg'||$type=='image/png'||$type=='image/gif') {
$location = 'uploads/';
$location = $location . $ID;
if (move_uploaded_file($tmp_name, $location.$name)) {
echo 'uploaded!';
} else {
echo 'There was an error.';
}
} else {
echo 'File must be jpg/jpeg, png, or gif.';
}
} else {
echo 'Please choose a file';
}
}
?>
Then, save your data to the db, including $ID
<?php
//Connecting and Sending data to the database follows
$dbc = mysqli_connect('localhost', 'root', 'root', 'surfboardhub')
or die('Error connecting to MySQL server');
//Get values from
$location = "";
$price = "";
$thick = "";
$width = "";
$height ="";
$model = "";
$brand = "";
$email = "";
$category = "";
if(isset($_POST['location'])){ $location = $_POST['location']; }
if(isset($_POST['price'])){ $price = $_POST['price']; }
if(isset($_POST['thick'])){ $thick = $_POST['thick']; }
if(isset($_POST['width'])){ $width = $_POST['width']; }
if(isset($_POST['height'])){ $height = $_POST['height']; }
if(isset($_POST['model'])){ $model = $_POST['model']; }
if(isset($_POST['brand'])){ $brand = $_POST['brand']; }
if(isset($_POST['email'])){ $email = $_POST['email']; }
//if(isset($_POST['image'])){ $imagename = $_POST['imagename']; }
//if(isset($_POST['mime'])){ $mime = $_POST['mime']; }
$query = "INSERT INTO uploads (ID, location, price, thick, width, height, model, brand, email,category)
VALUES ('$ID', '$location', '$price','$thick','$width','$height', '$model', '$brand', '$email','$category')";
$result = mysqli_query($dbc,$query)
or die('Error querying database.');
mysqli_close($dbc);
?>