Unable to insert image to database - php
I have a problem inserting images in my database with a basic form. There is two forms, one inserts categories (an image and a name) and the other inserts a location(Name, Address, image, etc). The add_category function works fine it's the add_location that doesn't and specifically inserting the image. And I believe it's inserting the image that is problematic.
The problem is that this if statement in the insert image never get executed and I don't know why. It's in the function add_location(..) under the check image if statement.
if ($result = $this->mysqli->query($query)) {
$error['result'] = $this->succAddLoc;
}
I removed unnecessary functions in the file:
<?php
class pongodev {
var $mysqli;
// Error handling variables
var $errCatName;
var $errLatitude;
var $errLongitude;
var $errImage;
var $errPhone;
var $errWebsite;
var $succAddLoc;
var $succAddCat;
var $errEmail;
var $errPass;
var $succPass;
var $succEmail;
var $succEmailPass;
var $succResetPass;
var $errResetPass;
var $errUsername;
// Email configuration variables
var $emailSubject;
var $resetMessage;
var $from;
var $adminEmail;
// Connect to database
function __construct($host, $user, $pass, $database){
// Connect to database
$this->mysqli = new mysqli($host, $user, $pass, $database);
if(mysqli_connect_errno($this->mysqli)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
// Close database
function close_database(){
$this->mysqli->close();
}
// Validate username and password
function validate_user($username, $password){
......
}
// Error handling label for reset password form
function fill_error_pass($succResetPass, $errResetPass, $errUsername){
......
}
// Email message configuration
function email_configuration($emailSubject, $resetMessage, $from, $adminEmail){
.....
}
// Reset password
function reset_password($username){
.....
}
// Error handling label for add new location form
function fill_error_location_data($errLatitude, $errLongitude, $errPhone, $errWebsite,
$errImage, $succAddLoc){
$this->errLatitude = $errLatitude;
$this->errLongitude = $errLongitude;
$this->errPhone = $errPhone;
$this->errWebsite = $errWebsite;
$this->errImage = $errImage;
$this->succAddLoc = $succAddLoc;
}
// Add new location
function add_location($locationName, $address, $category,
$locImage, $lat, $lng, $tel, $url, $desc){
// Create array variables to store multiple error
$error = array();
// Check if latitude is float
$floatLat = floatVal($lat);
if(!($floatLat && intVal($floatLat) != $floatLat)){
$error['latitude'] = $this->errLatitude;
}
// Check if Longitude is float
$floatLng = floatVal($lng);
if(!($floatLng && intVal($floatLng) != $floatLng)){
$error['longitude'] = $this->errLongitude;
}
// Validate phone number
if(empty($tel) || ($tel == "-")){
$tel = "-";
}else{
$phonePattern = "/^[0-9()-]+$/";
if(!preg_match($phonePattern, $tel)){
$error['phone'] = $this->errPhone;
}
}
// Validate website
if(empty($url) || ($url == "-")){
$url = "-";
}else{
$urlPattern = "/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i";
if (!preg_match($urlPattern, $url)){
$error['website'] = $this->errWebsite;
}
}
// Check image file
$allowedExts = array("jpeg", "jpg");
$temp = explode(".", $locImage["name"]);
$extension = end($temp);
if (((($locImage["type"] == "image/jpeg")
|| ($locImage["type"] == "image/jpg"))
|| ($locImage["type"] == "image/pjpeg"))
&& ($locImage["size"] < 700000)
&& in_array($extension, $allowedExts)
&& !isset($error['latitude']) && !isset($error['longitude']) && !isset($error['phone']) && !isset($error['website'])){
// Create random image file name
$string = '0123456789';
$file = preg_replace("/\s+/", "_", $locImage['name']);
$imageUpload = date("Y-m-d")."-".$this->get_random_string($string, 4).".".$extension;
// Copy file to server directory
move_uploaded_file($locImage["tmp_name"],
"upload/images/" . $imageUpload);
$imageUpload = "upload/images/". $imageUpload;
$locationDate = date("Y-m-d");
// Add location data to tbl_location
$query = "INSERT INTO tbl_location
(location_date, location_name, category_id, address, location_image,
latitude, longitude, phone, website, description)
VALUES ('$locationDate','$locationName', '$category', '$address', '$imageUpload',
$lat, $lng, '$tel', '$url', '$desc')";
if($result = $this->mysqli->query($query)){
$error['result'] = $this->succAddLoc;
}
}else{
$error['image'] = $this->errImage;
}
return $error;
}
// Get all locations data
function get_all_locations(){
.....
}
// Get all locations data for map
function get_all_locations_map(){
.....
}
// Get location data by id
function get_location_by_id($id, $tag){
.....
}
// Get location data to be displayed on location view page
function get_location_view($id){
// Get all locations data from tbl_location
$query = "SELECT location_name, category_name, category_marker, address, location_image, latitude, longitude, phone, website, description
FROM tbl_location l, tbl_categories c
WHERE (l.category_id = c.category_id) AND (l.location_id = ?)";
$stmt = $this->mysqli->stmt_init();
if($stmt->prepare($query)) {
// Bind your variables to replace the ?s
$stmt->bind_param('s', $id);
// Execute query
$stmt->execute();
// store result
$stmt->store_result();
$stmt->bind_result($data['location_name'],
$data['category_name'],
$data['category_marker'],
$data['address'],
$data['location_image'],
$data['latitude'],
$data['longitude'],
$data['phone'],
$data['website'],
$data['description']
);
$stmt->fetch();
$stmt->close();
}
return $data;
}
// Delete location data
function delete_location($id){
......
}
// Add new location
function update_location($id, $locationName, $address, $category,
$locImage, $lat, $lng, $tel, $url, $desc, $previousImage){
// Create array variables to handle multiple errors
$error = array();
// Check if latitude is float
$floatLat = floatVal($lat);
if(!($floatLat && intVal($floatLat) != $floatLat)){
$error['latitude'] = $this->errLatitude;
}
// Check if Longitude is float
$floatLng = floatVal($lng);
if(!($floatLng && intVal($floatLng) != $floatLng)){
$error['longitude'] = $this->errLongitude;
}
// Validate phone number
if(empty($tel) || ($tel == "-")){
$tel = "-";
}else{
$phonePattern = "/^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]*([\d]{3})[\.\-\s]?([\d]{4})$/";
if(!preg_match($phonePattern, $tel)){
$error['phone'] = $this->errPhone;
}
}
// Validate url
if(empty($url) || ($url == "-")){
$url = "-";
}else{
$urlPattern = "/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i";
if (!preg_match($urlPattern, $url)){
$error['website'] = $this->errWebsite;
}
}
// Check image location
if(empty($locImage['name'])){
if(!isset($error['latitude']) && !isset($error['longitude']) && !isset($error['phone']) && !isset($error['website'])){
// Add location data to database
$query = "UPDATE tbl_location
SET location_name = '$locationName',
category_id = '$category',
address = '$address',
latitude = '$lat',
longitude = '$lng',
phone = '$tel',
website = '$url',
description = '$desc'
WHERE location_id = '$id'";
if($result = $this->mysqli->query($query)){
$error['result'] = $this->succAddLoc;
}
}
}else{
// Check image file
$allowedExts = array("jpeg", "jpg");
$temp = explode(".", $locImage["name"]);
$extension = end($temp);
if (((($locImage["type"] == "image/jpeg")
|| ($locImage["type"] == "image/jpg"))
|| ($locImage["type"] == "image/pjpeg"))
&& ($locImage["size"] < 700000)
&& in_array($extension, $allowedExts)
&& !isset($error['latitude']) && !isset($error['longitude']) && !isset($error['phone']) && !isset($error['website'])){
// Create random image file name
$string = '0123456789';
$file = preg_replace("/\s+/", "_", $locImage['name']);
$imageUpload = date("Y-m-d")."-".$this->get_random_string($string, 4).".".$extension;
// Copy file to server directory
move_uploaded_file($locImage["tmp_name"],
"upload/images/" . $imageUpload);
$imageUpload = "upload/images/". $imageUpload;
// Delete previous image
$delete = unlink("$previousImage");
// Add location data to database
$query = "UPDATE tbl_location
SET location_name = '$locationName',
category_id = '$category',
address = '$address',
location_image = '$imageUpload',
latitude = '$lat',
longitude = '$lng',
phone = '$tel',
website = '$url',
description = '$desc'
WHERE location_id = '$id'";
if($result = $this->mysqli->query($query)){
$error['result'] = $this->succAddLoc;
}
}else{
$error['image'] = $this->errImage;
}
}
return $error;
}
// Error handling label
function fill_error_category_data($errCatName, $errImage, $succAddCat){
$this->errImage = $errImage;
$this->errCatName = $errCatName;
$this->succAddCat = $succAddCat;
}
// Delete category
function delete_category($id){
......
}
// Add new category
function add_category($categoryName, $markerImage){
// Get category data from tbl_categories
$query = "SELECT * FROM tbl_categories
WHERE category_name = '$categoryName'";
if($result = $this->mysqli->query($query)){
$row = $result->num_rows;
$result->close();
}
// Create array variables to handle multiple array
$error = array();
// If category already exist in tbl_categories set the error
if($row > 0){
$error['name'] = $this->errCatName;
}
list($width, $height, $type, $attr) = getimagesize($markerImage["tmp_name"]);
$allowedExts = array("png");
$temp = explode(".", $markerImage["name"]);
$extension = end($temp);
if ((($markerImage["type"] == "image/x-png")
|| ($markerImage["type"] == "image/png"))
&& ($markerImage["size"] < 100000)
&& in_array($extension, $allowedExts)
&& (($width == 64) && ($height == 64))
&& !isset($error['name']) ){
// Create random image file name
$string = '0123456789';
$file = preg_replace("/\s+/", "_", $markerImage['name']);
$imageUpload = date("Y-m-d")."-".$this->get_random_string($string, 4).".".$extension;
// Copy image to server directory
move_uploaded_file($markerImage["tmp_name"],
"upload/markers/" . $imageUpload);
$imageUpload = "upload/markers/". $imageUpload;
// Add category to database
$query = "INSERT INTO tbl_categories
(category_name, category_marker)
VALUES ('$categoryName', '$imageUpload')";
if($result = $this->mysqli->query($query)){
debug_to_console( $query);
$error['result'] = $this->succAddCat;
}
}else{
$error['marker'] = $this->errImage;
}
return $error;
}
// Get all categories data
function get_all_categories(){
// Get categories data from database
$query = "SELECT * FROM tbl_categories
ORDER BY category_id";
$result = $this->mysqli->query($query);
return $result;
}
// Get category data
function get_category_by_id($id){
.....
}
// Update category data
function update_category($id, $previousName, $categoryName, $categoryMarker, $previousMarker){
.......
}
// Create random name for image file
function get_random_string($valid_chars, $length){
$random_string = "";
$num_valid_chars = strlen($valid_chars);
for ($i = 0; $i < $length; $i++){
$random_pick = mt_rand(1, $num_valid_chars);
$random_char = $valid_chars[$random_pick-1];
$random_string .= $random_char;
}
return $random_string;
}
// Error handling label
function fill_error_settings($errEmail, $errPass, $succPass, $succEmail, $succEmailPass){
$this->errEmail = $errEmail;
$this->errPass = $errPass;
$this->succPass = $succPass;
$this->succEmail = $succEmail;
$this->succEmailPass = $succEmailPass;
}
// Settings
function settings($user, $email, $newPass, $confirmPass){
.....
}
}
?>
Here is add_location_form.php
<?php
include('variables/variables.php');
include('libs/pongodev.php');
// Create object of pongodev class
$objMap = new pongodev($host, $userdb, $passdb, $database);
$result = 9999;
// Get all category name
$resultCategory = $objMap->get_all_categories();
// Initialize location data
$locationName = '';
$address = '';
$category = '';
$image = '';
$latitude = '';
$longitude = '';
$phone = '';
$website = '';
$description = '';
// When user click on Submit button
if(isset($_POST['btnSubmit'])){
// Get location data
$locationName = $_POST['locationName'];
$address = $_POST['address'];
$category = $_POST['category'];
$image = $_FILES['image'];
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
$phone = $_POST['phone'];
$website = $_POST['website'];
$description = $_POST['description'];
// Create array variables
$result = array();
// Fill error label
$objMap->fill_error_location_data($lblErrLatitude, $lblErrLongitude, $lblErrPhone, $lblErrWebsite, $lblErrImage, $lblAddLocSuccess);
// Add location data to database
$result = $objMap->add_location($locationName, $address, $category,
$image, $latitude, $longitude,
$phone, $website, $description);
}
?>
<div class="content-container">
<div class="row heading-container">
<div class="col-xs* col-md-9">
<h1><?php echo $lblAddNewLocation; ?></h1>
</div>
</div><!--/heading-container-->
<div class="clear"></div>
<form class="form-horizontal" role="form" method="post" enctype="multipart/form-data">
<!-- Location name form -->
<div class="form-group">
<label for="inputLocationName" class="col-sm-2 control-label"><?php echo $lblName; ?></label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputLocationName" name="locationName" placeholder="<?php echo $lblName; ?>" value="<?php echo $locationName; ?>" required focus>
</div><!--/span-->
</div><!--/form-group-->
<!--/Location name form -->
<!-- Address form -->
<div class="form-group">
<label for="inputAddress" class="col-sm-2 control-label"><?php echo $lblAddress; ?></label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputAddress3" name="address" placeholder="<?php echo $lblAddress; ?>" value="<?php echo $address; ?>" required>
</div><!--/span-->
</div><!--/form-group-->
<!--/Address form -->
<!-- Category form -->
<div class="form-group">
<label for="inputCategory" class="col-sm-2 control-label"><?php echo $lblCategory; ?></label>
<div class="col-sm-10">
<select class="form-control" id="inputCategory" name="category" required>
<?php while($data = mysqli_fetch_array($resultCategory)){
if($data['category_id'] == $category){?>
<option value="<?php echo $data['category_id']; ?>" selected><?php echo $data['category_name']; ?></option>
<?php }else{ ?>
<option value="<?php echo $data['category_id']; ?>"><?php echo $data['category_name']; ?></option>
<?php }
}?>
</select>
</div><!--/span-->
</div><!--/form-group-->
<!--/Category form -->
<!-- Latitude form -->
<?php echo isset($result['latitude']) ? '<div class="form-group has-error">' : '<div class="form-group">'; ?>
<label for="inputLatitude" class="col-sm-2 control-label"><?php echo $lblLatitude; ?></label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputLatitude" name="latitude" placeholder="<?php echo $lblLatitude; ?>" value="<?php echo $latitude; ?>" required>
<span class="help-block"><em><?php echo isset($result['latitude']) ? $result['latitude']." ".$lblLatitudeHelp : $lblLatitudeHelp; ?></em></span>
</div><!--/span-->
</div><!--/form-group-->
<!--/Latitude form -->
<!-- Longitude form -->
<?php echo isset($result['longitude']) ? '<div class="form-group has-error">' : '<div class="form-group">'; ?>
<label for="inputLongitude" class="col-sm-2 control-label"><?php echo $lblLongitude; ?></label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputLongitude" name="longitude" placeholder="<?php echo $lblLongitude; ?>" value="<?php echo $longitude; ?>" required>
<span class="help-block"><em><?php echo isset($result['longitude']) ? $result['longitude']." ".$lblLongitudeHelp : $lblLongitudeHelp; ?></em></span>
</div><!--/span-->
</div><!--/form-group-->
<!--/Longitude form -->
<!-- Image form -->
<?php echo isset($result['image']) ? '<div class="form-group has-error">' : '<div class="form-group">'; ?>
<label for="inputImage" class="col-sm-2 control-label"><?php echo $lblImage; ?></label>
<div class="col-sm-10">
<input type="file" class="form-control" id="inputImage" name="image" required>
<span class="help-block"><em><?php echo isset($result['image']) ? $result['image']." ".$lblImageHelp : $lblImageHelp; ?></em></span>
</div><!--/span-->
</div><!--/form-group-->
<!--/Image form -->
<!-- Phone form -->
<?php echo isset($result['phone']) ? '<div class="form-group has-error">' : '<div class="form-group">'; ?>
<label for="inputPhone" class="col-sm-2 control-label"><?php echo $lblPhone; ?></label>
<div class="col-sm-10">
<input type="tel" class="form-control" id="inputPhone" name="phone" placeholder="<?php echo $lblPhone; ?>" value="<?php echo $phone; ?>">
<span class="help-block"><em><?php echo isset($result['phone']) ? $result['phone']." ".$lblPhoneHelp : $lblPhoneHelp; ?></em></span>
</div><!--/span-->
</div><!--/form-group-->
<!--/Phone form -->
<!-- Website form -->
<?php echo isset($result['website']) ? '<div class="form-group has-error">' : '<div class="form-group">'; ?>
<label for="inputWebsite" class="col-sm-2 control-label"><?php echo $lblWebsite; ?></label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputWebsite" name="website" placeholder="<?php echo $lblWebsite; ?>" value="<?php echo $website; ?>">
<span class="help-block"><em><?php echo isset($result['website']) ? $result['website']." ".$lblWebsiteHelp : $lblWebsiteHelp; ?></em></span>
</div><!--/span-->
</div><!--/form-group-->
<!--/Website form -->
<!-- Description -->
<div class="form-group">
<label for="inputDescription" class="col-sm-2 control-label"><?php echo $lblDescription; ?></label>
<div class="col-sm-10">
<textarea class="form-control" rows="3" id="inputDescription" name="description" placeholder="Description" required><?php echo $description; ?></textarea>
</div><!--/span-->
</div><!--/form-group-->
<!--/Description -->
<!-- if add data success show success alert, otherwise display error alert -->
<?php if($result != 9999){
if(isset($result['result'])){ ?>
<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<p><?php echo $result['result']; ?></p>
</div>
<?php }else{ ?>
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<p><?php echo $lblErrData; ?></p>
</div>
<?php }} ?>
<!--/Adding result -->
<!-- Submit button -->
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="reset" class="btn btn-default"><?php echo $lblReset; ?></button>
<button type="submit" class="btn btn-primary" name="btnSubmit"><?php echo $lblSubmit; ?></button>
</div><!--/span-->
</div><!--/form-group-->
<!--/Submit button -->
</form>
</div><!--/contain-container-->
<?php $objMap->close_database(); ?>
Replace :
$image = $_FILES['image'];
with
$image = $_FILES['image']['name'];
if you want the image nameor : with :
$image = $_FILES['image']['tmp_name'];
if you mean the file
try this $image = $_FILES['image']['name']; instead of $image = $_FILES['image'];
$_FILES['image'] contains array of all related information of uploaded file like name, type,size,error,tmp_name, so whatever datat you want you need to call like:
$_FILES['image']['name']
$_FILES['image']['type'] etc.
Hope this helps you...:)
Inserting Images into your database is not a good idea. It is advisable to rather move your uploaded images into a given directory and save the path to the image in to your database.
just do the following..
$image=$_FILES['image']['name'];
take the values in the $image variable in the above way, m sure your problem will be solved.
Related
File (image) Upload issue in codeigniter
Actually, I have saved all the data in database after i have show in front end,in my side issue is i have created upload image function to save database after i fetch and display the front end,upload function is taking to save full path like :C:/xampp/www/htdocs/rentozy/admin/images/media/rajkumar-1515559187/1.jpg. all the images saved folder also but in front end is coming like this only : C:/xampp/www/htdocs/rentozy/admin/images/media/rajkumar-1515559187/1.jpg please i need save database like this : (images/media/rajkumar-1499778784/19510.jpg) please help me how will resolve this this is my first sit is codeigniter please help how will pass like this url. Here my code for controller: function addNewMedia() { if($this->isAdmin() == TRUE) { $this->loadThis(); } else { $this->load->library('form_validation'); $this->form_validation->set_rules('name','Name','trim|required|max_length[128]|xss_clean'); $this->form_validation->set_rules('event_image','Pg Image'); // $this->form_validation->set_rules('media_image','Image'); // $this->form_validation->set_rules('date_added','Date','trim|required'); if($this->form_validation->run() == FALSE) { $this->addNew(); } else { $data = array(); $upload_data = array(); $this->load->library('upload'); $data['name'] = $this->input->post('name'); $folder_srting = $data['name']."-".time(); $data['name'] = $this->input->post('name'); // print_r($folder_srting); $folder_string = str_replace(' ', '-', $folder_srting);// Replaces all spaces with hyphens. $folder_string = preg_replace('/[^A-Za-z0-9\-]/', '', $folder_srting);// Removes special chars. $folder_name = preg_replace('/-+/', '-', strtolower($folder_string));// Replaces multiple hyphens with single one. print_r($folder_name); //$data['name'] = $this->input->post('name'); //$pg_id = $this->input->post('pg_id'); if ($_FILES['event_image']['error'] != 4) { $folder = $this->checkdirectory($folder_name); //print_r($folder_name); $this->upload->initialize($this->set_upload_options($folder)); if ( ! $this->upload->do_upload('event_image')) { $error = array('error' => $this->upload->display_errors()); print_r($error); die; } else { $upload_data['banner_data'] = $this->upload->data(); //print_r($upload_data['banner_data']);die; $upload_data['bannerfilepath'] = $upload_data['banner_data']['full_path']; //print_r($upload_data['bannerfilepath']);die; } foreach($upload_data['banner_data'] as $bannerfilepath){ $data['banner_image_path'] = str_ireplace(FCPATH,"", $upload_data['banner_data']['full_path']); //print_r($data['banner_image_path']);die; } $event_image = $data['banner_image_path']; //print_r($event_image);die; } // $name = ucwords(strtolower($this->input->post('name'))); $event_image = $event_image; //print_r($event_image);die; $name = $this->input->post('name'); $address = $this->input->post('pg_address'); $incharge_name = $this->input->post('pg_incharge_name'); $incharge_mobile = $this->input->post('pg_incharge_mobile'); $email = $this->input->post('pg_email'); $mediaInfo = array('name'=>$name,'event_image'=>$event_image,'pg_address'=>$address,'pg_incharge_name'=>$incharge_name,'pg_incharge_mobile'=> $incharge_mobile,'pg_email'=>$email,'folder_name'=>$folder); //echo "<pre>";print_r($mediaInfo);die; $this->load->model('media_model'); //echo "<pre>";print_r($mediaInfo);die; $result = $this->media_model->addNewMedia($mediaInfo); if($result > 0) { $this->session->set_flashdata('success', 'New Pg created successfully'); } else { $this->session->set_flashdata('error', 'Pg creation failed'); } redirect('mediaListing'); } } } function editMedia() { if($this->isAdmin() == TRUE) { $this->loadThis(); } else { $this->load->library('form_validation'); $eventId = $this->input->post('pg_id'); $this->form_validation->set_rules('name','Name','trim|required|max_length[128]|xss_clean'); $this->form_validation->set_rules('event_image','Pg Image'); //$this->form_validation->set_rules('event_description','Event Description','required|max_length[200]'); // $this->form_validation->set_rules('start_date','Start Date','trim|required'); //$this->form_validation->set_rules('end_date','End Date','trim|required'); //$this->form_validation->set_rules('additional_images','Additional Images'); //$this->form_validation->set_rules('short_description','Short Description','required'); if($this->form_validation->run() == FALSE) { $this->editNew($eventId); } else { $data = array(); $upload_data = array(); $this->load->library('upload'); $existing_folder = $_POST['folder_name']; //print_r($existing_folder);die; if(isset($_POST['image_exists']) && $_POST['image_exists']!= '') $temp_attachment = $_POST['image_exists']; $folder = $this->checkdirectory($existing_folder); if (isset($_FILES['event_image']['name']) && $_FILES['event_image']['error'][0] != 4 && $_FILES['event_image']['name']!='') { $this->upload->initialize($this->set_upload_options($folder)); if ( ! $this->upload->do_upload('event_image')) { $error = array('error' => $this->upload->display_errors()); //print_r($error); die; } else { $upload_data['banner_data'] = $this->upload->data(); $upload_data['bannerfilepath'] = $upload_data['banner_data']['full_path']; } // GET REQUIRED BANNER IMAGES FILE PATH FROM FULL PATH foreach($upload_data['banner_data'] as $bannerfilepath){ $data['banner_image_path'] = str_ireplace(FCPATH,"", $upload_data['banner_data']['full_path']); print_r($data['banner_image_path']);die; } $event_image = $data['banner_image_path']; //print_r($event_image);die; } else{ // echo "sfgjdf"; $event_image = $temp_attachment; // print_r($event_image);die; } $event_image = $event_image; $name = $this->input->post('name'); $pg_address = $this->input->post('pg_address'); $pg_incharge_name = $this->input->post('pg_incharge_name'); $pg_incharge_mobile = $this->input->post('pg_incharge_mobile'); $pg_email = $this->input->post('pg_email'); // $additional_images = $additional_images; $mediaInfo = array('name'=>$name,'event_image'=>$event_image,'pg_address'=>$pg_address,'pg_incharge_name'=>$pg_incharge_name,'pg_incharge_mobile'=>$pg_incharge_mobile,'pg_email'=>$pg_email,'folder_name'=>$folder); //echo "<pre>";print_r($mediaInfo);die; $result = $this->media_model->editMedia($mediaInfo, $eventId); if($result == true) { $this->session->set_flashdata('success', 'Pg updated successfully'); } else { $this->session->set_flashdata('error', 'Pg updation failed'); } redirect('mediaListing'); } } } here my model: function addNewMedia($mediaInfo) { $this->db->trans_start(); $this->db->insert('tbl_master_property', $mediaInfo); $insert_id = $this->db->insert_id(); $this->db->trans_complete(); return $insert_id; } function getMediaInfo($eventId) { $this->db->select('pg_id, name,event_image,pg_address,pg_incharge_name,pg_incharge_mobile,pg_email,folder_name'); $this->db->from('tbl_master_property'); $this->db->where('status', 0); $this->db->where('pg_id', $eventId); $query = $this->db->get(); return $query->result(); } function editMedia($mediaInfo, $eventId) { $this->db->where('pg_id', $eventId); $this->db->update('tbl_master_property', $mediaInfo); return TRUE; } here my view file code: <?php define("IMAGE_PATH", "http://localhost/rentozy/admin/"); $eventId = ''; $name = ''; $pg_address = ''; $pg_incharge_name = ''; $pg_incharge_mobile = ''; $pg_email =''; $event_image = ''; $folder_name = ''; if(!empty($mediaInfo)) { foreach ($mediaInfo as $ef) { $eventId = $ef->pg_id; $name = $ef->name; $pg_address = $ef->pg_address; $pg_incharge_name = $ef->pg_incharge_name; $pg_incharge_mobile = $ef->pg_incharge_mobile; $pg_email = $ef->pg_email; $event_image = $ef->event_image; $folder_name = $ef->folder_name; } } ?> <script type="text/javascript" src="http://js.nicedit.com/nicEdit-latest.js"></script> <script type="text/javascript"> //<![CDATA[ bkLib.onDomLoaded(function() { nicEditors.allTextAreas() }); //]]> </script> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> <i class="fa fa-users"></i> Property Management <small>Add / Edit Property</small> </h1> </section> <section class="content"> <div class="row"> <!-- left column --> <div class="col-lg-12 col-sm-12 col-md-12 col-xs-12"> <!-- general form elements --> <div class="box box-primary"> <div class="box-header"> <h3 class="box-title">Enter Property Details</h3> </div><!-- /.box-header --> <!-- form start --> <form role="form" action="<?php echo base_url() ?>editMedia" method="post" id="editEvent" role="form" enctype="multipart/form-data" files="true"> <div class="box-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="event_name">Name</label> <input type="text" class="form-control" id="name" placeholder="Name" name="name" value="<?php echo $name; ?>" maxlength="128" readonly> <input type="hidden" value="<?php echo $eventId; ?>" name="pg_id" id="eventId" /> <input type="hidden" value="<?php echo $folder_name; ?>" name="folder_name"/> </div> </div> </div> <div class="row"> <div class="col-md-6" style="padding-bottom:15px;"> <div class="form-group"> <label for="description" class="pull-left">Pg Address</label> <textarea rows="6" cols="50" name="pg_address" class="pull-left" style="width:100%;" value="<?php echo $pg_address;?>" id="pgaddress"><?php echo $pg_address;?></textarea> </div> </div> <div class="col-md-6" style="padding-bottom:15px;"> <div class="form-group"> <label for="description" class="pull-left">Pg Incharge Name</label> <div class="clearfix"></div> <textarea rows="6" cols="50" name="pg_incharge_name" class="pull-left" style="width:100%;" value="<?php echo $pg_incharge_name;?>" id="pg_incharge_name" ><?php echo $pg_incharge_name;?></textarea> </div> </div> <div class="col-md-3"> <div class="form-group"> <label for="start-date">Pg Incharge Mobile</label> <input type="text" class="form-control required pg_incharge_mobile" value="<?php echo $pg_incharge_mobile;?>" id="pg_incharge_mobile" name="pg_incharge_mobile"> </div> </div> <div class="col-md-3"> <div class="form-group"> <label for="end-date">Pg Email</label> <input type="text" class="form-control pg_email" value="<?php echo $pg_email;?>" id="pg_email" name="pg_email"> </div> <div class="col-md-6"> <div class="col-md-6"> <div class="form-group"> <label for="event_image">Pg Image</label> <input type="file" value="<?php echo $event_image; ?>" class="form-control file_change1" id="eventimage" name="event_image"> <img src="<?php echo IMAGE_PATH.$event_image;?>" width="100px" height="50px"> <input type="hidden" name="image_exists" value="<?php echo $event_image;?>" class="form-control" id="eventimage" placeholder="Enter Image Text" aria-describedby="fileHelp"> <div><?php echo $event_image;?></div> </div> </div> </div> </div> </div> </div> </div>
I don't know if you've thought about it, but you could easily use PHP's str_replace to do what you need. <?php $path = $upload_data['banner_data']['full_path']; $dir = 'C:/xampp/www/htdocs/rentozy/admin/'; $url = str_replace( $dir, '', $path ); echo $url; In CodeIgniter, if you are saving to a path that is a directory off of document root, you can use the FCPATH constant to make this easy. So if your path to your upload folder is in a directory named /uploads/, and /uploads/ is at document root, then: <?php $path = $upload_data['banner_data']['full_path']; $dir = FCPATH . 'uploads/'; $url = str_replace( $dir, '', $path ); echo $url; This is just an example, but it is easy
Carrying a variable via session to another file
I have searched through numerous posts on this site to figure out why my session variable is not being recognized, but I haven't been able to figure out a solution. It is really simply what I am trying to do. I have two PHP files. The first one I have the following code. I HAVE started a session. PHP file 1 $profile_viewer = $_GET['user']; $_SESSION['viewer'] = $profile_viewer; PHP file 2 $_SESSION['viewer'] = $profile_viewer; I keep getting the error : Notice: Undefined variable: profile_viewer What am I doing wrong with putting $profile_viewer in the session and then calling for it? EDIT: File 1 $profile_user = $_GET['user']; $_SESSION['viewer'] = $profile_user; File 2 $user = new User(); //$profile_user = $_GET['user']; $profile_user = $_SESSION['viewer']; echo $profile_user; $friend_status = $_POST['friend_status']; $okay = true; if ( $okay ) { $add_friend_sql = " INSERT INTO friends (friend_one, friend_two, date) VALUES(?, ?, NOW()) "; $add_friend_stmt = $con->prepare($add_friend_sql); $add_friend_stmt->execute(array($user_id, $profile_user)); } Full code for file 1 <?php ini_set('display_errors', 1); error_reporting(E_ALL); require_once '../core/init_account.php'; if(Session::exists('home')) { echo '<p>' . Session::flash('home') . '</p>'; } if(!$user->isLoggedIn()) { Redirect::to('../index'); } $profile_user = $_GET['user']; $_SESSION['viewer'] = $profile_user; // If you make a file function, you can change where things are saved // You can also change the destination (for portability) function UploadFile($fileArray = array(), $destinationFolder = 'profile_images/') { $filename = $fileArray['file']['name']; $tmp_name = $fileArray['file']['tmp_name']; $filesize = $fileArray['file']['size']; $file_error = $fileArray['file']['error']; $file = $fileArray['file']; // Save all the default data. // Success and error should be set by default to fail $return['error'] = true; $return['success'] = false; $return['file']['dest'] = $destinationFolder.$filename; $return['file']['size'] = $filesize; if($file_error == 0) $return['error'] = false; // I added a directory creation function so you don't have to // manually make folders. This will do it for you. if(!is_dir($destinationFolder)) mkdir($destinationFolder,0755,true); // If your filename is not empty, return success or fail of upload if (!empty($filename)) $return['success'] = (move_uploaded_file($tmp_name, $destinationFolder.$filename)); return $return; } // Create a save-to-database function so it's easier and reusable function SaveToDb($con,$filename = false) { // Return fail immediately if the connection is false or image is invalid if(empty($filename) || !$con) return false; $user_id = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" ); $img_insert_sql = " INSERT INTO profile_img (user_id, img) VALUES (?, ?) "; if($img_insert_stmt = $con->prepare($img_insert_sql)) { $img_insert_stmt->execute(array($user_id, $filename)); return true; } return false; } // Get current profile img function getPhoto($con) { $user_id = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" ); $profile_viewer = $_GET['user']; if ($profile_viewer == $user_id) { /*$img_select_sql = " SELECT * FROM profile_img WHERE user_id = ? ORDER BY id DESC LIMIT 1 ";*/ $img_select_sql = " SELECT i.* FROM profile_img i WHERE user_id IN (?, ?) ORDER BY id DESC LIMIT 1; "; } else { //echo "This is not your image"; echo $profile_viewer; $img_select_sql = " SELECT i.* FROM profile_img i WHERE user_id IN (?, ?) ORDER BY id DESC LIMIT 1; "; } if ($select_img_stmt = $con->prepare($img_select_sql)) { $select_img_stmt->execute(array($user_id, $profile_user)); $rows = $select_img_stmt->fetchAll(PDO::FETCH_ASSOC); foreach ($rows as $row) { //$status = $row['status']; return $row; } } } // Make sure all functions above are include here. Checks for post if(isset($_POST['create'])) { // Try uploading $upload = UploadFile($_FILES); // If upload fails if(!$upload['success']) { echo '<h3>Sorry, an error occurred</h3>'; } else { // You could add error handling here based on the results of // each function's success or failure below. // Try to save it $saveToDb = SaveToDb($con,$upload['file']['dest']); // Get the profile from image name $profPic = ($saveToDb)? getPhoto($con,$upload['file']['dest']) : false; } } $profPic = getPhoto($con); ?> </head> <body> <?php include_once("../analyticstracking.php"); if($user->hasPermission('User')) { include 'nav/navUser.php'; } ?> <div id="main"> <?php $profile_viewer_message = null; if($profile_user == $user_id) { echo $profile_viewer_message = "This is your profile."; } else { echo $profile_viewer_message = "You are viewing someone elses profile."; echo '<div id="add-friend"><img src="../icons/collection/add.png" alt="Add Friend">' . "Add Friend" . '</div>'; } ?> <div id="profile-pic-container"> <img id="profile-pic" src="<?php echo (!empty($profPic) && $profPic != 0)? $profPic['img'] : "profile_images/default.jpg"; ?>" alt="<?php echo (!empty($profPic) && $profPic != 0)? "Profile Picture" : "No Picture"; ?>" /> <img src="../icons/photo-camera.png" id="change-picture" alt="Profile Picture"> <form action="" method="POST" enctype="multipart/form-data"> <input type="file" id="upload-profile-pic" name="file" class="file-input"> <div id="profile-pic-change">Change profile pic</div> </div> <!-- <img width="300px" height="200px" class="none" id="file" src="#" alt="your image"> <input type="submit" class="none" name="create" value="Upload Profile Picture"> </form> --> <div id="new-profile-pic-preview"> <div id="pic-preview-container"><img class="none pic-preview total-center" id="file" src="#" alt="your image"></div> <input type="submit" class="none" name="create" value="Upload Profile Picture"> </form> <a class="popup-close" data-popup-close="popup-1" href="#">Close</a> </div> <!-- <form action="" method="POST" enctype="multipart/form-data"> <input type="file" id="upload-profile-pic" name="file" class="file-input"> <img width="300px" height="200px" class="none" id="file" src="#" alt="your image"> <input type="submit" class="none" name="create" value="Upload Profile Picture"> </form> --> <form action="profile.php" method="POST"> <div class="field"> <label for="streetline1">First Name</label> <input type="text" class="inputbar" name="streetline1" value="<?php echo escape($user->data()->firstname); ?>"> </div> <div class="field"> <label for="streetline2">Last Name</label> <input type="text" class="inputbar" name="streetline2" value="<?php echo escape($user->data()->lastname); ?>"> </div> <div class="field"> <label for="city">Email</label> <input type="text" class="inputbar" name="city" value="<?php echo escape($user->data()->email); ?>"> </div> <div class="field"> <label for="state">Phone</label> <input type="text" class="inputbar" name="state" value="<?php echo escape($user->data()->phone); ?>"> </div> <div class="field"> <label for="zipcode">Phone Network</label> <input type="text" class="inputbar" name="zipcode" value="<?php echo escape($user->data()->network); ?>"> </div> <div class="field"> <label for="zipcode">Birthday</label> <input type="text" class="inputbar" name="zipcode" value="<?php echo escape($user->data()->birthday); ?>"> </div> <label for="submit"> <input id="signinButton" name="submit" type="submit" value="Submit"> </label> </form> </div> </body> </html> Session class class Session { public static function exists($name) { return (isset($_SESSION[$name])) ? true : false; } public static function put($name, $value) { return $_SESSION[$name] = $value; } public static function get($name) { return $_SESSION[$name]; } public static function delete($name) { if(self::exists($name)) { unset($_SESSION[$name]); } } public static function flash($name, $string = '') { if(self::exists($name)) { $session = self::get($name); self::delete($name); return $session; } else { self::put($name, $string); } } }
The only variables that get carried between scripts are $_SESSION['xxx']. Ordinary variables like $profile_user don't persist. The assignment $_SESSION['viewer'] = $profile_user; doesn't make $profile_user get copied, it copies its value into $_SESSION, and you have to pull it out of there in the other script. So script 2 should start with: session_start(); $profile_user = $_SESSION['viewer'];
PHP Form update without logout
As i am newbie to PHP kindly pardon me if i looks silly , I created a form in php , while i do the update part of the form the update reflects in db whereas in the form it still shows the same old value . i tried refresh and force refresh but nothing changes . Whereas if i logout and login again , the form shows the updated value . I tried using die(); after mysql_close($link); but it logs out the session and needs to re-login . Kindly help me on viewing the changes while i am still inside the login . My code is as follows : <?php if(isset($_POST['update'])) { $name_a = $_POST['name']; $email_a = $_POST['email']; $pass_a = $_POST['password']; $sql = "UPDATE admin SET a_name = '$name_a', a_email = '$email_a', password = '$pass_a' where aid='$update_id' "; $retval = mysql_query($sql,$link); if(! $retval ) { die('Could not update data: ' . mysql_error()); } echo "Updated data successfully\n"; mysql_close($link); }else { ?> <!-- Widget: user widget style 1 --> <div class="box box-widget widget-user-2"> <!-- Add the bg color to the header using any of the bg-* classes --> <div class="widget-user-header bg-yellow"> <div class="widget-user-image"> <?php echo '<img src="' . $img . '" class="img-circle" alt="User Image">'; ?> </div> <!-- /.widget-user-image --> <h3 class="widget-user-username"><?php echo "$name"; ?></h3> <h5 class="widget-user-desc"><?php echo "$role"; ?></h5> </div> <div class="box-footer no-padding"> <form role="form" method = "post" action = "<?php $_PHP_SELF ?>"> <div class="box-body"> <div class="form-group"> <label for="exampleInputName1">Name</label> <input type="text" class="form-control" id="exampleInputName1" name="name" value="<?php echo "$name"; ?>"> </div> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" name="email" value="<?php echo "$email"; ?>"> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="password" class="form-control" id="exampleInputPassword1" name="password" value="<?php echo "$password"; ?>"> </div> </div> <!-- /.box-body --> <div class="box-footer"> <button type="submit" name="update" id="update" class="btn btn-primary">Submit</button> </div> </form> </div> </div> <!-- /.widget-user --> <?php } ?>
SOLUTION 1) use the updated value like $name_a instead of $name because $name_a contain updated value and $name contain old value 2) reload page after update and get new value from database on page load and store that value in $name , $email etc variable (if new data update successfully in database then only you get new value ) 3) if You store your data in session or cookie then update session and cookie value also when you update in database
Try this: <?php $name = ''; $email = ''; $password = ''; $update_id = ''; //$img = ''; //$role = ''; //$link = null; if( isset($_POST['update']) && isset($_POST['id']) && isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password']) ) { $update_id = mysql_real_escape_string($_POST['id']); $name = mysql_real_escape_string($_POST['name']); $email = mysql_real_escape_string($_POST['email']); $password = mysql_real_escape_string($_POST['password']); $sql = 'UPDATE admin SET a_name = \'' . $name . '\', a_email = \'' . $email . '\', password = \'' . $password . '\' WHERE aid = \'' . $update_id . '\''; $result = #mysql_query($sql, $link); if(!$result) die('Could not update data: ' . mysql_error($link)); echo 'Updated data successfully', "\n"; } elseif(isset($_GET['id'][0])) { $update_id = mysql_real_escape_string($_GET['id']); $sql = 'SELECT a_name,a_email,a_password FROM admin WHERE aid = \'' . $update_id . '\''; $result = #mysql_query($sql, $link); if($result) { $result = mysql_fetch_row($result); $name = $result[0]; $email = $result[1]; $password = $result[2]; } else { echo 'Could not find the id.' . "\n"; $update_id = ''; } } unset($result); if(isset($update_id[0])) { mysql_close($link); ?> <!-- Widget: user widget style 1 --> <div class="box box-widget widget-user-2"> <!-- Add the bg color to the header using any of the bg-* classes --> <div class="widget-user-header bg-yellow"> <div class="widget-user-image"> <img src="<?php echo htmlspecialchars($img); ?>" class="img-circle" alt="User Image"> </div> <!-- /.widget-user-image --> <h3 class="widget-user-username"><?php echo htmlspecialchars($name); ?></h3> <h5 class="widget-user-desc"><?php echo htmlspecialchars($role); ?></h5> </div> <div class="box-footer no-padding"> <form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST"> <input type="hidden" name="id" value="<?php echo htmlspecialchars($update_id); ?>"> <div class="box-body"> <div class="form-group"> <label for="exampleInputName1">Name</label> <input type="text" class="form-control" id="exampleInputName1" name="name" value="<?php echo htmlspecialchars($name); ?>"> </div> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" name="email" value="<?php echo htmlspecialchars($email); ?>"> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="password" class="form-control" id="exampleInputPassword1" name="password" value="<?php echo htmlspecialchars($password); ?>"> </div> </div> <!-- /.box-body --> <div class="box-footer"> <button type="submit" name="update" id="update" class="btn btn-primary">Submit</button> </div> </form> </div> </div> <!-- /.widget-user --> <?php } else { $sql = 'SELECT aid,a_name FROM admin'; $result = #mysql_query($sql, $link); if($result) { while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo '' . $row['a_name'] . '<br />' . "\n"; } } mysql_close($link); } ?>
As #DivyeshSavaliya mentioned in the comment the issue is , I didn't Used Select query after update . Once done that the issue solved The new working code is <?php if(isset($_POST['update'])) { $name_a = $_POST['name']; $email_a = $_POST['email']; $pass_a = $_POST['password']; $sql = "UPDATE admin SET a_name = '$name_a', a_email = '$email_a', password = '$pass_a' where aid='$update_id' "; $retval = mysql_query($sql,$link); if(! $retval ) { die('Could not update data: ' . mysql_error()); } } $result = mysql_query("SELECT * FROM admin where aid='$update_id' ",$link); while($row = mysql_fetch_array($result)){ $name = $row['a_name']; $email = $row['a_email']; $password = $row['password']; } mysql_close($link); ?> Thanks to #DivyeshSavaliya
Uploading image Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation:
I maked image upload for my form, but this going with adding time to error Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'image' cannot be null' in /www/data08/users/i/itsiim.planet.ee/htdocs/progemine/system/lisa.php:58 Stack trace: #0 /www/data08/users/i/itsiim.planet.ee/htdocs/progemine/system/lisa.php(58): PDOStatement->execute(Array) #1 {main} thrown in /www/data08/users/i/itsiim.planet.ee/htdocs/progemine/system/lisa.php on line 58 <?php require 'conf/db.php'; if ( !empty($_POST)) { // keep track validation errors $nimiError = null; $emailError = null; $mobiilError = null; $suguError = null; // keep track post values $nimi = $_POST['nimi']; $email = $_POST['email']; $mobiil = $_POST['mobiil']; $sugu = $_POST['sugu']; // validate input $valid = true; if (empty($nimi)) { $nimiError = 'Palun sisesta nimi'; $valid = false; } if (empty($email)) { $emailError = 'Palun sisesta e-mail'; $valid = false; } else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) { $emailError = 'Palun sisesta korrektne e-mail'; $valid = false; } if (empty($mobiil)) { $mobiilError = 'Palun sisesta mobiili number'; $valid = false; } if (empty($sugu)) { $suguError = 'Palun vali sugu'; $valid = false; } //Pilt if(is_uploaded_file($_FILES['image']['tmp_name'])){ $folder = "upload/"; $file = basename( $_FILES['image']['name']); $full_path = $folder.$file; if(move_uploaded_file($_FILES['image']['tmp_name'], $full_path)) { $image = $full_path; } } // insert data if ($valid) { $pdo = Database::connect(); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO kliendid (nimi,email,mobiil,sugu,image) values(?, ?, ?, ?, ?)"; $q = $pdo->prepare($sql); $q->execute(array($nimi,$email,$mobiil,$sugu,$image)); Database::disconnect(); header("Location: index.php"); } } ?> <!DOCTYPE html> <html lang="et"> <head> <meta charset="utf-8"> <title>Klientide andmed by Siim Aarmaa IS-13</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="col-md-6 col-md-offset-3"> <div class="row"> <h3>Lisa uus klient</h3> </div> <form class="form-horizontal" action="lisa.php" method="post"> <div class="form-group <?php echo !empty($nimiError)?'error':'';?>"> <label class="col-sm-2 control-label">Nimi</label> <div class="controls"> <input name="nimi" type="text" placeholder="Nimi" value="<?php echo !empty($nimi)?$nimi:'';?>"> <?php if (!empty($nimiError)): ?> <span class="help-block"><?php echo $nimiError;?></span> <?php endif; ?> </div> </div> <div class="form-group <?php echo !empty($emailError)?'error':'';?>"> <label class="col-sm-2 control-label">E-mail</label> <div class="controls"> <input name="email" type="text" placeholder="E-mail" value="<?php echo !empty($email)?$email:'';?>"> <?php if (!empty($emailError)): ?> <span class="help-block"><?php echo $emailError;?></span> <?php endif;?> </div> </div> <div class="form-group <?php echo !empty($mobiilError)?'error':'';?>"> <label class="col-sm-2 control-label">Mobiili number</label> <div class="controls"> <input name="mobiil" type="text" placeholder="Mobiili number" value="<?php echo !empty($mobiil)?$mobiil:'';?>"> <?php if (!empty($mobiilError)): ?> <span class="help-block"><?php echo $mobiilError;?></span> <?php endif;?> </div> </div> <div class="form-group <?php echo !empty($suguError)?'error':'';?>"> <label class="col-sm-2 control-label">Sugu</label> <div class="controls"> <input name="sugu" type="radio" value="<?php echo !empty($mees)?$mees:'Mees';?>">Mees <input name="sugu" type="radio" value="<?php echo !empty($naine)?$naine:'Naine';?>">Naine <?php if (!empty($suguError)): ?> <span class="help-block"><?php echo $suguError;?></span> <?php endif;?> </div><br> <div class="form-group <?php echo !empty($mobiilError)?'error':'';?>"> <label class="col-sm-2 control-label">Pilt</label> <div class="controls"> <input type="file" name="image" required="required" value=""/> <?php if (!empty($mobiilError)): ?> <span class="help-block"><?php echo $mobiilError;?></span> <?php endif;?> </div> </div> <br> <div class="form-group"> <button type="submit" class="btn btn-success">Lisa klient</button> <a class="btn btn-default" href="index.php">Tagasi</a> </div> </form> </div> </div> <!-- /container --> </body> </html>
Looks like something went wrong with the fileupload. You have no else branches for the is_uploaded_file() and move_uploaded_file() checks. <?php require 'conf/db.php'; $errors = array(); if ( !isset($_POST['nimi'],$_POST['email'],$_POST['mobiil'],$_POST['sugu']) ) { $errors['parameter'] = 'missing POST parameter'; } else { // keep track post values $nimi = $_POST['nimi']; $email = $_POST['email']; $mobiil = $_POST['mobiil']; $sugu = $_POST['sugu']; // validate input if (empty($nimi)) { $errors['nimi'] = 'Palun sisesta nimi'; } if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) { $errors['email'] = 'Palun sisesta korrektne e-mail'; } if (empty($mobiil)) { $errors['mobiil'] = 'Palun sisesta mobiili number'; } if (empty($sugu)) { $errors['suguError'] = 'Palun vali sugu'; } if ( empty($errors) ) { //Pilt if( !is_uploaded_file($_FILES['image']['tmp_name']) ) { $errors['upload'] = 'no file uploaded'; } else { $folder = "upload/"; $file = basename( $_FILES['image']['name']); $full_path = $folder.$file; if( !move_uploaded_file($_FILES['image']['tmp_name'], $full_path) ) { $errors['upload'] = 'cannot move file'; } else { $image = $full_path; } } } } // insert data if ( empty($errors) ) { $pdo = Database::connect(); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO kliendid (nimi,email,mobiil,sugu,image) values(?, ?, ?, ?, ?)"; $q = $pdo->prepare($sql); $q->execute( array($nimi,$email,$mobiil,$sugu,$image) ); Database::disconnect(); header("Location: index.php"); die; } else { echo '<pre>', join("\r\n", $errors), '</pre>'; }
The problem is because of the Undefined index: image, which means your file didn't get uploaded. And that's because you didn't set the enctype="multipart/form-data" in your <form> element. It should be, <form class="form-horizontal" action="lisa.php" method="post" enctype="multipart/form-data"> // your HTML code </form>
PHP Adding Data to Database
I've been testing a CRUD interface with PHP and SQLSRV driver but i got stuck on the creating part, i can read the data that alredy was added on the database by id, but i cant get to work the create data from PHP to the database, when i press the create Button it clears the inputs and shows the errors. Would like to know if there is something wrong with my code so far. PHP CODE: <?php require 'database.php'; if ( !empty($_POST)) { $iError = null; $nError = null; $dError = null; $tError = null; $id = $_POST['id']; $name = $_POST['name']; $Address = $_POST['Address']; $phone = $_POST['phone']; $valid = true; if (empty($id)) { $iError = 'add id'; $valid = false; } if (empty($name)) { $nError = 'add name'; $valid = false; } if (empty($Address)) { $dError = 'add address'; $valid = false; } if (empty($phone)) { $tError = 'add phone'; $valid = false; } if ($valid) { $tsql = "INSERT INTO dbo.TEST1 (id, name, Address, phone) values(?, ?, ?, ?)"; $arr1 = array($id, $name, $Address, $phone); $stmt = sqlsrv_query($conn, $tsql, $arr1 ); if ( $stmt === FALSE ){ echo "New data created"; } else { echo "Error creating data"; die(print_r(sqlsrv_errors(),true)); } } }?>` this is the HTML part: <body> <div> <div> <h3>CREAR</h3> </div> <form class="form-horizontal" action="create.php" method="post"> <div class=" <?php echo !empty($iError)?'error':'';?>"> <label >ID</label> <div > <input name="name" type="text" placeholder="ID" value="<?php echo !empty($id)?$id:'';?>"> <?php if (!empty($iError)): ?> <span ><?php echo $iError;?></span> <?php endif; ?> </div> </div> <div class=" <?php echo !empty($nError)?'error':'';?>"> <label>name</label> <div> <input name="name" type="text" placeholder="name" value="<?php echo !empty($name)?$name:'';?>"> <?php if (!empty($nError)): ?> <span><?php echo $nError;?></span> <?php endif; ?> </div> </div> <div class=" <?php echo !empty($emailError)?'error':'';?>"> <label >Address</label> <div > <input name="email" type="text" placeholder="Address" value="<?php echo !empty($Address)?$Address:'';?>"> <?php if (!empty($dError)): ?> <span><?php echo $dError;?></span> <?php endif;?> </div> </div> <div class=" <?php echo !empty($tError)?'error':'';?>"> <label >phoner</label> <div > <input name="mobile" type="text" placeholder="phone" value="<?php echo !empty($phone)?$phone:'';?>"> <?php if (!empty($tError)): ?> <span ><?php echo $tError;?></span> <?php endif;?> </div> </div> <div > <button type="submit">Create</button> Return </div> </form> </div> </div>