Carrying a variable via session to another file - php

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'];

Related

Images not displaying - Bad file descriptor

This page works for showing everything but the images, which are stored in the public/uploads folder with filenames as "1.jpg", "2.jpg" etc. I seem to be unable to construct a query string that effectively retrieves the image. Need be, I can include the SQLite.
<?php
$page_name = 'gallery';
$nav_plantgallery_class = 'active_page';
// plant gallery requires login to access content
// if (is_user_logged_in()) {
// --- Upload Document ---
// Set maximum file size for uploaded files.
// MAX_FILE_SIZE must be set to bytes
// 1 MB = 1000000 bytes
define("MAX_FILE_SIZE", 1000000);
// feedback CSS classes
$file_feedback_class = 'hidden';
// $name_feedback_class = 'hidden';
$desc_feedback_class = 'hidden';
$name_feedback_class = 'hidden';
$genus_feedback_class= 'hidden';
// $desc_feedback_class = 'hidden';
$type_feedback_class = 'hidden';
$id_feedback_class='hidden';
// upload fields
$upload_name = NULL;
// $plant_name=
$upload_desc = NULL;
// $upload_source = NULL;
$upload_filename = NULL;
$upload_ext = NULL;
$upload_genus=
$upload_type=
$upload_plantid=NULL;
// sticky values
// Note: file uploads are not sticky!
// $sticky_name = '';
// $sticky_desc = '';
// $sticky_source = '';
$sticky_name = $sticky_genus=
$sticky_desc ='';
$sticky_plantid=
$sticky_planttype_groundcover = '';
$sticky_planttype_fern = '';
$sticky_planttype_flower = '';
$sticky_planttype_shrub = '';
$sticky_planttype_vine = '';
$sticky_planttype_tree = '';
$sticky_planttype_grass = '';
// Users must be logged in to upload files!
if (isset($_POST["upload"])) {
$upload_name = trim($_POST['name']); // untrusted
$upload_desc = trim($_POST['desc']); // untrusted
// $upload_source = trim($_POST['source']); // untrusted
$upload_genus= trim($_POST['genus']);
$upload_type= trim($_POST['type']);
$upload_plantid= trim($_POST['plant_id']);
// get the info about the uploaded files.
$upload = $_FILES['jpg-file'];
// Assume the form is valid...
$form_valid = True;
// file is required
if ($upload['error'] == UPLOAD_ERR_OK) {
// The upload was successful!
// Get the name of the uploaded file without any path
$upload_filename = basename($upload['name']);
// Get the file extension of the uploaded file and convert to lowercase for consistency in DB
$upload_ext = strtolower(pathinfo($upload_filename, PATHINFO_EXTENSION));
// This site only accepts JPG files!
if (!in_array($upload_ext, array('jpg'))) {
$form_valid = False;
}
} else {
// upload was not successful
$form_valid = False;
}
// name is required
if (empty($upload_name)) {
$form_valid = False;
$name_feedback_class = '';
}
// description is required
if (empty($upload_desc)) {
$form_valid = False;
$desc_feedback_class = '';
}
if (empty($upload_genus)) {
$form_valid = False;
$genus_feedback_class = '';
}
if (empty($upload_type)) {
$form_valid = False;
$type_feedback_class = '';
}
if (empty($upload_plantid)) {
$form_valid = False;
$id_feedback_class = '';
}
// // Record NULL (not empty string)
// if (empty($upload_source)) {
// $upload_source = NULL;
// }
if ($form_valid) {
// insert upload into DB
$result = exec_sql_query(
$db,
"INSERT INTO plants (plant_id, name, description, genus, type, file_name, file_ext) VALUES (:plant_id, :name, :description, :genus, :type, :file_name, :file_ext)",
array(
// ':user_id' => $current_user['id'],
':plant_id' => $upload_plantid,
':name' => $upload_name,
':description' => $upload_desc,
':genus' => $upload_genus,
':type' => $upload_type,
':file_name' => $upload_filename,
':file_ext' => $upload_ext,
// ':source' => $upload_source
)
);
if ($result) {
// We successfully inserted the record into the database, now we need to
// move the uploaded file to it's final resting place: public/uploads directory
// get the newly inserted record's id
$record_id = $db->lastInsertId('id');
// uploaded file should be in folder with same name as table with the primary key as the filename.
// Note: THIS IS NOT A URL; this is a FILE PATH on the server!
// Do NOT include / at the beginning of the path; path should be a relative path.
// NO: /public/...
// YES: public/...
$id_filename = 'public/uploads/documents/' . $record_id . '.' . $upload_ext;
// Move the file to the public/uploads/documents folder
// Note: THIS FUNCTION REQUIRES A PATH. NOT A URL!
move_uploaded_file($upload["tmp_name"], $id_filename);
}
} else {
// file uploads are not sticky!
// user must reselect file, show file feedback when showing feedback!
$file_feedback_class = '';
$sticky_name = $upload_name;
$sticky_desc = $upload_desc;
$sticky_genus= $upload_genus;
$sticky_type= $upload_type;
$sticky_plantid=$upload_plantid;
// $sticky_source = $upload_source;
}
}
// --- Document Records ---
// query the database for the grade records
$records = exec_sql_query(
$db,
"SELECT * FROM plants ORDER BY file_name ASC;",
)->fetchAll();
// }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<name><?php echo $page_name; ?> - plants</name>
<link rel="stylesheet" type="text/css" href="/public/styles/site.css" media="all" />
</head>
<body>
<?php include('includes/header.php'); ?>
<main class="plantgallery">
<section class="gallery">
<h2><?php echo $page_name; ?></h2>
<?php
// if (is_user_logged_in()) {
// Only show the documents gallery if we have records to display.
if (count($records) > 0) { ?>
<ul>
<?php
foreach ($records as $record) { ?>
<li>
<a href="/document?<?php echo http_build_query(array('id' => $record['id'])); ?>">
<img class="flower" src="/public/uploads/<?php echo $record['id'] . '.' . $record['file_ext']; ?>" alt="<?php echo htmlspecialchars($record['id']); ?>" />
<p><?php echo ucfirst($record['plant_name']); ?></p>
</a>
</li>
<?php
} ?>
</ul>
<?php
} else { ?>
<p>Gallery is <em>empty</em>.</p>
<?php } ?>
<?php if ($is_admin() && is_user_logged_in()) {?>
<section class="upload">
<h2>Upload Plant</h2>
<form action="/" method="post" enctype="multipart/form-data" novalidate>
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_FILE_SIZE; ?>" />
<p class="feedback <?php echo $file_feedback_class; ?>">Please select an JPG file.</p>
<div class="label-input">
<label for="upload-file">JPG File:</label>
<input id="upload-file" type="file" name="jpg-file" accept=".jpg,image/jpg" />
</div>
<p class="feedback <?php echo $name_feedback_class; ?>">Please provide a name.</p>
<div class="label-input">
<label for="upload-name">Plant name:</label>
<input id='upload-name' type="text" name="name" placeholder="plant name" value="<?php echo htmlspecialchars($sticky_name); ?>" />
</div>
<p class="feedback <?php echo $desc_feedback_class; ?>">Please provide a description.</p>
<div class="label-input">
<label for="upload-desc">Description:</label>
<textarea id="upload-desc" name="desc" rows="5" placeholder="plant description."><?php echo htmlspecialchars($sticky_desc); ?></textarea>
</div>
<p class="feedback <?php echo $genus_feedback_class; ?>">Please provide a genus.</p>
<div class="label-input">
<label for="upload-genus">Genus:</label>
<input id='upload-genus' type="text" name="genus" placeholder="plant genus" value="<?php echo htmlspecialchars($sticky_genus); ?>" />
</div>
<p class="feedback <?php echo $id_feedback_class; ?>">Please provide a plant ID.</p>
<div class="label-input">
<label for="upload-id">name:</label>
<input id='upload-id' type="text" name="id" placeholder="plant id" value="<?php echo htmlspecialchars($sticky_plantid); ?>" />
</div>
<!-- <div class="label-input">
<label for="upload-source" class="optional">Source URL:</label>
<input id='upload-source' type="url" name="source" placeholder="URL where found. (optional)" value="<?//php echo htmlspecialchars($sticky_source); ?>" />
</div> -->
<div class="align-right">
<button type="submit" name="upload">Upload Plant</button>
</div>
</form>
</section>
<?php
// } else {
?>
<!-- <p>Please login to access your plant gallery.</p> -->
<?php
//echo_login_form('/', $session_messages);
?>
<?php
}
?>
</main>
<?//php include("includes/footer.php"); ?>
</body>
</html>
You save your files into public/uploads/documents/ but take from different folder public/uploads/. Try to fix the src path like this
<?php
foreach ($records as $record) { ?>
<li>
<a href="/document?<?php echo http_build_query(array('id' => $record['id'])); ?>">
<img class="flower" src="/public/uploads/documents/<?php echo $record['id'] . '.' . $record['file_ext']; ?>" alt="<?php echo htmlspecialchars($record['id']); ?>" />
<p><?php echo ucfirst($record['plant_name']); ?></p>
</a>
</li>
<?php
} ?>

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

php mvc update images

I have some questions about editing multiple images on my custom PHP MVC code.
Here is controller:
public function izmijeniProizvod() {
$item['item_id'] = $_POST['item_id'];
$item['title'] = $_POST['title'];
$item['description'] = $_POST['description'];
$item['price'] = $_POST['price'];
$item['fk_category_id'] = $_POST['fk_category_id'];
$item['fk_sub_category_id'] = $_POST['fk_sub_category_id'];
$item['active'] = $_POST['active'];
$item['sifra_proizvoda'] = $_POST['sifra_proizvoda'];
$item['image'] = !empty($_FILES['image']['name'][0]) ? $_FILES['image']['name'][0] : '';
$imageFile = $_FILES['image']['name'];
$imageFolder = BASE_PATH.'cdn/proizvodi/' . $item['item_id'] . '/';
$result = $this-> model-> updateItem($item);
for($i = 0; $i < count($imageFile); $i++) :
$item['image'] = !empty($_FILES['image']['name'][$i]) ? $_FILES['image']['name'][$i] : '';
if (!empty($_FILES['image']['tmp_name'][$i]) && $_FILES['image']['error'][$i] == 0 && $_FILES['image']['size'][$i] > 0) :
require_once APP . 'PHPThumb/ThumbLib.inc.php';
if (!is_dir($imageFolder)) :
mkdir($imageFolder);
endif;
if (is_dir($imageFolder)) {
array_map('unlink', glob($imageFolder . '*'));
}
foreach ($this->thumbs as $thumb) :
$newImageFile = $thumb['width'] . 'x' . $thumb['height'] . '_' . $imageFile[$i];
$phpThumb = PhpThumbFactory::create($_FILES['image']['tmp_name'][$i]);
$phpThumb->resize($thumb['width'], $thumb['height'])->save($imageFolder . $newImageFile); //cuva sliku
endforeach;
$this-> model-> updateSlike($item, $imageFile[i]);
endif;
endfor;
And model for this part of code is:
public function updateItem($item) {
$imageSql = !empty($item['image']) ? " , `image` = '{$item['image']}' " : '';
$sql = "UPDATE `items` SET `title` = '{$item['title']}', `active` = '{$item['active']}' , `sifra_proizvoda` = '{$item['sifra_proizvoda']}' , `description` = '{$item['description']}', `price` = '{$item['price']}',
`fk_category_id` = '{$item['fk_category_id']}', `fk_sub_category_id` = '{$item['fk_sub_category_id']}'
$imageSql
WHERE `item_id` = '{$item['item_id']}'";
$result = $this->db->exec($sql);
return $result;
}
public function updateSlike($item){
//$slika = count($item['image']);
$sql = "UPDATE `slike_proizvoda` SET `slika1` = '{$item['image']}' WHERE `item_id` = '{$item['item_id']}'";
$result = $this->db->exec($sql);
return $result;
}
View part of code:
<div class="form-group">
<label class="col-lg-3 control-label">Slika:</label>
<div class="col-lg-8">
<?php if (!empty($this->item['images']['300x300'])) { ?>
<img id="slika" alt="<?php echo $this->item['image']; ?>" src="<?php echo $this->item['images']['300x300'] ?>" />
<?php } ?>
<div class="help-block">
<p>
<label for="image">Izmijeni glavnu sliku:</label>
<input type="file" name="image[]" id="image">
<input type="hidden" name="image[]" />
</p>
<p>
<label for="image2">Ubaci još jednu sliku:</label>
<input type="file" name="image[]" id="image">
<input type="hidden" name="image[]" />
</p>
<p>
<label for="image3">Ubaci još jednu sliku:</label>
<input type="file" name="image[]" id="image">
<input type="hidden" name="image[]" />
</p>
</div>
</div>
Things I get with this parts of code is:
only one imaget get upload, on updateSlike() get only one image name in mysql ...
Thanks.

My GET statements work correctly but my POST statements don't

I've been fiddling with this for hours and cant figure out why the $_GET statements perform correctly, but the $_POST statements don't.
IF $stock is in dB, show values in the form, and if the form is submitted submit UPDATE those values, IF $stock is NOT in dB and the form is submitted INSERT into table. Neither $_POST statement seems to work, yet are not throwing any errors, just redirecting back to the same page when you hit the submit button.
include_once ('../helper_content/sql_Connect.php');
$error = array();
$KBB_Low = "";
$KBB_High = "";
$KBB_Fair = "";
$KBB_Retail = "";
$KBB_URL = "";
$TrueCar_Great = "";
$TrueCar_Average = "";
$TrueCar_Above = "";
$TrueCar_URL = "";
$NADA_Trade = "";
$NADA_Loan = "";
$NADA_Retail = "";
# Was the form submitted via POST?
if(isset($_POST['Submit'])) {
# Yes
# Is this a new stock item?
if(empty($_POST['stock'])) {
# Yes - insert
$kbb_low = filter_var($_POST['kbb_low'], FILTER_SANITIZE_STRING);
$kbb_high = filter_var($_POST['kbb_high'], FILTER_SANITIZE_STRING);
$kbb_fair = filter_var($_POST['kbb_fair'], FILTER_SANITIZE_STRING);
$kbb_retail = filter_var($_POST['kbb_retail'], FILTER_SANITIZE_STRING);
$kbb_url = filter_var($_POST['kbb_url'], FILTER_SANITIZE_STRING);
$truecar_great = filter_var($_POST['truecar_great'], FILTER_SANITIZE_STRING);
$truecar_average = filter_var($_POST['truecar_average'], FILTER_SANITIZE_STRING);
$truecar_above = filter_var($_POST['truecar_above'], FILTER_SANITIZE_STRING);
$truecar_url = filter_var($_POST['truecar_url'], FILTER_SANITIZE_STRING);
$nada_trade = filter_var($_POST['nada_trade'], FILTER_SANITIZE_STRING);
$nada_loan = filter_var($_POST['nada_loan'], FILTER_SANITIZE_STRING);
$nada_retail = filter_var($_POST['nada_retail'], FILTER_SANITIZE_STRING);
if ($stmt = $conn->prepare("INSERT INTO `Inventory_Valuations` (`stock`,
`kbb_low`, `kbb_high`, `kbb_fair`, `kbb_retail`, `kbb_url`,
`truecar_great`, `truecar_average`, `truecar_above`, `truecar_url`,
`nada_trade`, `nada_loan`, `nada_retail`
) VALUES (?,?,?,?,?,?)")) {
$stmt->bind_param('iiiisiiisiii', $stock,
$kbb_low, $kbb_high, $kbb_fair, $kbb_retail, $kbb_url,
$truecar_great, $truecar_average, $truecar_above, $truecar_url,
$nada_trade, $nada_loan, $nada_retail
);
if ($stmt->execute()) {
$stmt->close();
header('Location: ./?inserted=true');
exit();
} else {
$error[] = "Error adding: " . $stmt->error;
$stmt->close();
}
}
} else {
# No - update
$stock = $_POST['stock'];
$kbb_low = $_POST['kbb_low'];
$kbb_high = $_POST['kbb_high'];
$kbb_fair = $_POST['kbb_fair'];
$kbb_retail = $_POST['kbb_retail'];
$kbb_url = $_POST['kbb_url'];
$truecar_great = $_POST['truecar_great'];
$truecar_average = $_POST['truecar_average'];
$truecar_above = $_POST['truecar_above'];
$truecar_url = $_POST['truecar_url'];
$nada_trade = $_POST['nada_trade'];
$nada_loan = $_POST['nada_loan'];
$nada_retail = $_POST['nada_retail'];
/*... get variables from the $_POST array */
if ($stmt = $conn->prepare("UPDATE `Inventory_Valuations` SET
kbb_low=?, kbb_high=?, kbb_fair=?, kbb_retail=?, kbb_url=?,
truecar_great=?, truecar_average=?, truecar_above=?, truecar_url=?,
nada_trade=?, nada_loan=?, nada_retail=?
WHERE stock=?")) {
$stmt->bind_param('iiiisiiisiii',
$kbb_low, $kbb_high, $kbb_fair, $kbb_retail, $kbb_url,
$truecar_great, $truecar_average, $truecar_above, $truecar_url,
$nada_trade, $nada_loan, $nada_retail,
$stock);
if ($stmt->execute()) {
$stmt->close();
header('Location: ./?updated=true');
exit();
}
else {
$error[] = "Error updating: " . $stmt->error;
$stmt->close();
}
}
}
}
else {
# No - assume a GET
$status = 'Active';
$stock = $_GET['stock'];
$cat = $_GET['cat'];
if(isset($_GET['updated'])) {
$message = "Record updated";
}
else if(isset($_GET['inserted'])) {
$message = "Record added into database";
}
if($stock != "") {
# Load the item?
$query = "SELECT * FROM `Inventory_Valuations` WHERE stock=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('i', $stock);
if($stmt->execute()) {
$result = $stmt->get_result();
if($result) {
$row = $result->fetch_assoc();
$KBB_Low = $row['kbb_low'];
$KBB_High = $row['kbb_high'];
$KBB_Fair = $row['kbb_fair'];
$KBB_Retail = $row['kbb_retail'];
$KBB_URL = $row['kbb_url'];
$TrueCar_Great = $row['truecar_great'];
$TrueCar_Average = $row['truecar_average'];
$TrueCar_Above = $row['truecar_above'];
$TrueCar_URL = $row['truecar_url'];
$NADA_Trade = $row['nada_trade'];
$NADA_Loan = $row['nada_loan'];
$NADA_Retail = $row['nada_retail'];
}
}
$stmt->close();
}
}
?>
<?php if(isset($message)) : ?>
<div class="alert alert-success">
<?= $message ?>
</div>
<?php endif; ?>
<?php if(isset($error)) : ?>
<div class="alert alert-danger">
<ul>
<?php foreach($error as $err): ?>
<li><?= $err ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>?cat=Sales&stock=<?= $stock; ?>">
<section class="valuations">
<h3>Valuations</h3>
<input type="hidden" name="stock" value="<?= $stock; ?>">
<div>
<a target="_blank" href="<?=$KBB_Link; ?>"><img src="images/logos/KBB.png"></a>
<p>
<label for="kbb_low">Fair Market Range</label>
<input type="number" class="dollars" id="kbb_low" name="kbb_low" placeholder="Low" value="<?= $KBB_Low; ?>"> -
<input type="number" class="dollars" id="kbb_high" name="kbb_high" placeholder="High" value="<?= $KBB_High; ?>">
</p>
<p>
<label for="kbb_fair">Fair Price</label>
<input type="number" class="dollars" id="kbb_fair" name="kbb_fair" placeholder="Fair" value="<?= $KBB_Fair; ?>">
</p>
<p>
<label for="kbb_retail">Sug. Retail</label>
<input type="number" class="dollars" id="kbb_retail" name="kbb_retail" placeholder="Retail" value="<?= $KBB_Retail; ?>">
</p>
<p class="clear">
<label for="kbb_url">Report URL</label>
<input type="url" id="kbb_url" name="kbb_url" size="20" spellcheck="false" placeholder="www.kbb.com/" value="<?= $KBB_URL; ?>">
<i title="Copy KBB URL" data-clipboard-target="#kbb_url" data-clipboard-action="copy" class="fa fa-clipboard" aria-hidden="true"></i>
</p>
</div>
<div>
<img src="images/logos/TrueCar.png">
<p><label for="truecar_great">Great Price</label> <input type="number" class="dollars" id="truecar_great" name="truecar_great" placeholder="Great" value="<?= $TrueCar_Great; ?>"></p>
<p><label for="truecar_average">Average Price</label> <input type="number" class="dollars" id="truecar_average" name="truecar_average" placeholder="Average" value="<?= $TrueCar_Average; ?>"></p>
<p><label for="truecar_above">High Price</label> <input type="number" class="dollars" id="truecar_above" name="truecar_above" placeholder="Above" value="<?= $TrueCar_Above; ?>"></p>
<p class="clear">
<label for="truecar_url">Report URL</label> <input type="url" id="truecar_url" name="truecar_url" size="20" spellcheck="false" placeholder="www.truecar.com/" value="<?= $TrueCar_URL; ?>">
<i title="Copy TrueCar URL" data-clipboard-target="#truecar_url" data-clipboard-action="copy" class="fa fa-clipboard" aria-hidden="true"></i>
</p>
</div>
<div>
<a target="_blank" href="http://www.nadaguides.com/Cars/<?= $year; ?>/<?= $make; ?>/<?= $model; ?>"><img src="images/logos/NADA.png"></a>
<p><label for="nada_trade">Trade</label> <input type="number" class="dollars" id="nada_trade" name="nada_trade" placeholder="Trade" value="<?= $NADA_Trade; ?>"></p>
<p><label for="nada_loan">Loan</label> <input type="number" class="dollars" id="nada_loan" name="nada_loan" placeholder="Loan" value="<?= $NADA_Loan; ?>"></p>
<p><label for="nada_retail">Retail</label> <input type="number" class="dollars" id="nada_retail" name="nada_retail" placeholder="Retail" value="<?= $NADA_Retail; ?>"></p>
</div>
<input type="submit" id="Submit" value="Submit">
</form>
<script src="include/js/clipboard.min.js"></script>
<script>
var clipboard = new Clipboard('.fa-clipboard');
clipboard.on('success', function(e) {console.log(e);});
clipboard.on('error', function(e) {console.log(e);});
</script>
Replace
if(isset($_POST['Submit']))
with
if (!empty($_POST))
this checks in general if anything has been posted (if the POST request is not empty -> do this)
Please verify your submit have this ...
<input type="submit" value="Submit" name="submit" />
and your form method is
<form method="POST" action="xyz"> ...
Your code is a bit off.
You're checking
if(isset($_POST['Submit'])) {
Which is not being posted at all. This is why, the if part never gets executed.
You can try to check if it is POST request by
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// …
}
maybe this helps.
You should use filter_input to handle POST and GET params. Using $_POST or $_GET is deprecated.

Data ain't changed after submitted to mysql

i have a code for updating data to myql. It looks doesn't have a problem but it ain't changed
my update code :
//previous data//
....
if (isset($_POST['update'])) {
$nim = mysqli_real_escape_string($connection, ($_POST['nim']));
$name = mysqli_real_escape_string($connection, ($_POST['name']));
$class1 = mysqli_real_escape_string($connection, ($_POST['class2']));
$class2 = mysqli_real_escape_string($connection, ($_POST['class1']));
if (!preg_match("/^[1-9][0-9]*$/",$nim)) {
$error = true;
$nim_error = "NIM only contain numbers";
}
if (!preg_match("/[^a-zA-Z]/",$name)) {
$error = true;
$name_error = "NIM only contain numbers";
}
if (!preg_match("/^[1-9][0-9]*$/",$class1)) {
$error = true;
$class1_error = "Class only contain numbers";
}
if (!preg_match("/^[1-9][0-9]*$/",$class1)) {
$error = true;
$class2_error = "Class only contain numbers";
}
$result = "UPDATE users SET nim='$nim', name='$name', class1='$class1', class1='$class1' WHERE id='$id'";
mysqli_query($connection, $result);
}
?>
and this is my html code :
<div id="popup2" class="overlay">
<div class="popup">
<h2 class="range2">Edit</h2>
<a class="close" href="#">×</a>
<div class="content">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input class="input" type="text" name="nim" placeholder="NIM" required/>
<input class="input" type="text" name="name" placeholder="Name" required/>
<i>SK</i>
<input class="input1" type="text" name="class1" placeholder="00" required/>
<i>-</i>
<input class="input1" type="text" name="class2" placeholder="00" required/>
<input name="update" type="submit" class="button" id="submit" value="Submit">
</form>
</div>
</div>
</div>
is there any wrong code ? Thank you..
It is really hard to explain: Take a look.
If you want to update a single data you will need a identity(Primary
key). That mean which data you want to update.
Below Example: check index.php file
In file index.php change dbname to your database name in connection.
browse project_url/index.php?id=1 [here use any id from your database]
Then update your data.
index.php
//Show existed data againist id
if(isset($_GET['id'])){
$id = $_GET['id'];
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(array('id'=>$id));
$data = $stmt->fetch();
if (empty($data)) {
echo "No data found in user table. Use proper ID.";
}
}
//Update query
$msg = array();
if (isset($_POST['id']) && $_POST['id']!='') { //operation is update, because id exist
if($_POST['nim']!=0 && is_numeric($_POST['nim'])){
$nim = $_POST['nim'];
}else{
$msg[]="Nim only can be number";
}
if($_POST['name']!=''){
$name = $_POST['name'];
}else{
$msg[]="came only can not be empty";
}
if(is_numeric($_POST['class1'])){
$class1 = $_POST['class1'];
}else{
$msg[]="Class1 only can be number";
}
if(is_numeric($_POST['class2'])){
$class2 = $_POST['class2'];
}else{
$msg[]="Class1 only can be number";
}
$id = $_POST['id'];
if(count($msg)==0){
$stmt = $pdo->prepare('UPDATE users SET nim=:nim, name=:name, class1=:class1, class2=:class2 WHERE id=:id');
$result = $stmt->execute(array(
'nim' => $nim,
'name' => $name,
'class1'=> $class1,
'class2'=> $class2,
'id' => $id,
));
if($result){
echo "successfully updated.";
}else{
echo "update failed";
}
}
}else{
//You can run here insert operation because id not exist.
echo "Id not set";
}
?>
<div id="popup2" class="overlay">
<div class="popup">
<h2 class="range2">Edit</h2>
<a class="close" href="#">×</a>
<div class="content">
<?php foreach ($msg as $value) {
echo $value."<br>";
}?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php if(isset($data)){?>
<input class="input" type="hidden" name="id" value="<?php echo $data['id']; ?>" />
<?php } ?>
<input class="input" type="text" name="nim" value="<?php echo isset($data)?$data['nim']:''?>" placeholder="NIM" required/>
<input class="input" type="text" name="name" value="<?php echo isset($data)?$data['name']:''?>" placeholder="Name" required/>
<i>SK</i>
<input class="input1" type="text" name="class1" value="<?php echo isset($data)?$data['class1']:''?>" placeholder="00" required/>
<i>-</i>
<input class="input1" type="text" name="class2" value="<?php echo isset($data)?$data['class2']:''?>" placeholder="00" required/>
<input name="update" type="submit" class="button" id="submit" value="Submit">
</form>
</div>
</div>
</div>
My friend,
only do one thing to resolve this
echo $result = "UPDATE users SET nim='$nim', name='$name', class1='$class1', class1='$class1' WHERE id='$id'";
die;
then submit your form again and you will get your static query into your page then just copy that query and try to run into phpmyadmin then you will get your actual error.

Categories