PHP articles and images issue - php

This is still not working, so I'm posting whole code here now...
<form id="contact-form" action="fileovi/dodaj_novost.php" method="post">
<fieldset>
<div class="coll-1">
<div class="txt-form">Naslov[hr]</div>
<label class="name">
<input type="text" name="naslov_hr">
<br>
</div>
<div class="clear"></div>
<div class="coll-1">
<div class="txt-form">Naslov[en]</div>
<label class="name">
<input type="text" name="naslov_en">
<br>
</div>
<div class="clear"></div>
<div class="clear"></div>
<div class="coll-1">
<div class="txt-form">Naslov[de]</div>
<label class="name">
<input type="text" name="naslov_de">
<br>
</div>
<div class="clear"></div>
<div class="clear"></div>
<div class="coll-1">
<div class="txt-form">Link slike</div>
<label class="name">
<input type="file" name="image[]" enctype="multipart/form-data"/><br />
<input type="file" name="image[]" enctype="multipart/form-data"/><br />
<br>
</div>
<div class="clear"></div>
<div class="clear"></div>
<div class="coll-big">
<div class="txt-form"><center>Tekst[hr]</center></div>
<label class="name">
<textarea id="tekst" name="tekst_hr"></textarea>
<br>
</div>
<div class="clear"></div>
<div class="coll-big">
<div class="txt-form"><center>Tekst[en]</center></div>
<label class="name">
<textarea id="tekst1" name="tekst_en"></textarea>
<br>
</div>
<div class="clear"></div>
<div class="coll-big">
<div class="txt-form"><center>Tekst[de]</center></div>
<label class="name">
<textarea id="tekst2" name="tekst_de"></textarea>
<br>
</div>
<div class="clear"></div>
Dodaj!
</form>
And here's my php function that I've created...
function dodaj_novost()
{
global $mysqli;
$mysqli->query("SET NAMES utf8");
$mysqli->query("SET CHARACTER SET utf8");
$mysqli->query("SET COLLATION_CONNECTION='utf8_general_ci'");
//sanitize variables
$naslovhr = $_POST['naslov_hr'];
$naslovhr = $mysqli->real_escape_string($naslovhr);
$nasloven = $_POST['naslov_en'];
$nasloven = $mysqli->real_escape_string($nasloven);
$naslovde = $_POST['naslov_de'];
$naslovde = $mysqli->real_escape_string($naslovde);
$teksthr = $_POST['tekst_hr'];
$teksthr = $mysqli->real_escape_string($teksthr);
$teksten = $_POST['tekst_en'];
$teksten = $mysqli->real_escape_string($teksten);
$tekstde = $_POST['tekst_de'];
$tekstde = $mysqli->real_escape_string($tekstde);
//sanitize variables END
$dan = date('d');
$mjesec = date('M');
$godina = date('Y');
$sql="INSERT INTO novosti (naslovhr, nasloven, naslovde, teksthr, teksten, tekstde, dan, mjesec, godina) VALUES ($naslovhr,$nasloven, $naslovde,$teksthr,$teksten,$tekstde,$dan,$mjesec,$godina)";
$query = $mysqli->query("$sql");
//Add picture!
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$max_size = 2048 * 1024; // max file size (200kb)
$path = 'uploads/'; // upload directory
if(isset($_FILES['image'])){
for($i=0; $i<count($_FILES['image']['name']); $i++){
if( #is_uploaded_file($_FILES['image']['tmp_name'][$i]) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image']['name'][$i], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image']['size'][$i] < $max_size)
{
// unique file path
$filename = uniqid(). '.' .$ext;
// move uploaded file from temp to uploads directory
if (move_uploaded_file($_FILES['image']['tmp_name'][$i], $path.$filename))
{
$status = $path.$filename;
$link = 'http://'.$domena.'/'.$path.'/'.$filename;
$upit = "INSERT INTO slike_novosti (link, id_posta) VALUES ($link, $id_posta)";
$upit = $mysqli->query("$upit");
if ($upit == 'true'){
echo 'Successfull!';
} else {
echo 'Not sucessfull!';
}
}
else {
$status = 'Upload Fail: Unknown error occurred!';
}
}
else {
$status = 'Upload Fail: Unsupported file format or It is too large to upload!';
}
}
else{
//image is not uploaded!
$status = ' ';
}
echo '<br>'.$status.'<br>';
}
} else {
echo 'Nema slike!';
}
//Add picture END!!
}
And for some reason this code is still not working, If someone can point me in right direction on how to solve this problem.. I would be soo happy! :) Cheers.

At first:
$sql1 = "INSERT INTO slike_novosti (slika, link_slike) VALUES ('$link_slike','$slika')";
check order of your variables? I think, it must be:
$sql1 = "INSERT INTO slike_novosti (slika, link_slike) VALUES ('$slika','$link_slike')";
at second: Use PDO component, you have a very bad code and SQL Injection.

Remove the single qoutes from your $variables. For PHP '$var' is a variable with the value of $var. If you want them qouted, use "$var". See variables
So this wil work
$sql="INSERT INTO novosti (naslovhr, nasloven, naslovde, teksthr, teksten, tekstde,
link_slike, dan, mjesec, godina) VALUES
$naslovhr,$nasloven,$naslovde,$teksthr,
$teksten,$tekstde,$link_slike,$dan,$mjesec,$godina)";

Related

menu_id is not inserted into table .How to insert my sql database?

menu_id is not inserted in the table, how to insert it. Only 0 is inserted in the table. Uncaught ReferenceError: tinymce is not defined at add-category.php:63:3 I am getting this error I have given the image below, please see it and let me know I have tried several times and I am getting errors.i am new devloper
<?php include_once('functions.php'); ?>
<?php
if (isset($_POST['btnAdd'])) {
$category_name = $_POST['category_name'];
$menu_id = $_POST['menu_id'];
// get image info
$menu_image = $_FILES['category_image']['name'];
$image_error = $_FILES['category_image']['error'];
$image_type = $_FILES['category_image']['type'];
// create array variable to handle error
$error = array();
if(empty($category_name)){
$error['category_name'] = " <span class='label label-danger'>Must Insert!</span>";
}
if(empty($category_name)){
$error['menu_id'] = " <span class='label label-danger'>Must Insert!</span>";
}
// common image file extensions
$allowedExts = array("gif", "jpeg", "jpg", "png");
// get image file extension
error_reporting(E_ERROR | E_PARSE);
$extension = end(explode(".", $_FILES["category_image"]["name"]));
if($image_error > 0) {
$error['category_image'] = " <span class='font-12 col-red'>You're not insert images!!</span>";
} else if(!(($image_type == "image/gif") ||
($image_type == "image/jpeg") ||
($image_type == "image/jpg") ||
($image_type == "image/x-png") ||
($image_type == "image/png") ||
($image_type == "image/pjpeg")) &&
!(in_array($extension, $allowedExts))){
$error['category_image'] = " <span class='font-12'>Image type must jpg, jpeg, gif, or png!</span>";
}
if(!empty($category_name) && empty($error['category_image'])&& empty($error['menu_id'])){
// create random image file name
$string = '0123456789';
$file = preg_replace("/\s+/", "_", $_FILES['category_image']['name']);
$function = new functions;
$menu_image = $function->get_random_string($string, 4)."-".date("Y-m-d").".".$extension;
// upload new image
$upload = move_uploaded_file($_FILES['category_image']['tmp_name'], 'upload/category/'.$menu_image);
// insert new data to menu table
$sql_query = "INSERT INTO tbl_category (category_name, category_image,menu_id)
VALUES(?, ?,?)";
$upload_image = $menu_image;
$stmt = $connect->stmt_init();
if($stmt->prepare($sql_query)) {
// Bind your variables to replace the ?s
$stmt->bind_param('sss',
$category_name,
$upload_image,
$menu_id
);
// Execute query
$stmt->execute();
// store result
$result = $stmt->store_result();
$stmt->close();
}
if($result) {
$error['add_category'] = "<br><div class='alert alert-info'>New Category Added Successfully...</div>";
} else {
$error['add_category'] = "<br><div class='alert alert-danger'>Added Failed</div>";
}
}
}
$sql_category = "SELECT * FROM menu ORDER BY mid DESC";
$category_result = mysqli_query($connect, $sql_category);
?>
<section class="content">
<ol class="breadcrumb">
<li>Dashboard</li>
<li>Manage Category</li>
<li class="active">Add Category</a></li>
</ol>
<div class="container-fluid">
<div class="row clearfix">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<form id="form_validation" method="post" enctype="multipart/form-data">
<div class="card">
<div class="header">
<h2>ADD CATEGORY</h2>
<?php echo isset($error['add_category']) ? $error['add_category'] : '';?>
</div>
<div class="body">
<div class="row clearfix">
<div>
<div class="form-group form-float col-sm-12">
<div class="form-line">
<input type="text" class="form-control" name="category_name" id="category_name" required>
<label class="form-label">Category Name</label>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input type="file" name="category_image" id="category_image" id="category_image" class="dropify-image" data-max-file-size="1M" data-allowed-file-extensions="jpg jpeg png gif" />
<div class="div-error"><?php echo isset($error['category_image']) ? $error['category_image'] : '';?></div>
</div>
</div>
<div class="form-group form-float col-sm-12">
<div class="form-group">
<div class="font-12">Category *</div>
<select class="form-control show-tick" name="menu_id" id="menu_id">
<?php while ($data = mysqli_fetch_array ($category_result)) { ?>
<option value="<?php echo $data['mid '];?>"><?php echo $data['menu_Name'];?></option>
<?php } ?>
</select>
</div>
</div>
<div class="col-sm-12">
<button class="btn bg-blue waves-effect pull-right" type="submit" name="btnAdd">SUBMIT</button>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</section>

How to insert images with text data to database in php using mysql.?

I have a long-form with some images upload areas. I need to insert images with text data to MySQL database The form and query code as follows. If PHP codes are not correct, tell me how to do it correctly.?
<div class="container">
<div class="row">
<div class="col-md-4">
<div class="form_main">
<h4 class="heading"><strong>Add</strong> Vehicle <span></span></h4>
<div class="form">
<form action="insert.php" method="POST" id="contactFrm" enctype="multipart/form-data" name="contactFrm">
<select class="form-control form-control-lg" name="brand">
<option value="TATA" >TATA</option>
<option value="TOYOTA">TOYOTA</option>
<option value="DAIHATSu">DAIHATSU</option>
</select>
<input type="text" required="" placeholder="Model" name="model" class="txt">
<div class="form-group">
<label for="exampleFormControlFile1">Front</label>
<input type="file" name="vehi_front" class="form-control-file" id="exampleFormControlFile1">
</div>
<div class="form-group">
<label for="exampleFormControlFile1">Left</label>
<input type="file" name="vehi_left" class="form-control-file" id="exampleFormControlFile1">
</div>
<div class="form-group">
<label for="exampleFormControlFile1">Right</label>
<input type="file" name="vehi_right" class="form-control-file" id="exampleFormControlFile1">
</div>
<div class="form-group">
<label for="exampleFormControlFile1">Rear</label>
<input type="file" name="vehi_back" class="form-control-file" id="exampleFormControlFile1">
</div>
<textarea placeholder="Other" name="other" type="text" class="txt_3"></textarea>
<input type="submit" value="submit" name="submit" class="txt2">
</form>
</div>
</div>
</div>
</div>
</div>
This is the insert query code.
<?php
include("../inc/conn.php");
$brand=$_POST['brand'];
$model=$_POST['model'];
$vehi_front=$_POST['vehi_front'];
$vehi_left=$_POST['vehi_left'];
$vehi_right=$_POST['vehi_right'];
$vehi_back=$_POST['vehi_back'];
$other=$_POST['other'];
{
$sql = "INSERT INTO vehicle(brand,model,vehi_front,vehi_left,vehi_right,vehi_back,other) VALUES ('{$brand}','{$model}','{$vehi_front}','{$vehi_left}','{$vehi_right}','{$vehi_back}','{$other}')";
if(mysqli_query($con,$sql))
{
header("location:add_vehicle.php?msg=Successfully Saved !");
}
}
?>
you must create image uploader function
in php $_POST['image_input_name'] return you null
you must use $_FILE
function uploadPic($file_input_name, $path)
{
if (isset($_FILES[$file_input_name])) {
$file = $_FILES[$file_input_name];
// for bin2hex and random_bytes you must use php > 7
$new_name = (string)bin2hex(random_bytes(32));
$extension = ".jpg";
$final_name = $new_name . $extension;
move_uploaded_file($file['tmp_name'], $path . $final_name);
return $path . $final_name;
}
}
first line check for image
2 get the file and put in into $file
3 change the name for security
4 change the extension for more security
// user upload a shel.php. in function we change the name and extension
// for exp shel.php converted to hs7f4w8r5c1f4s5d9t6g3s149748654asdasd.jpg
5 add name and extension in var
6 we move uploaded pic to path
7 we return the address and name of pic
and in your new code here
<?php
include("../inc/conn.php");
$brand = $_POST['brand'];
$model = $_POST['model'];
// in if we check for image exist
if ($_FILES['vehi_front']['tmp_name'] != "") {
$vehi_front = $this->uploadPic("vehi_front", "/path/to/save/image");
}
if ($_FILES['vehi_left']['tmp_name'] != "") {
$vehi_left = $this->uploadPic("vehi_left", "/path/to/save/image");
}
if ($_FILES['vehi_right']['tmp_name'] != "") {
$vehi_right = $this->uploadPic("vehi_right", "/path/to/save/image");
}
if ($_FILES['vehi_back']['tmp_name'] != "") {
$vehi_right = $this->uploadPic("vehi_back", "/path/to/save/image");
}
$other = $_POST['other'];
{
$sql = "INSERT INTO vehicle(brand,model,vehi_front,vehi_left,vehi_right,vehi_back,other) VALUES ('{$brand}','{$model}','{$vehi_front}','{$vehi_left}','{$vehi_right}','{$vehi_back}','{$other}')";
if (mysqli_query($con, $sql)) {
header("location:add_vehicle.php?msg=Successfully Saved !");
}
}
?>
You can do this using $_FILES variable
see reference here: https://www.php.net/manual/en/reserved.variables.files.php

Inserting into two database tables, parent and child, not working, likely something small

If anyone can point me to a similar solution, I initally had only one table (Dog) with basic data and one profile img.
I decided I would make an extra table, that will have the dogId as a FK for additional images.
My code works perfect if I keep the tables separate. When I create the FK in the images table, the code will not insert any data into the DB. I think the issue is something small.
i have two database tables, one is for a Dog includes name , age, gender etc and one profile image.
The second is the new table, for additional images, with a foreign key of dog Id in order to reference the dog the additional images belong to.
The issue i am having is, the basic upload of a dog profile was working perfect (uploading one main image and data, and entering into the database).
I made a new table for additional image uploads, and put a foreign key of the main Dog table into it. (id). this was to reference the dog the additional pics belong to.
I amended the code to include an additional form element:
<div class="form-group">
<label for="extra_images">Choose Images</label>
<input type="file" class="form-control"
name="userfile[]" value="" multiple="">
</div>
It will not upload to either table now, or show the multi images on the show_dog page (included last in code)
I am not sure if I am referencing the Foreign key correctly, or inserting that part correct. this could relate to:
$sql = "INSERT IGNORE INTO dog_img (name, img_dir, id) VALUES('$name',
'$img_dir', '$id')";
which is in the Functions section for:
if(isset($_FILES['userfile'])){......
//CODE BELOW
<form class="" action="create_dog.php" method="post"
enctype="multipart/form-data">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" <?
php echo $name ?> placeholder="Enter Name" value="" required>
</div>
<div class="form-group">
<label for="age">Age:</label>
<input type="text" class="form-control" name="age"
placeholder="Enter Age" value="" required>
</div>
<div class="form-group">
<label for="gender">Gender:</label>
<input type="text" class="form-control" name="gender"
placeholder="Enter Gender" value="" required>
</div>
<div class="form-group">
<label for="breed">Breed</label>
<input type="text" class="form-control" name="breed"
placeholder="Enter Breed" value="" required>
</div>
<div class="form-group">
<label for="description">Description</label>
<input type="text" class="form-control"
name="description" placeholder="Enter a Description" value="" required>
</div>
<div class="form-group">
<label for="image">Choose Image</label>
<input type="file" class="form-control" name="image"
value="">
</div>
<div class="form-group">
<label for="extra_images">Choose Images</label>
<input type="file" class="form-control"
name="userfile[]" value="" multiple="">
</div>
<div class="form-group">
<button type="submit" name="create_dog_btn" value
="upload" class="btn btn-primary waves">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
//functions
if (isset($_POST['create_dog_btn'])) {
create_new_dog();
}
function create_new_dog(){
global $conn;
global $upload_dir;
if (isset($_GET['id'])) {
$id = $_GET['id'];
$id=mysqli_real_escape_string($conn,trim($_GET['id']));
echo $id;
$sql = "SELECT * from dog where id=".$id;
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
}else {
$errorMsg = 'Could not Find Any Record';
}
}
//validation....... (cut out for tidyness sake)
if(empty($errors)){
$imgExt = strtolower(pathinfo($imgName,
PATHINFO_EXTENSION));
$allowExt = array('jpeg', 'jpg', 'png', 'gif');
$userPic = time().'_'.rand(1000,9999).'.'.$imgExt;
if(in_array($imgExt, $allowExt)){
if($imgSize < 5000000){
move_uploaded_file($imgTmp
,$upload_dir.$userPic);
}else{
$errors[] = 'Image too large';
}
}else{
$errors[] = 'Please select a valid image';
}
}
elseif(!empty($errors)){
foreach ($errors as $msg) {
echo "- $msg <br/>";
}
echo "<h4><br/>Please enter correct details!</h4>";
}
if(!isset($errors)){
$sql = "INSERT INTO dog(name, age, gender, breed,
description, image)
values('".$name."', '".$age."',
'".$gender."', '".$breed."', '".$description."',
'".$userPic."')";
$result = mysqli_query($conn, $sql);
if($result){
$successMsg = 'New dog added successfully';
header('Location: index_admin.php');
}else{
$errors[] = 'Error adding this record.
'.mysqli_error($conn);
if(!empty($errors)){
foreach ($errors as $msg) {
echo "- $msg <br/>";
}
//echo $errorMsg[];
}
}
}
}
function reArrayFiles($file_post){
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for($i=0; $i < $file_count; $i ++){
foreach($file_keys as $key){
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
if(isset($_FILES['userfile'])){
$phpFileUploadsErrors = array(
0=> 'there is no error, the fle uploaded with success',
1=> 'the file exceeds the upload max file size in php ini',
2=> 'the file exceeds the upload max file size specified in HTML
form',
3=> 'uploaded file only partially uploaded',
4=> 'no file was uploaded',
5=> 'missing a temporary folder',
6=> 'failed to write file to disk',
7=> 'a php extension stopped the file upload',
);
$file_array = reArrayFiles($_FILES['userfile']);
pre_r($_FILES);
for($i=0; $i<count($file_array); $i++){
if($file_array[$i]['error']){
?> <div class = "alert alert-danger">
<?php echo $file_array[$i]['name'].' -
'.$phpFileUploadsErrors[$file_array[$i]['error']];
?> </div> <?php
}
else{
$extensions = array('jpg', 'png', 'gif', 'jpeg');
$file_ext = explode('.', $file_array[$i]['name']);
//pre_r( $file_ext); die;
//image name variable at index 0 as per associative arrays
$name = $file_ext[0];
$name = preg_replace("!-!"," ", $name);
$name = ucwords($name);
$file_ext = end($file_ext);
//convert any uppercase extensions to lowercase whilst checking valid
extension
if(!in_array(strtolower($file_ext), $extensions)){
?> <div class = "alert alert-danger">
<?php echo "{$file_array[$i]['name']} Invalid file extension!";
?> </div> <?php
}
else{
$img_dir = "../uploads/".$file_array[$i]['name'];
move_uploaded_file($file_array[$i]['tmp_name'],$img_dir);
$sql = "INSERT IGNORE INTO dog_img (name, img_dir, id)
VALUES('$name',
'$img_dir', '$id')";
$conn->query($sql) or die($conn->error);
?> <div class = "alert alert-success">
<?php echo $file_array[$i]['name'].' -
'.$phpFileUploadsErrors[$file_array[$i]['error']];
?> </div> <?php
}
}
}
} //END OF FUNCTIONS
//SHOW DOG THE MULTI UPLOAD IMAGES WILL NOT DISPLAY
<div class="card-header">
SHOW DOG
</div>
<div class="card-body">
<div class="row">
<div class="col-md">
<img src="<?php echo $upload_dir.$row['image'] ?>"
height="200">
</div>
<div class="col-md">
<h5 class="form-control"><i class="fa fa-user-tag">
<span><?php echo $row['name'] ?></span>
</i></h5>
<h5 class="form-control"><i class="fa fa-mobile-alt">
<span><?php echo $row['age'] ?></span>
</i></h5>
<h5 class="form-control"><i class="fa fa-mobile-alt">
<span><?php echo $row['gender'] ?></span>
</i></h5>
<h5 class="form-control"><i class="fas fa-dog">
<span><?php echo $row['breed'] ?></span>
</i></h5>
<h5 class="form-control"><i class="fas fa-dog">
<span><?php echo $row['description'] ?></span>
</i></h5>
<a class="btn btn-outline-danger"
href="index_admin.php"><i class="fa fa-sign-out-alt"></i>
<span>Back</span></a>
</div>
</div>
</div>
</div>
</div>
<?php
$result = $conn-> query("SELECT * FROM dog_img") or die($conn-
>error);
echo "test";
while($data = $result->fetch_assoc()){
echo "<h2>{$data['name']} </h2>";
echo "<img src='{$data['img_dir']}' width ='40%'
height='40%'>";
}
?>
</div>
Any help would be appreciated, I accept my code is very long, but I am really stuck with this.
thank you.

Why does the image i uploaded do not save in the database and in the folder i assigned it to?

i don't understand why the image i upload when i create news doesn't save both in my database and in the folder. there's no error either that's why i couldn't figure out what's wrong with my code.
here's my createNews.php
<form action="/cn/admin/post_news.php" method="post" enctype="multipart/form-data">
<div class="control-group form-group">
<div class="controls">
<label>Title</label>
<input type="text" name="title" class="form-control">
<p class="help-block"></p>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Image:</label>
<input type="file" name="file" multiple accept='image/*' >
<p class="help-block"></p>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Body:</label><br>
<textarea rows="10" cols="100" name="body" class="form-control" id="body" maxlength="999" style="resize:none"></textarea>
</div>
</div>
<input type="submit" name="submit" value="Post News" style="float: right"/>
</form>
and this is my post_news.php where the process happens.
<?php
date_default_timezone_set('Asia/Manila');
include_once('db.php');
if(isset($_POST['submit'])) {
$title = $_POST['title'];
$body = $_POST['body'];
$date = date('Y-m-d H:i:s');
$title= stripslashes($title);
$body= stripslashes($body);
$title = mysql_real_escape_string($title);
$body = mysql_real_escape_string($body);
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$type = $_FILES['file']['type'];
$size = $_FILES['file']['size'];
$loc = $_FILES['file']['tmp_name'];
$destination = "/cn/news-images/";
$new_size=$size/1024; // file size in KB
// make file name in lower case
$new_file_name = strtolower($file);
// make file name in lower case
$final_file=str_replace(' ','-',$new_file_name);
$servername = "localhost";
$username="root";
$password = "";
$database = "cn";
$connection = new mysqli($servername, $username, $password, $database);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
if(move_uploaded_file($loc,$destination.$final_file)) {
$sql = "INSERT INTO news (title, body, name, date, photo, type, size) VALUES('$title','$body','$name','$date','$final_file','$type','$new_size')";
mysql_query($sql);
echo "<script type='text/javascript'>alert('Your news has been posted!'); window.location.assign('home.php');</script>";
}
else
{
$sql = "INSERT INTO news (title, body, name, date, photo, type, size) VALUES('$title','$body','$name','$date','','', '0')";
mysql_query($sql);
echo "<script type='text/javascript'>alert('Your news has been posted!'); window.location.assign('home.php');</script>";
}
}
?>
Since you are using Mysqli so Instead of using mysql_query($sql), use $connection->query($sql)
..and file saves to tmp dir. if you wants to place it in any place see
http://php.net/manual/en/function.move-uploaded-file.php
after
$destination = "/cn/news-images/";
about write to DB.....mb got it in post before...

Failed to upload a file in PHP

I try to upload an image, but it is not working. Other variables I have set are inserted into database, but image file is not... I was trying to check submit with isset, but it is not working. Where is my error?
Thanks for your help.
PHP file:
<?php
include ('includes/config.php');
$mysqli = new mysqli(DB_SERVER,DB_UNAME,DB_PASSWD,DB_NAME);
if($mysqli->connect_errno) {
echo "MYSQLI connect error no {$mysqli->connect_errno} : {$mysqli->connect_error}";
die();
}
$itemcode = $_POST['icode'];
$itemname = $_POST['iname'];
$brandname = $_POST['brandname'];
$upload = basename ($_FILES['upload']['name']);
$path = "img/";
if(!empty($upload)) {
$i1 = strrpos($upload,".");
if (!$i1) {
return "";
}
$l1 = strlen($upload) - $i1;
$ext1 = substr($upload,$i1+1,$l1);
$ext1 = strtolower($ext1);
$news_name1=time()+(1).'.'.$ext1;
$newname1 = $path.$news_name1;
$copied1 = copy($_FILES['upload']['tmp_name'], $newname1);
} else {
$news_name1 = '';
}
$iadd = $mysqli->prepare("INSERT INTO table_item (`itemcode`,`itemname`,`brandname`,`upload`) VALUES ('".$itemcode."', '".$itemname."','".$brandname."','".$news_name1."') ");
$iadd->execute();
$iadd->close();
$mysqli->close();
?>
This is my HTML file:
<form class="cmxform form-horizontal tasi-form" name="form2" id="form2" method="post" action="">
<div class="form-group ">
<label for="icode" class="control-label col-lg-2">Item Code</label>
<div class="col-lg-10">
<input class=" form-control" id="icode" name="icode" type="text" />
</div>
</div>
<div class="form-group ">
<label for="iname" class="control-label col-lg-2">Item Name</label>
<div class="col-lg-10">
<input class=" form-control" id="iname" name="iname" type="text" />
</div>
</div>
<div class="form-group ">
<label for="brandname" class="control-label col-lg-2">Brand Name</label>
<div class="col-lg-10">
<input class=" form-control" id="brandname" name="brandname" type="text" />
</div>
</div>
<fieldset style="width:48%; float:left;"> <!-- to make two field float next to one another, adjust values accordingly -->
<label>Doc 2</label>
<input style="margin: 0 10px;" type="file" name="upload" size="50">
</fieldset>
Add 'enctype="multipart/form-data"' to your form tag attributes, you can read more about file uploading here.
Also consider checking the values of the post, because your current method can get you sql injections
add form attribute enctype="multipart/form-data"
You have not proper syntax used and also use 'enctype="multipart/form-data"'.
I have implemented your code
<?php
include ('includes/config.php');
$mysqli = new mysqli(DB_SERVER,DB_UNAME,DB_PASSWD,DB_NAME);
if($mysqli->connect_errno){
echo "MYSQLI connect error no {$mysqli->connect_errno} : {$mysqli->connect_error}";
die();
}
$itemcode = $_POST['icode'];
$itemname = $_POST['iname'];
$brandname = $_POST['brandname'];
$upload = basename ($_FILES['upload']['name']);
$path = "img/";
if(!empty($upload)){
$i1 = strrpos($upload,".");
if (!$i1) { return ""; }
$l1 = strlen($upload) - $i1;
$ext1 = substr($upload,$i1+1,$l1);
$ext1 = strtolower($ext1);
$news_name1=time()+(1).'.'.$ext1;
$newname1 = $path.$news_name1;
$copied1 = $_FILES['upload']['tmp_name'], $newname1;
}else{
$news_name1 = '';
}
$iadd = $mysqli->prepare("INSERT INTO table_item (`itemcode`,`itemname`,`brandname`,`upload`) VALUES ('".$itemcode."', '".$itemname."','".$brandname."','".$news_name1."') ");
$iadd->execute();
$iadd->close();
$mysqli->close();
?>

Categories