Issue with uploading a image into mysqli database - php

Since I added the function to upload a image my script doesn't work anymore .. That means I can't insert new posts into the datbase.
Please help me with this issue, thanks! For more questions just use the comments section below :)
PHP:
<?php
session_start();
header('content-type: text/html; charset=utf-8');
$uname = $_POST['username'];
$typ = $_POST['typ'];
$titel = $_POST['titel'];
$content = $_POST['content'];
$timestamp = time();
$db = new mysqli("localhost", "...", "...", "...");
if($db->connect_errno > 0){
die("Unable to connect to database: " . $db->connect_error);
}
if(is_uploaded_file($_FILES['image']['tmp_name'])) {
// Verweis auf Bild
$image = $_FILES['image']['tmp_name'];
// Vorbereiten für den Upload in DB
$data = addslashes(file_get_contents($image));
// Metadaten auslesen
$meta = getimagesize($image);
$mime = $meta['mime'];
}
//create a prepared statement
$stmt = $db->set_charset("utf8");
$stmt = $db->prepare("INSERT INTO artikel (`red`, `typ`, `titel`, `content`, `image`, `mimetype`, `timestamp`) VALUES (?,?,?,?,?,?,?)");
//bind the username and message
$stmt->bind_param('sssssss', $uname, $typ, $titel, $content, $data, $mime, $timestamp);
//run the query to insert the row
$stmt->execute();
header("Location: erfolg.php");
?>
html form:
<form name="form2" action="insert.php" method="post">
Username:<br>
<input style="width:100%;" type="text" accept-charset="utf-8" name="username" value="<?php echo $_SESSION['username']; ?>" class="login_form" readonly><br><br>
Typ:<br>
<input style="width:100%;" type="text" name="typ" value="blog" class="login_form" readonly><br><br>
Titel:<br>
<input style="width:100%;" type="text" placeholder="Überschrift, z.B. Die Kunst des Spickens" name="titel"><br><br>
Inhalt:<br>
<textarea style="width:100%; height:250px; font:Arial, Helvetica, sans-serif !important;" type="text" placeholder="Inhalt" name="content"></textarea><br><br>
Bild anhängen (maximal 1 Bild):<br>
<input name="image" type="file"><br><br>
<input type="submit" value="Eintragen">
</form>
So, this was the php and html, thanks for your help!
And sorry for the bad english

First of all, your form needs enctype="multipart/form-data" to upload files.
Second, wouldn't it be an idea to move the uploaded file from the temp dir and save the path in the database, instead of saving the complete binary data of the temporary image?
http://php.net/manual/en/function.move-uploaded-file.php

Related

During image update other images are returning empty except the one that I update

I've been trying a lot of different things to get the images to retain when other images are getting updated. Everything is good just except when I upload or update one of the images the other images are getting deleted or saved empty into the database.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
include ("connection.php");
include ("functions.php");
$user_data = check_login($con);
if(count($_POST)>0) {
if(!empty($_FILES['garden_photo1']['name'] . $_FILES['garden_photo2']['name']) && isset($_FILES["garden_photo1"]["name"], $_FILES['garden_photo2']['name'] )){
$id = $_POST['id'];
$cultivar_name = $_POST['cultivar_name'];
$breeder = $_POST['breeder'];
$lineage1 = $_POST['lineage1'];
$garden_photo1 = $_FILES['garden_photo1']['name'];
$ImageName = $_FILES['garden_photo1']['name'];
$ImageName2 = $_FILES['garden_photo2']['name'];
$target = "/cultivar/images/" . $ImageName;
$target2 = "/cultivar/images/" . $ImageName2;
move_uploaded_file($_FILES['garden_photo1']['tmp_name'], $target);
move_uploaded_file($_FILES['garden_photo2']['tmp_name'], $target2);
$stmt = $con->prepare("UPDATE cultivar_db set cultivar_name = ?, breeder = ?, lineage1 = ?, garden_photo1 = ?, garden_photo2 = ? WHERE id= ? ");
$stmt->bind_param( "sssssi", $cultivar_name, $breeder, $lineage1, $garden_photo1, $garden_photo2, $id);
$stmt->execute();
}else {
$id = $_POST['id'];
$cultivar_name = $_POST['cultivar_name'];
$breeder = $_POST['breeder'];
$lineage1 = $_POST['lineage1'];
$stmt = $con->prepare("UPDATE cultivar_db set cultivar_name = ?, breeder = ?, lineage1 = ? WHERE id= ? ");
$stmt->bind_param( "sssi", $cultivar_name, $breeder, $lineage1, $id);
$stmt->execute();
}
$message = "Cultivar Record Modified Successfully!";
}
$id = $_GET['id'];
$sql = "SELECT * FROM cultivar_db WHERE id=?";
$stmt = $con->prepare($sql);
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = mysqli_fetch_array($result);
?>
<html>
<head>
<title>Update Cultivar Data</title>
<style>
.success{color: green; font-size:20px; fonte-weight:bold;}
</style>
</head>
<body>
<form name="cultivar_db" method="post" enctype="multipart/form-data">
<div style="padding-bottom:5px;">
<p>Go Back to Cultivar Database > Edit <?php echo $row["cultivar_name"];?> Page</p>
</div>
<br>
<input type="hidden" name="id" value="<?php echo $row['id']; ?>" >
<br>
Cultivar Name: <br>
<input name="cultivar_name" value="<?php echo $row['cultivar_name']; ?>">
<br>
Breeder: <br>
<input type="text" name="breeder" value="<?php echo $row['breeder']; ?>">
<br>
Lineage 1 :<br>
<input type="text" name="lineage1" value="<?php echo $row['lineage1']; ?>">
<br>
Garden Photo 1: <img id="output" src="../cultivar/images/<?php echo $row["garden_photo1"];?>" style="height:auto; width:70px;">
<br>
<br>
<input id="garden_photo1" type="file" name="garden_photo1" >
<br>
Garden Photo 1: <img id="output" src="../cultivar/images/<?php echo $row["garden_photo2"];?>" style="height:auto; width:70px;">
<br>
<br>
<input id="garden_photo1" type="file" name="garden_photo2" >
<br>
<br>
<input id="submit" type="submit" name="submit" value="Submit" >
<br>
<br>
<div class="success">
<?php if(isset($message)) { echo $message; } ?>
</div>
</form>
</body>
</html>
Right now, you appear to be only differentiating between the two cases, no images were uploaded at all - or two images were uploaded. You need to handle the case(s) that either one of the images was uploaded, while the other one wasn't, as well.
But instead of writing different branches for all four possible combinations (no image was uploaded; image 1 was uploaded but image 2 was not; image 1 was not uploaded but image 2 was; or both were uploaded), it would make more sense if you handled each image upload separately:
Was image 1 uploaded? Then process that upload, and update the column for image 1 in your database.
Was image 2 uploaded? Then process that upload, and update the column for image 2 in your database.

Error when inserting image in MySQL with PHP

I am new to PHP, I make a form to insert in a database and I can not insert an error when I want to insert the image, in the database the type of the image is "longblob", I enclose the form and the. PHPto insert in the database.
Form:
<form align="center" action="guardar.php" method="POST" enctype="multipart/form-data">
<input type="text" REQUIRED name="titulo" placeholder="Titulo.." value=""/><br><br>
<input type="text" REQUIRED name="contenido" placeholder="Contenido.." value=""/><br><br>
<input type="text" REQUIRED name="fecha" placeholder="Fecha.." value=""/><br><br>
<input type="file" REQUIRED name="imagen" /><br><br>
<input type="submit" name="Aceptar" />
</form>
PHP
<?php
include("conexion.php");
$titulo=$_POST['titulo'];
$contenido=$_POST['contenido'];
$fecha=$_POST['fecha'];
$imagen=addslashes(file_get_contents($_FILES['imagen']['tmp_name']));
$query="INSERT INTO articulos(titulo,contenido,fecha,imagen) VALUES('$titulo','$contenido','$fecha','$imagen')";
mysqli_query($conexion, $query);
$resultado=$conexion->query($query);
if($resultado){
echo "INSERT";
}else{
echo "No INSERT";
}
?>
You should not use file_get_contents(), this is the wrong function for this - it does something else entirely (you can read the manual if you are curious what this function does). Instead of using a query that injects values directly, you should also use a prepared statement, as shown below.
This will prevent SQL-injection attacks, and make sure that no data will break the query.
<?php
include "conexion.php";
$titulo = $_POST['titulo'];
$contenido = $_POST['contenido'];
$fecha = $_POST['fecha'];
$imagen = $_FILES['imagen']['tmp_name'];
$query = "INSERT INTO articulos (titulo, contenido, fecha, imagen) VALUES (?, ?, ?, ?)";
if ($stmt = $conexion->prepare($query)) {
$stmt->bind_param("ssss", $titulo, $contenido, $fecha, $imagen);
if ($stmt->execute()) {
echo "Inserted");
} else {
// Do some logging
error_log($stmt->error);
echo "Not inserted";
}
} else {
// Do some logging
error_log($conexion->error);
echo "Not inserted";
}

when saving text and images in the database undefined variable error occur.How to solve?

I am new to php. So some person, this question may be very childish.But still I can't solve this. I want to save image path in database and save user's other text inputs in a same table.But it gives this error **Notice: Undefined index: age in **.Can you please help me?
<?php
// Create database connection
$db = mysqli_connect("localhost", "root", "", "construction");
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = $_FILES['image']['name'];
// Get text
$image_text = mysqli_real_escape_string($db, $_POST['image_text']);
$age = mysqli_real_escape_string($db, $_POST['age']);
// image file directory
$target = "uploads/".basename($image);
$sql = "INSERT INTO images (image_path, description,age) VALUES ('$image', '$image_text','$age')";
// execute query
mysqli_query($db, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="POST" action="imageUpload.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea id="text" cols="40" rows="4" name="image_text" placeholder="Say something about this image..."></textarea>
<input type="text" name="age">
</div>
<div>
<button type="submit" name="upload">POST</button>
</div>
</form>
</div>
</body>
</html>

PHP & MySQL - not inserting into database

I've got an problem in my code. The insert is not working. The code is below.
HTML:
<form action="staff.php" method="post" class="center" enctype="multipart/form-data" autocomplete="off">
<input type="hidden" name="size" value="1000000">
<input type="text" placeholder="headline of the news" name="title">
<input type="file" accept="image/*" name="image">
<select name="side" value="side">
<option>Left</option>
<option>Header</option>
<option>Main</option>
<option>Ending</option>
</select>
<textarea name="desc" id="description" cols="30" rows="10" placeholder="full news" name="desc"></textarea>
<input type="submit" name="go" value="Post">
</form>
PHP:
<?php
$db = mysqli_connect("DB SERVER", "DB USER", "DB PASS", "DataBase");
$charset = mysqli_set_charset($db,"utf8");
$msg = "";
if (isset($_POST['go'])) {
$target = "images/".basename($_FILES['image']['name']);
$title = $_POST['title'];
$image = $_FILES['image']['name'];
$side = $_POST['side'];
$desc = $_POST['desc'];
$sql = "INSERT INTO contents (title, image, side, description)
VALUES ('$title', '$image', '$side', '$desc')";
$result = mysqli_query($db, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "<p class='success'>Image uploaded successfully</p>";
} else {
$msg = "<p class='error'>There was a problem uploading the image</p>";
}
}
?>
Everything is fine except the inserting into database.
add concatenation in the query like this
$sql = "INSERT INTO contents (title, image, side, description)
VALUES ('".$title."', '".$image."', '".$side."', '".$desc."')";
Your query is fine, it should work.
But you're allowing SQL injections, so if you send within parameter single quotes your query will not work as expected and will throw out an error...
You should first:
clear passed strings (use mysqli_real_escape_string), http://php.net/manual/en/mysqli.real-escape-string.php
Check if mysqli_query executed if not then use mysqli_error to find out what error caused your query to not work: http://php.net/manual/en/mysqli.error.php
$sql = "INSERT INTO contents VALUES ('".$title."', '".$image."', '".$side."', '".$desc."')";
This could be a shorter way.
Use as
<?php
$db = mysqli_connect("DB SERVER", "DB USER", "DB PASS", "DataBase") or die(mysqli_error("Could not connect to Database"));
mysqli_query($db,"SET NAMES 'utf8'");
$msg = "";
if (isset($_POST['go'])) {
$target = "images/".basename($_FILES['image']['name']);
$title = mysqli_real_escape_string($db,$_POST['title']);
$image = mysqli_real_escape_string($db,$_FILES['image']['name']);
$side = mysqli_real_escape_string($db,$_POST['side']);
$desc = mysqli_real_escape_string($db,$_POST['desc']);
$sql = "INSERT INTO contents (title, image, side, description)
VALUES ('$title', '$image', '$side', '$desc')";
$result = mysqli_query($db,$sql) or die(mysqli_error($db));
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "<p class='success'>Image uploaded successfully</p>";
}else{
$msg = "<p class='error'>There was a problem uploading the image</p>";
}
}
?>
$sql = "INSERT INTO contents (title, image, side, description) VALUES ('".$title."', '".$image."', '".$side."', '".$desc."')";
The problem is here use this.

PHP MySqli query didn't work

I want to insert data to my DB, but the query didn't work. I was using this code in another page, but it work. And for this page it seems didn't work.
This my upload.php
<?php
include_once("connect.php");
//Fetching Values from URL
if (isset($_POST['submit'])) {
$nama_program=$_POST['nama_program'];
$deskripsi=$_POST['deskripsi'];
$code=$_POST['link_youtube'];
$link_youtube="<iframe width='420' height='315' src='https://www.youtube.com/embed/".$code."' frameborder='0' allowfullscreen></iframe>";
$link_twitter=$_POST['link_twitter'];
$rating=$_POST['rating'];
$image=$_POST['uploafimage'];
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["uploadimage"]["name"]);
$result=$mysqli->query("INSERT INTO program(nama, deskripsi, link_youtube, link_twitter, image, rating, slider, twtiter) VALUES('$nama_program','$deskripsi','$link_youtube','$link_twitter','$target_file','$rating', 0, 0)");
if($result === TRUE){
echo "Congrats Your data hase been saved";
} else{
echo"There is eror here".$result;
}
} else{
echo "Error";
}
?>
This is my form look like
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="text" class="form-control" id="nama_program" name="nama_program">
<textarea class="form-control textarea" name="deskripsi" id="deskripsi"></textarea>
<textarea class="form-control textarea" name="link_youtube" id="link_youtube"></textarea>
<textarea class="form-control textarea" name="link_twitter" id="link_twitter"></textarea>
<select name="rating" id="rating" class="form-control">
<option>Rating</option>
<option>1</option>
<option>2</option>
<option>3</option>
<input type="file" name="uploadimage" id="uploadimage">
<button type="submit" class="btn btn-info">
submit
</button>
</form>
What's wrong with mysqli ? I use this enctype="multipart/form-data" because i want to upload image, but first the query didn't work.
This is my connect.php
<?php
$host = "localhost";
$user = "*****";
$pass = "****";
$dbnm = "*******";
$mysqli = new mysqli($host, $user, $pass, $dbnm);
if($mysqli->connect_errno > 0){
die('Unable to connect to database [' . $mysqli->connect_error . ']');
}
?>
mysqli_query($yourcon,"INSERT INTO program(nama, deskripsi, link_youtube, link_twitter, image, rating, slider, twtiter) VALUES ('$nama_program','$deskripsi','$link_youtube','$link_twitter','$target_file','$rating', 0, 0)");
Give more Explanation about question and errors you getting for batter
solution.

Categories