Date not being stored in database from .xlsx sheet in PHP - php

I have a page to save an excel sheet records to the database. The records are being stored same way as they are provided in excel sheet other than "date of birth" column.
The "Date of Birth" column saves only for the second record being uploaded from excel sheet. I had been searching a lot on this but not found the exact reason for it.
Here is my complete code ,
<?php include 'blocks/headerInc.php' ;
include 'Classes/PHPExcel/IOFactory.php';
?>
<?php
$scsmsg = "" ;
$errmsg = "" ;
if(isset($_POST['submit']))
{
extract($_POST);
//$moduleId = mysql_real_escape_string(htmlspecialchars(trim($module_id)));die;
if(empty($_FILES['bulk_file']['name']))
{
$errmsg .= 'Please Choose File.<br>';
}
if(!empty($_FILES['bulk_file']['name']))
{
$extensions = array('.xlsx');
$valid_extensions = '.xlsx';
$extension = strrchr($_FILES['bulk_file']['name'], '.');
if (!in_array($extension, $extensions))
{
$errmsg .="Wrong files format , alowed Extension only".$valid_extensions.""."<br>";
}
}
if($errmsg == "")
{
$created = date("Y-m-d h:i:s");
$register_date = date("Y-m-d");
$created_by = $_SESSION['session_admin_id'] ;
$bulk_file = $_FILES['bulk_file']['name'];
if(!empty($bulk_file))
{
$tmp_name=$_FILES['bulk_file']['tmp_name'];
$bulk_file=$_FILES['bulk_file']['name'];
$file_name = $bulk_file;
//$file=$file_name.".csv";
$inputFileName = "uploads/user/$file_name";
$file_sucess=move_uploaded_file($tmp_name,$inputFileName);
//$inputFileName = 'format.xlsx';
try {
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
} catch(Exception $e)
{
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet
for($i=2;$i<=$arrayCount;$i++)
{
$salutation = trim($allDataInSheet[$i]["A"]);
$sbiempid = trim($allDataInSheet[$i]["B"]);
$branch = trim($allDataInSheet[$i]["C"]);
$middlename = trim($allDataInSheet[$i]["D"]);
$firstname = trim($allDataInSheet[$i]["E"]);
$lastname = trim($allDataInSheet[$i]["F"]);
$dateofbirth = trim($allDataInSheet[$i]["G"]);
$dateInput = explode('-',$dateofbirth);
$dob = $dateInput[2].'-'.$dateInput[1].'-'.$dateInput[0];
// $dob ="19".date("Y-m-d", strtotime($dateofbirth));
//var_dump($dob);
//print_r($dob);
$mobileno = trim($allDataInSheet[$i]["H"]);
$email = trim($allDataInSheet[$i]["I"]);
$city = trim($allDataInSheet[$i]["J"]);
$state = trim($allDataInSheet[$i]["K"]);
$designation = trim($allDataInSheet[$i]["L"]);
$corporate_user_sql=mysql_fetch_array(mysql_query("select * from tbl_corporate where id='$created_by'"));
$pre_define_day=$corporate_user_sql['pre_defined_day'];
$dataQuestion = array("type"=>"3","salutation"=>$salutation, "employee_id"=>$sbiempid, "branch"=>$branch, "middle_name"=>$middlename, "first_name"=>$firstname, "last_name"=>$lastname, "dob"=> $dob, "mobile"=>$mobileno, "email"=>$email, "city"=>$city,"state"=>$state,"designation"=>$designation,"created_on"=>$created, "created_by"=>$created_by,"status"=>"0","register_date"=>$register_date,"request_updated_day"=>$pre_define_day,"registration_type"=>"1");
$db->query_insert("tbl_user", $dataQuestion);
$question_id = mysql_insert_id();
$raw_password=uniqid().$question_id;
$md5_pass=md5(uniqid().$question_id);
$dataOption1 = array("registration_id"=>$sbiempid."_".$question_id,"password"=>$md5_pass,"raw_password"=>$raw_password);
$db->query_update("tbl_user", $dataOption1,"id=$question_id");
}
}
$scsmsg = "<b>Record inserted Successfully</b>";
}
}
?>
<div class="container pagecontainer">
<!-- Static navbar -->
<div class="row row-offcanvas row-offcanvas-right">
<!--/.col-xs-12.col-sm-9-->
<div class="col-sm-3 col-md-3 sidebar" id="sidebar">
<div id="left_panel" class="clearfix left">
<?php include 'blocks/leftnavInc.php' ; ?>
</div>
</div>
<div class="col-xs-12 col-sm-9 page-right">
<div class="panel panel-primary">
<div class="panel-heading">Upload User</div>
<div class="panel-body">
<div class="column col-sm-offset-0">
<?php
if($scsmsg!="")
{
echo "<div class='success'>".ucwords($scsmsg)."</div>";
}
if($errmsg!="")
{
echo "<div class='error'>".ucwords($errmsg)."</div>";
}
echo "<div id='error'></div>";
?>
<form class="form-horizontal" method="post" action="" enctype="multipart/form-data">
<div class="form-group">
<div class="col-md-12">
<div class="col-md-3">
<label for="username" class="control-label">Select FIle:</label>
</div>
<div class="col-md-9">
<input type="file" name="bulk_file" class="form-control" required="" >
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<div class="col-md-3">
<label for="username" class="control-label">
Download Format</label>
</div>
<div class="col-md-9 text-right">
<button type="submit" name="submit" value="submit" class="btn btn-success"><i class="glyphicon glyphicon-floppy-disk"></i> Save</button>
<button type="reset" onClick="javascript:window.location.href='quizList.php';" class="btn btn-danger"><i class="glyphicon glyphicon-ban-circle"></i> Cancel</button>
<button type="reset" onclick="javascript:history.go(-1)" class="btn btn-danger"><i class="glyphicon glyphicon-ban-circle"></i> Go Back</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!--/.sidebar-offcanvas-->
</div>
</div>
<?php include 'blocks/footerInc.php'; ?>
May I know where am I doing wrong in this as rest of the data fields are being posted semantically. This stores date of birth only for the second record in the excel sheet and for rest rows date of birth are being saved as 0000-00-00.
Any suggestion and help will be highly appreciated.

I'd suggest that you don't request formatted values when you build the array from the spreadsheet content, use
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,false,true);
instead of
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
Then manually convert the raw timestamp date values from cells to the format you need for the database
$dateofbirth = PHPExcel_Shared_Date::ExcelToPHPObject($allDataInSheet[$i]["G"])
->format('Y-m-d');

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>

why <input = "file"> on modal can't pass image to php

I'm rookie at php and html, i have this modal that has in it which i need for inserting an image..
if (isset($_POST['add_roomtype_action'])) {
require 'script/addRoomType.php';
}
<div class="modal fade" id="add_roomtype_modal" tabindex="-1" role="dialog"
aria-labelledby="add_roomtype_modal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-
hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add Room Type</h4>
</div>
<form action="room_management.php" method="post"
autocomplete="off">
<div class="modal-body">
<input type="hidden" id="upd_roomtype_id" name =
"add_roomtype_idnm">
<label style="font-size: 10pt">Room Type : </label>
<input type="text" id="add_roomtype" name = "add_roomtypenm"
style="font-size: 10pt" ><br></br>
<label style="font-size: 10pt">Rate : </label>
<input type="text" id="addupd_rate" name = "add_ratenm"
style="font-size: 10pt" ><br></br>
<label style="font-size: 10pt">Image : </label>
<input type="file" id ="add_roomtypeImgid"
name="add_roomtypeImgnm" accept="image/x-png,image/jpeg">
</div>
<div class="modal-footer">
<button type="button" class="btn" data-
dismiss="modal">Close</button>
<button type="submit" class="btn" id = "add_roomtype_action"
name = "add_roomtype_action">Add</button>
</div>
</form>
</div>
</div>
</div>
and this is the php file which the modal will call
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "afgroms";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['add_roomtype_action'])){
$roomtypeid = $_POST['add_roomtype_idnm'];
$roomtype = $_POST['add_roomtypenm'];
$rate = $_POST['add_ratenm'];
$file = $_FILES['add_roomtypeImgnm'];
$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$fileType = $file['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg','jpeg','png');
if(in_array($fileActualExt, $allowed)){
if($fileError === 0)
{
if ($fileSize > 500000) {
mysql_query("UPDATE `tbl_roomtype` SET `RoomType` =
'$roomtype', `Rate` = '$rate', `Image` = '$img' WHERE RoomTypeID =
".$roomtypeid);
echo "<script>";
echo "alert(\"Successfully Added!\");";
echo "</script>";
}else{
echo "<script>";
echo "alert(\"File size too big!\");";
echo "</script>";
}
}else
{
echo "<script>";
echo "alert(\"There was an error\");";
echo "</script>";
}
}else
{
echo "<script>";
echo "alert(\"You cannot upload this type of file\");";
echo "</script>";
}
}
?>
but this error keep on occurring : Notice: Undefined index: add_roomtypeImgnm...
help me out here guys, i don't know whats the problem. I already tried to change the name and id of my and same error keeps on occurring.
The reason why you cannot post files is not your modal dialog but the fact that you are not using enctype="multipart/form-data" in your form.
Try it like this and it should work.

Can't add data through PHP and MySQL

Validate function
function validate(add_app_form){
var valid = true;
var userTxt = document.getElementById("patient_name").value;
var dateTxt = document.getElementById("app_date").value;
var timeTxt = document.getElementById("app_time").value;
var oldName = document.getElementById("select_old").value;
if(userTxt == "" && dateTxt == "" && timeTxt == "" && oldName == "choose")
{
//$("#lblTxt").text("Username and Password are required!");
$('#patient_name').css('border-color', 'red');
$('#app_date').css('border-color', 'red');
$('#app_time').css('border-color', 'red');
$('#select_old').css('border-color', 'red');
$("#add_app_lbl").text("Please Fill all the form");
valid = false;
}
if(userTxt == "" && oldName == "choose")
{
$('#patient_name').css('border-color', 'red');
$("#add_app_lbl").text("Please Add Patient Name Or select an old patient");
valid = false;
}
if(dateTxt == "")
{
$('#app_date').css('border-color', 'red');
$("#add_app_lbl").text("Please Add a Date");
valid = false;
}
return valid;
}
EDITED CODE
<?php
//Set error reporting on
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('../include/global.php');
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
if(isset($_POST['add_app_btn'])){
//Values From AJAX
$patient_name = $_POST['patient_name'];
$date_app = $_POST['app_date'];
$time_app = $_POST['app_time'];
$reason = $_POST['app_reason'];
$old_patient_id = $_POST['select_old'];
//If new patient
if($patient_name == "" && $old_patient_id != "choose")
{
try{
//See if date and time exist
$appExist = "SELECT * FROM appointment WHERE id_logged = :id_logged AND date_app = :date_app and time_app = : time_app";
$appExistStmt = $conn->prepare($appExist);
$appExistStmt->bindValue(":id_logged", $id_logged);
$appExistStmt->bindValue(":date_app", $date_app);
$appExistStmt->bindValue(":time_app", $time_app);
$appExistStmt->execute();
$appExistStmtCount = $appExistStmt->rowCount();
if($appExistStmtCount == 0)
{
//Add to appointment table
$appAdd = "INSERT INTO appointment(id_logged, patient_id, date_app, time_app, reason)
VALUES(:id_logged, :patient_id, :date_app, :time_app, :reason)";
$appAddStmt = $conn->prepare($appAdd);
$appAddStmt->bindValue(":id_logged", $id_logged);
$appAddStmt->bindValue(":patient_id", $old_patient_id);
$appAddStmt->bindValue(":date_app", $date_app);
$appAddStmt->bindValue(":time_app", $time_app);
$appAddStmt->bindValue(":reason", $reason);
$appAddStmt->execute();
echo "added";
}
else
{
echo "not added";
header("Location: add_appoint.php");
}
}
catch(PDOException $m)
{
$m->getMessage();
echo "error";
header("Location: add_app_btnoint.php");
}
}
}
?>
EDITED CODE 2
<form class="form-horizontal" id="add_app_form" method="post" action="add_appoint.php" onSubmit="return validate(this);">
<div class="box-body">
<div class="form-group">
<label for="patient_name" class="col-sm-3 control-label">Old Patient</label>
<div class="col-sm-4">
<select id="select_old" name="select_old">
<option value="choose">Choose Name</option>
<?php foreach($name_array as $na) { ?>
<option value="<?php echo $na['id'] ?>"><?php echo $na['patient_name'] ?></option>
<?php } ?>
</select>
</div>
<label for="patient_name" class="col-sm-1 control-label">New</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="patient_name" name="patient_name" placeholder="New Patient Name">
</div>
</div>
<div class="form-group">
<label for="app_date" class="col-sm-2 control-label">Date</label>
<div class="col-sm-4">
<input type="date" class="form-control" id="app_date" name="app_date">
</div>
<label for="app_time" class="col-sm-2 control-label">Time</label>
<div class="col-sm-4">
<input type="time" class="form-control" id="app_time" name="app_time">
</div>
</div>
<div class="form-group">
<label for="app_reason" class="col-sm-2 control-label">Reason</label>
<div class="col-sm-10">
<textarea class="form-control" id="app_reason" name="app_reason" placeholder="Reason"></textarea>
</div>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button type="submit" id="add_app_btn" name="add_app_btn" class="btn btn-success pull-right">Add Appointment</button>
</div><!-- /.box-footer -->
</form>
I have a php code that take values from a form and add them into MySQL database.
First part of the PHP code, see if the admin choose an already exist patient from drop list, then add a date and time of an appointment with a reason.
Then values are posted into PHP code where we see if we have already an appointment in those date and time. If not ($appExistStmtCount == 0) then go and insert an appointment.
The problem is that nothing added to database and can't see any PHP errors echoed.
Here is the PHP code:
<?php
//Set error reporting on
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('../include/global.php');
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
if(isset($_POST['add_app_btn'])){
//Values From AJAX
$patient_name = $_POST['patient_name'];
$date_app = $_POST['app_date'];
$time_app = $_POST['app_time'];
$reason = $_POST['app_reason'];
$old_patient_id = $_POST['select_old'];
//If new patient
if($patient_name == "" && $old_patient_id != "choose")
{
try{
//See if date and time exist
$appExist = "SELECT * FROM appointment WHERE id_logged = :id_logged AND date_app = :date_app and time_app = : time_app";
$appExistStmt = $conn->prepare($appExist);
$appExistStmt->bindValue(":id_logged", $id_logged);
$appExistStmt->bindValue(":date_app", $date_app);
$appExistStmt->bindValue(":time_app", $time_app);
$appExistStmt->execute();
$appExistStmtCount = $appExistStmt->rowCount();
if($appExistStmtCount == 0)
{
//Add to appointment table
$appAdd = "INSERT INTO appointment(id_logged, patient_id, date_app, time_app, reason)
VALUES(:id_logged, :patient_id, :date_app, :time_app, :reason)";
$appAddStmt = $conn->prepare($appAdd);
$appAddStmt->bindValue(":id_logged", $id_logged);
$appAddStmt->bindValue(":patient_id", $old_patient_id);
$appAddStmt->bindValue(":date_app", $date_app);
$appAddStmt->bindValue(":time_app", $time_app);
$appAddStmt->bindValue(":reason", $reason);
$appAddStmt->execute();
echo "added";
}
else
{
echo "not added";
header("Location: add_appoint.php");
}
}
catch(PDOException $m)
{
$m->getMessage();
echo "error";
header("Location: add_app_btnoint.php");
}
}
}
?>
And here the HTML form:
<form class="form-horizontal" id="add_app_form" onSubmit="return validate(this);">
<div class="box-body">
<div class="form-group">
<label for="patient_name" class="col-sm-3 control-label">Old Patient</label>
<div class="col-sm-4">
<select id="select_old" name="select_old">
<option value="choose">Choose Name</option>
<?php foreach($name_array as $na) { ?>
<option value="<?php echo $na['id'] ?>"><?php echo $na['patient_name'] ?></option>
<?php } ?>
</select>
</div>
<label for="patient_name" class="col-sm-1 control-label">New</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="patient_name" name="patient_name" placeholder="New Patient Name">
</div>
</div>
<div class="form-group">
<label for="app_date" class="col-sm-2 control-label">Date</label>
<div class="col-sm-4">
<input type="date" class="form-control" id="app_date" name="app_date">
</div>
<label for="app_time" class="col-sm-2 control-label">Time</label>
<div class="col-sm-4">
<input type="time" class="form-control" id="app_time" name="app_time">
</div>
</div>
<div class="form-group">
<label for="app_reason" class="col-sm-2 control-label">Reason</label>
<div class="col-sm-10">
<textarea class="form-control" id="app_reason" name="app_reason" placeholder="Reason"></textarea>
</div>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button type="submi;" id="add_app_btn" class="btn btn-success pull-right">Add Appointment</button>
</div><!-- /.box-footer -->
</form>
PS
Values can be seen in the URL but the page just refresh and nothing added
Your form has no method, so it's passing data through get. You need to add method="post" to your form.
Edit. As #u_mulder mentioned, you need to add name attribute to your button for the check in your php if the button is clicked.

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();
?>

PHP articles and images issue

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)";

Categories