How to update image in codeigniter? - php

I created image upload which works fine but I also want it to be updated. When I add a need image it updates correctly but I if don't want to change the image and leave it as it is, then my current image can't be retrieve.i want to update my factory_name(field name) only sometimes. when i update image it updated successfully,but when i update factory_name only the existing image is missing. Please help me how to do this?
this my view file
<form action="<?php echo base_url('login/insert_factory/'.$id); ?>" method="POST" enctype="multipart/form-data">
<?php
$id =$this->uri->segment(3);
if($id == "")
{
?>
<div class="form-group">
<label class="form-label" for="field-1">Factory Name</label>
<!--span class="desc">e.g. "Beautiful Mind"</span-->
<div class="controls">
<input type="text" name="factory_name" class="form-control" >
</div>
</div>
<?php
}
else
{ ?>
<div class="form-group">
<label class="form-label" for="field-1">Factory Name</label>
<!--span class="desc">e.g. "Beautiful Mind"</span-->
<div class="controls">
<input type="text" name="factory_name" value="<?php echo $result->factory_name; ?>" class="form-control" >
</div>
</div>
<?php } ?>
<?php
if($id == "")
{
?>
<div class="form-group">
<label class="form-label" for="field-1">Upload Logo</label>
<!--span class="desc">e.g. "Beautiful Mind"</span-->
<div class="controls">
<input type="file" name="upload_logo" />
</div>
</div>
<?php
}
else
{ ?>
<div class="form-group">
<label class="form-label" for="field-1">Upload Logo</label>
<!--span class="desc">e.g. "Beautiful Mind"</span-->
<div class="controls">
<input type="file" name="upload_logo" value="<?php echo $result->factory_logo; ?>" />
</div>
</div>
<?php } ?>
<?php
if($id == "")
{
?>
<div class="form-group">
<div class="controls">
<input type="submit" class="btn btn-primary" value="submit" />
</div>
</div>
<?php
}
else
{ ?>
<div class="form-group">
<div class="controls">
<input type="submit" class="btn btn-primary" value="Update" />
</div>
</div>
<?php } ?>
</form>
this my controller code:
public function insert_factory()
{
$id =$this->uri->segment(3);
if($id == "")
{
if(isset($_FILES['upload_logo'])){
$errors= array();
$file_name = $_FILES['upload_logo']['name'];
$file_tmp =$_FILES['upload_logo']['tmp_name'];
if(empty($errors)==true){
move_uploaded_file($file_tmp,"assets/uploads/".$file_name);
// echo "Success";
}else{
print_r($errors);
}
$fields = array(
'factory_name' => $this->input->post('factory_name',True),
'factory_logo' => $file_name
);
$result = $this->login_model->insert_factory($fields);
if($result){
$this->session->set_flashdata('success_msg',' Factory Created Successfully!');
redirect('login/view_factory');
}else{
$this->session->set_flashdata('error_msg','Factory Cannot Created.!');
redirect('login/create_factory');
}
}
}else{
if(isset($_FILES['upload_logo'])){
$errors= array();
$file_name = $_FILES['upload_logo']['name'];
$file_tmp =$_FILES['upload_logo']['tmp_name'];
if(empty($errors)==true){
move_uploaded_file($file_tmp,"assets/uploads/".$file_name);
// echo "Success";
}else{
print_r($errors);
}
$fields = array(
'factory_name' => $this->input->post('factory_name',True),
'factory_logo' => $file_name
);
$this->db->where('factory_id', $id);
$this->db->update('create_factory', $fields);
if($this->db->affected_rows()>0)
{
$this->session->set_flashdata('success_msg',' Factory Updated Successfully!');
}else{
$this->session->set_flashdata('error_msg','Factory Cannot Updated.!');
redirect('login/create_factory');
}
redirect(base_url('login/view_factory'));
}
}
}
And this my model file:
public function insert_factory($fields)
{
$this->db->insert('create_factory',$fields);
return ($this->db->affected_rows() != 1) ? false : true;
}

In your controller, in both if and else blocks, please modify your existing code in order to not update empty image when image is not provided and only factory name is provided.
This code in both if and else blocks:
$fields = array(
'factory_name' => $this->input->post('factory_name',True),
'factory_logo' => $file_name
);
Needs to be change to:
$fields['factory_name'] = $this->input->post('factory_name', True);
if (!empty($file_name)) {
$fields['factory_logo'] = $file_name;
}

Related

How to update the image name in SQL table and store it in the directory?

I wanted to update the image "name" to SQL and store the new image file in the directory, But I'm not able to find a good way to do it and my existing code is not working as well for the file upload.
.PHP file
<?PHP
$base_url = "https://example.com/"; // Current page path URL: https://example.com/settings#/edit-profile
$uniqueid = $_SESSION['uniqueid']; // Current user unique id.
// For Extension
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
?>
<?php
if(!empty($uniqueid))
{
$edituserid = $uniqueid;
$query_result=mysqli_query($con,"SELECT * FROM tbl_admin WHERE uniqueid='$edituserid'");
$numrows=mysqli_num_rows($query_result);
if(!$numrows)
{
$_SESSION['error'] = "Somthing went wrong!";
header('Location:'.$base_url.'settings#/edit-profile');
}
else
{
$Query = mysqli_query($con,"SELECT * FROM tbl_admin WHERE uniqueid='$edituserid'");
$editRow = mysqli_fetch_array($Query);
$edituserid = $editRow['uniqueid'];
$previousimage = $editRow['profile_image'];
}
}
?>
<?php
if(isset($_POST['update_user_info']))
{
$first_name = mysqli_real_escape_string($con,$_POST['first_name']);
$last_name = mysqli_real_escape_string($con,$_POST['last_name']);
$uniqueid1 = mysqli_real_escape_string($con,$_POST['uniqueid']);
// Image preparation
$profile_image = $_FILES['profile_image']['name'];
if($profile_image)
{
$profile_image_original = ($_FILES['profile_image']['name']);
$profile_image = ($uniqueid);
$profile_image_extension = getExtension($profile_image_original);
$extension = strtolower($profile_image_extension);
$dot = ".";
$profile_image_type = $_FILES['profile_image']['type'];
$profile_image_size = $_FILES['profile_image']['size'];
$image_file_name = "assets/user_images/".$profile_image.=$dot.=$extension;
move_uploaded_file($_FILES['profile_image']['tmp_name'], $image_file_name);
}
else
{
$profile_image = $previousimage;
}
if(!empty($_FILES['profile_image']['name']))
{
$sql2 = "UPDATE `tbl_admin` SET `first_name`='$first_name', `last_name`='$last_name', `uniqueid`='$uniqueid1', `profile_image`='$profile_image' WHERE uniqueid='$edituserid'";
}
else
{
$sql2 = "UPDATE `tbl_admin` SET `first_name`='$first_name', `last_name`='$last_name', `uniqueid`='$uniqueid1' WHERE uniqueid='$edituserid'";
}
//var_dump($sql); exit();
$result2 = mysqli_query($con, $sql2);
if($result2)
{
$_SESSION['success'] = "Update successful!";
header('Location:'.$base_url.'settings#/edit-profile');
} else {
$error="Something went wrong !";
}
$first_name = '';
$last_name = '';
$uniqueid1 = '';
}
?>
HTML form
<form method="POST" enctype="multipart/form-data">
<div class="row">
<div class="col-md-4 col-sm-12">
<div class="container">
<div class="avatar-upload">
<div class="avatar-edit">
<input type="file" id="imageUpload" name="profile_image" accept="image/*" />
<label for="imageUpload"></label>
</div>
<div class="avatar-preview">
</div>
</div>
</div>
</div>
<div class="form-group row">
<label for="staticEmail" class="col-sm-4 col-form-label">Email</label>
<div class="col-sm-8">
<input type="text" readonly class="form-control" id="staticEmail" value="<?php if(!empty($editRow)){ echo $editRow['email']; } ?>">
</div>
</div>
<div class="form-group row">
<label for="inputFirstName" class="col-sm-4 col-form-label">First Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="inputFirstName" name="first_name" value="<?php if(!empty($editRow)){ echo $editRow['first_name']; } ?>">
</div>
</div>
<div class="form-group row">
<label for="inputLastName" class="col-sm-4 col-form-label">Last Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="inputLastName" name="last_name" value="<?php if(!empty($editRow)){ echo $editRow['last_name']; } ?>">
</div>
</div>
<div class="form-group row">
<label for="inputSxID" class="col-sm-4 col-form-label">ID</label>
<div class="col-sm-8">
<input type="text" readonly class="form-control" id="inputSxID" name="uniqueid" value="<?php if(!empty($editRow)){ echo $editRow['uniqueid']; } ?>">
</div>
</div>
<button type="submit" class="btn btn-primary" name="update_user_info">Update</button>
</div>
</div>
</form>
It handles This table
id
first_name
last_name
email
profile_image
1
Joe
Dilon
abc#mail.com
abc.jpg
To // after success post update
id
first_name
last_name
email
profile_image
1
Changed
Changed
abc#mail.com
abc.jpg //No Response
And also there is no image file transfer into the targeted directory path. I'm not able to figure what's wrong or best way to do it correctly.

Codeigniter form_open_multipart didn't respond

Been trying out codeigniter and wanted to create a form with file upload using the upload class. However when i try to save the form, it didn't respond and just show the same page. I've been looking around, but I can't seem to find out how to make this work.
This is the controller Product.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
Class Product extends CI_Controller{
function __construct(){
parent::__construct();
check_not_login();
$this->load->model('product_m');
}
public function index(){
$data['row'] = $this->product_m->get();
$this->template->load('template', 'product/data/product_data', $data);
}
public function add(){
$product = new stdClass();
$product->product_id = null;
$product->product_name = null;
$product->customer_name = null;
$product->supplier_name = null;
$product->weight = null;
$product->product_date = null;
$product->expired_date = null;
$product->image = null;
$product->barcode = null;
$data = array(
'page' => 'add',
'row' => $product
);
$this->template->load('template', 'product/data/product_form', $data);
}
public function edit($id){
$query = $this->product_m->get($id);
if($query->num_rows()>0){
$product = $query->row();
$data = array(
'page' => 'edit',
'row' => $product
);
$this->template->load('template', 'product/data/product_form', $data);
}else{
echo "<script>alert('Data not found');";
echo "window.location='".site_url('product')."';</script>";
}
}
public function process(){
$post = $this->input->post(null, TRUE);
if(isset($_POST['add'])){
$config['upload_path'] = './uploads/product';
$config['allowed_types'] = 'jpeg|pdf|jpg|png|doc|docs|xls|xlsx';
$config['max_size'] = 5120;
$config['file_name'] = 'product-'.date('ymd').'-'.substr(md5(rand()),0,10);
$this->load->library('upload', $config);
if(#$_FILES['image']['name'] !=null){
if($this->upload->do_upload('image')){
$post['image'] = $this->upload->data('file_name');
$this->product_m->add($post);
if($this->db->affected_rows() > 0){
$this->session->set_flashdata('success', 'Data saved successfully');
}
redirect('product');
}else{
$error = $this->upload->display_errors();
$this->session->set_flashdata('error', $error);
redirect('product/add');
}
}
else{
$post['image'] = null;
$this->product_m->add($post);
if($this->db->affected_rows() > 0){
$this->session->set_flashdata('success', 'Data saved successfully');
}
redirect('product');
}
}else if(isset($_POST['edit'])){
$this->product_m->edit($post);
}
}
public function del($id){
$this->product_m->del($id);
if($this->db->affected_rows() > 0){
$this->session->set_flashdata('Success', 'Data successfully deleted');
}
redirect('product');
}
}
Script for the form product_form.php
<section class="content-header">
<h1>
Product
<small>Add product</small>
</h1>
</section>
<section class ="content">
<div class="box">
<div class="box-header">
<h3 class="box-title"> product</h3>
<div class="pull-right">
<a href="<?=site_url('product')?>" class="btn btn-warning btn-flat">
<i class="fa fa-undo"></i> Back
</a>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<?php echo form_open_multipart('product/process');?>
<div class="form-group">
<label>Product Name *</label>
<input type="hidden" name="id" value="<?=$row->product_id?>">
<input type="text" name="product_name" value="<?=$row->product_name?>" class="form-control" required>
</div>
<div class="form-group">
<label>Customer Name *</label>
<input type="text" name="customer_name" value="<?=$row->customer_name?>" class="form-control" required>
</div>
<div class="form-group">
<label>Supplier Name *</label>
<input type="text" name="supplier_name" value="<?=$row->supplier_name?>" class="form-control" required>
</div>
<div class="form-group">
<label>Weight(kg) *</label>
<input type="number" name="weight" value="<?=$row->weight?>" class="form-control" required>
</div>
<div class="form-group">
<label>Product Date(dd/mm/yyyy) *</label>
<input type="text" name="product_date" value="<?=$row->product_date?>" class="form-control" required>
</div>
<div class="form-group">
<label>Expired Date(dd/mm/yyyy) *</label>
<input type="text" name="expired_date" value="<?=$row->expired_date?>" class="form-control" required>
</div>
<div class="form-group">
<label>Technical Data</label>
<input type="file" name="image" class="form-control" >
</div>
<!-- FORM BARCODE -->
<div class="form-group">
<label>Barcode</label>
<input name="barcode" class="form-control" value="
<?php
$angka = rand(1000000,9999999);
$random = rand(0,25);
$random1 = rand(0,25);
$random2 = rand(0,25);
$name = array("A", "B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q",
"R","S","T","U","V","W","X","Y","Z");
echo $name[$random],$name[$random1],$name[$random2],$angka;
$row->barcode
?>" readonly>
</div>
<div class="form-group">
<button type="submit" name="<?=$page?>" class="btn btn-success btn-flat">
<i class="fa fa-paper-plane"> Save</i>
</button>
<button type="Reset" class="btn btn-flat"> Reset</button>
</div>
<!-- </form> -->
<?php echo form_close();?>
</div>
</div>
</div>
</div>
</section>
Load the form helper.
function __construct(){
parent::__construct();
check_not_login();
$this->load->model('product_m');
$this->load->helper('form');
}

Issue when trying to update clients info

I'm having an issue where when I go to upload or update a client, it will automatically take the clients profile off if you do not add an image to upload. But If I just want to update their website or motto, and click update, I don't want to have to try and search their image down again and upload it just to update a few items. Any Ideas on why it's doing this? Thank You In Advance.
Heres my code:
<?php
//Gets The Users info when editing it.
$stmt = $DB_con->prepare('SELECT * FROM sponsors WHERE id='.$id);
$stmt->execute();
if($stmt->rowCount() > 0)
{
$row=$stmt->fetch(PDO::FETCH_ASSOC);
extract($row);
}
?>
<div class="col-xs-12 col-sm-6 col-md-8">
<form method="post" class="form-horizontal" enctype="multipart/form-data">
<div class="form-group">
<label for="sponsor_name" class="col-sm-3 control-label">Sponsor Name:</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="sponsor_name" id="sponsor_name" value="<?php echo $name;?>">
</div>
</div>
<div class="form-group">
<label for="sponsor_phone" class="col-sm-3 control-label">Sponsor Phone Number:</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="sponsor_phone" id="sponsor_phone" value="<?php echo $phone;?>">
</div>
</div>
<div class="form-group">
<label for="sponsor_moto" class="col-sm-3 control-label">Sponsors Motto:</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="sponsor_motto" id="sponsor_motto" value="<?php echo $motto;?>">
</div>
</div>
<div class="form-group">
<label for="sponsors_website" class="col-sm-3 control-label">Sponsors Website:</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="sponsor_website" id="sponsor_website" value="<?php echo $website;?>">
</div>
</div>
<div class="form-group">
<label for="sponsor_on" class="col-sm-3 control-label">Sponsor on or off?:</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="sponsor_on" id="sponsor_on" value="<?php echo $live;?>">
</div>
</div>
<div class="form-group">
<label for="image" class="col-sm-3 control-label"> Profile Picture </label>
<div class="col-sm-9">
<p><img id="image" src="../images/sponsors/<?php echo $row['logo'];?>" height="150" width="150" /></p>
<div class="col-sm-9">
<input class="input-group" type="file" name="user_image" accept="image/*" />
</div>
<br>
<br>
<div class="col-sm-offset-3 col-sm-9">
<button type="submit" name="btn_save_updates" class="btn btn-info waves-effect waves-light">Update Sponsor</button>
Delete Sponsor</button>
</div>
</div>
</div>
</form>
Heres my PHP code that will update the Database.
<?php
if(isset($_GET['edit_id']) && !empty($_GET['edit_id']))
{
$id = $_GET['edit_id'];
$stmt_edit = $DB_con->prepare('SELECT * FROM sponsors WHERE id =:uid');
$stmt_edit->execute(array(':uid'=>$id));
$edit_row = $stmt_edit->fetch(PDO::FETCH_ASSOC);
extract($edit_row);
}
else
{
header("Location: ../../login.php");
}
if(isset($_POST['btn_save_updates']))
{
$username = $_POST['user_name'];
$description = $_POST['description'];
$imgFile = $_FILES['user_image']['name'];
$tmp_dir = $_FILES['user_image']['tmp_name'];
$imgSize = $_FILES['user_image']['size'];
if($imgFile)
{
$upload_dir = '../images/sponsors/';
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION));
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif');
$userprofile = rand(1000,1000000).".".$imgExt;
if(in_array($imgExt, $valid_extensions))
{
if($imgSize < 5000000)
{
unlink($upload_dir.$edit_row['logo']);
move_uploaded_file($tmp_dir,$upload_dir.$userprofile);
}
else
{
$errMSG = "Sorry, Your File Is Too Large To Upload. It Should Be Less Than 5MB.";
}
}
else
{
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF Extension Files Are Allowed.";
}
}
else
{
$userprofile = $edit_row['userprofile'];
}
if(!isset($errMSG))
{
$sponsorname = $_POST['sponsor_name'];
$motto = $_POST['sponsor_motto'];
$phone = $_POST['sponsor_phone'];
$website = $_POST['sponsor_website'];
$son = $_POST['sponsor_on'];
$stmt = $DB_con->prepare('UPDATE sponsors SET name=:sname, motto=:smotto, phone=:sphone,website=:swebsite,live=:son, logo=:upic WHERE id=:uid');
$stmt->bindParam(':sname',$sponsorname);
$stmt->bindParam(':smotto',$motto);
$stmt->bindParam(':sphone',$phone);
$stmt->bindParam(':swebsite',$website);
$stmt->bindParam(':son',$son);
$stmt->bindParam(':upic',$userprofile);
$stmt->bindParam(':uid',$id);
if($stmt->execute()){
?>
<script>
alert('Successfully Updated...');
window.location.href='managesponsors.php?action=sponsorupdated';
</script>
<?php
}
else{
$errMSG = "Sorry User Could Not Be Updated!";
}
}
}
?>

how to add either a link or file with codeigniter

I have two fields one for link and one for file upload in form, how do i add only one of those i.e. either link or file in database,
Sorry for any wrong code and methods, I am a newbie here and this is my first question in stack overflow. Hope you all help me out.
My Controller is
public function add_scrolllink()
{
$this->form_validation->set_rules('stitle','File Title','trim|required');
$this->form_validation->set_rules('slink','File Link','trim|required');
if(empty($_FILES['sfile']['name']))
{
$this->form_validation->set_rules('slink','File Link','required');
}
if($this->form_validation->run() == FALSE)
{
$this->load->view("add_scrolllink");
}
else
{
$slink_id = $this->input->post('stitle');
$slink_files = $this->input->post('slink');
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'pdf|docx|doc';
$config['max_size'] = 9000;
$this->upload->initialize($config);
$this->load->library('upload',$config);
if(!$this->upload->do_upload('slink'))
{
$msg1 = $this->upload->display_errors();
header("Location:".base_url()."news/add_scrolllink?msg1=$msg1");
}
else
{
$output = $this->upload->data();
$file2 = $output['file_name'];
$this->load->model('mpages');
$output1 = $this->mpages->add_scrolllink($slink_title,$file2);
if($output1)
{
$msg = "Scrolling Link added successfully!";
header("Location:".base_url()."news/scrolllink_list?
msg=$msg");
}
else
{
$msg1 = 'Scrolling Link add failed. Try again!';
header("Location:".base_url()."news/add_scrolllink?
msg1=$msg1");
}
}
}
//My View is
<form action="<?php echo base_url(); ?>news/add_scrolllink" method="post"
role="form" enctype="multipart/form-data">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-body">
<div class="form-group">
<label>Scrolling Link Title</label>
<input type="text" name="stitle" class="form-
control" value="<?php echo set_value('stitle'); ?>" placeholder="Enter
Scrolling Link Title">
</div>
<style type="text/css">
p.help-block{color:#ff0000;}
</style>
<div class="form-group">
<label>Scrolling Link</label>
<input type="text" name="slink" class="form-control"
value="<?php echo set_value('slink'); ?>" placeholder="Enter Scrolling
Link">
</div>
OR ADD FILE TO SCROLL LINK
<div class="form-group">
<label>Choose File to Upload</label>
<input type="file" name="slink" class="form-
control">
</div>
<input type="submit" name="submit" class="btn btn-
primary" value="Add Link"><br>
<?php echo "<br><span
style='color:#ff0000;'>".validation_errors()."</span>"; ?>
<?php
if(isset($_GET['msg'])){
echo "<div class='alert alert-success
fadein'>".$_GET['msg']."</div>";
}
if(isset($_GET['msg1'])){
echo "<div class='alert alert-danger
fadein'>".$_GET['msg1']."</div>";
}
?>
</div>
</div>
</div>
<div class="col-md-2"></div>
<div class="clearfix"></div>
</div>
</form>
you have use jquery to get input box value using this code and set some condition
$('#slink-id').val(); // set link field input box id
$('#slinkFile-id').val(); //set upload file field id
if($('#slink-id').val() != '' && $('#slinkFile-id').val() == ''){
// setread only your file field
}else{
// set read only link field
}

header location is not working after processing the process_student.php page

My code in the addstudent.php page
<?php include 'lib/header.php'; ?>
<div class="container mt-2 ">
<div class="row">
<div class="col-lg-12">
<div class="panel ">
<dev class="panel-heading main-color-bg bg-faded">
<h3 class="panel-title">Add Student <span class="pull-right">Back</span></h3>
</dev>
<div class="panel-body">
<form class="form form-control" action="lib/process_student.php" method="POST">
<fieldset class="form-group">
<label for="name"><strong>Student Name</strong></label>
<input type="text" class="form-control" id="name" name="name" placeholder="Student Name" required="1">
</fieldset>
<fieldset class="form-group">
<label for="email"><strong>Student Email</strong></label>
<input type="email" class="form-control" id="email" name="email" placeholder="Student Email" required="1">
</fieldset>
<fieldset class="form-group">
<label for="phone"><strong>Student Phone</strong></label>
<input type="text" class="form-control" id="phone" name="phone" placeholder="Student Phone" required="1">
</fieldset>
<fieldset class="form-group">
<input type="hidden" name="action" value="add">
<input type="submit" class="btn btn-primary" id="submit" name="submit" Value="Add Student">
</fieldset>
</form>
</div
</div>
</div>
</div>
</div>
<?php include 'lib/footer.php'; ?>
Now when it goes to the process_student.php page it stuck there. My process_student.php
<?php
include_once 'Session.php';
include 'Database.php';
Session::init();
$db = new Database;
$tablename = "tbl_student";
if(isset($_REQUEST["action"]) && !empty($_REQUEST["action"])) {
if($_REQUEST["action"] == "add") {
$studentdata = ["name" =$_POST["name"],"email" =$_POST["email"],"phone" =$_POST["phone"]];
$insertdata = $db->insert($tablename,$studentdata);
if ($insertdata) {
$msg = "<h2 class='alert alert-success'><strong>Success! Data inserted successfuly</strong></h2>";
return $msg;
} else {
$msg = "<h2 class='alert alert-danger'><strong>Error! No data inserted</strong></h2>";
return $msg;
}
/* redirecting to the index page */
Session::set("msg",$msg);
$home_url = "../index.php";
ob_start();
header("Location:".$home_url);
exit();
}elseif ($_REQUEST["action"] == "edit") {
$id = $_POST["id"];
if (!empty($id)){
$studentdata = ["name" =$_POST["name"],"email" =$_POST["email"],"phone" =$_POST["phone"]];
$tablename = "tbl_student";
$condition = ["id" =$id];
$updateddata = $db->update($tablename,$studentdata,$condition);
if ($updateddata) {
$msg = "<h2 class='alert alert-success'><strong>Success! Data updated successfuly </strong></h2>";
return $msg;
} else {
$msg = "<h2 class='alert alert-danger'><strong>Error! No data updated </strong></h2>";
return $msg;
}
try {
Session::set("msg",$msg);
header("Location:../index.php");
} catch (Exception $e) {
die("sorry".$e->getMessage());
}
}else {
# code...
}
}
}
?>
Remove return statement from this part of code. As return statement is returning back without executing the remaining code.
if ($insertdata) {
$msg = "<h2 class='alert alert-success'><strong>Success! Data inserted successfuly</strong></h2>";
} else {
$msg = "<h2 class='alert alert-danger'><strong>Error! No data inserted</strong></h2>";
}
Will work!!
Remove return because return exits the execution of the current script
Add below code In your addstudent.php add this code
if(isset($_SESSION['msg'])){
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}

Categories