Edit Using Dropdown - Codeigniter - php

I have these two table in my database:
tbl_province
id | id_prov | prov_name
and
tbl_district
id | id_dist | id_prov | dist_name
and
tbl_myhome
id | id_prov | id_dist | name | address
and I have this controller for edit & update:
public function edit()
{
$this->load->model('m_login');
$level = $this->session->userdata('level');
$data['menu'] = $this->m_login->get_menu_for_level($level);
$data['title'] = 'District Data';
$data['content'] = 'district/v_edit_dist';
$id = $this->uri->segment(3);
$this->db->where('id_dist',$id);
$q = $this->db->get('area_db');
if($q->num_rows()>0){
foreach($q->result() as $row){
$data['id'] = $row->id;
$data['id_dist'] = $id_dist;
$data['dist_name'] = $dist_name;
}
} else {
$data['id'] = '';
$data['id_prov'] ='';
$data['id_dist'] ='';
$data['dist_name'] ='';
}
$this->load->view('v_home',$data);
}
And this is my v_edit_dist source on Dropdown:
<?php
$q = $this->db->get('tbl_myhome');
foreach($q->result() as $row){
$distname = $row->dist_name;
?>
<select name="id_dist" id="id_dist" class="form-control">
<option selected="<?php echo $id_dist;?>"><?php echo $dist_name;?></option>
</select>
When I tried to edit my data per-row, all the data's in the dropdown menu showed up, all the district name just showing up, and the district name in the form was wrong, it's showing the first district id, but actually in the database the data is the fifth district id.
I just confused how to make the district name on the dropdown match with the one in the database, and not all the district names shows up and messing the css. Please help..helep...I'm desperate.
Thank you.

<select name="id_dist" id="id_dist" class="form-control">
<option value="<?php echo $id_dist;?>"><?php echo $dist_name;?></option>
</select>

///// In controller file
public function edit()
{
$this->load->model('m_login');
$level = $this->session->userdata('level');
$data['menu'] = $this->m_login->get_menu_for_level($level);
$data['title'] = 'District Data';
$data['content'] = 'district/v_edit_dist';
$id = $this->uri->segment(3);
$q = $this->db->get('tbl_district');
$district = array();
if($q->num_rows()>0){
foreach($q->result() as $row){
$district[]= $row;
}
}
$data['id_dist'] = $id;
$data['district']= $district;
$this->load->view('v_home',$data);
}
// in view file
<select name="id_dist" id="id_dist" class="form-control">
<?php
if(count($district)){
foreach($district as $item){
?>
<option value="<?php echo $item->id_dist; ?>" <?php if($item->id_dist==$id_dist) echo 'selected';?>><?php echo $item->dist_name;?></option>
<?php
}
}
?>
</select>

Use this code on your view page
<select name="id_dist" id="id_dist" class="form-control">
<?php
$q = $this->db->get('tbl_myhome');
$result = $q->result();
foreach($result as $row){
?>
<option value="<?php echo $row->id_dist;?>" <?php if($row->id_dist==$id_dist){ echo 'selected';} ?>><?php echo $row->dist_name;?></option>
<?php } ?>
</select>

Related

adding selected attribute to dropdownlist item if is in array

I have code table like this.
code
00
01
02
03
I'm adding this codes as array from dropdown list to assigned_code column in the user table.
assigned_code
00,02,03
When I want to edit the codes assigned to the user, I need to add selected attribute which codes are assigned previously in dropdown list. I'm stuck at this point. Can anyone show me the how to do this?
<?php
$assigned_code = array();
$sql = "select assigned_code from user where ID=1";
$rq = mysqli_query($conn, $sql);
$count = mysqli_num_rows($rq);
if ($count>0) {
while ($row = mysqli_fetch_array($rq)) {
$assigned_code=$row["$assigned_code"];
}
}
?>
<select name="u_codes[]" id="u_codes" class="selectpicker" multiple="multiple">
<?php
$sql = "select code,desc from codes";
$rq = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($rq)) {
$code = $row["code"];
$codeDesc = $row["desc"];
if ($assigned_code == $code) {
echo '<option value="'.$code.'" selected="selected">'.$codeDesc.'</option>';
} else {
echo '<option value="'.$code.'">'.$codeDesc.'</option>';
}
}
?>
</select>
try using array_push to items
array_push($assigned_code,$row["$assigned_code"]);
because every time you use $assigned_code=$row["$assigned_code"];
you erase the existing value inside $assigned_code
and debug it with var_dump() it will give you a clear information about the data and it's type.
$assigned_code = array();
$assigned_code=$row["$assigned_code"];
$expArr = explode(',',$assigned_code);
if (in_array($code,$expArr)) {
echo '<option value="'.$code.'" selected="selected">'.$codeDesc.'</option>';
} else {
echo '<option value="'.$code.'">'.$codeDesc.'</option>';
}
in_array perfectly worked for me.

Data not being inserted mysql

I am building a custom CMS for myself and its going great but for some reason the system is not inserting a certain field called categories. I have a table called categories and i am able to insert those categories with no problems.
On my addnewpost.php page I have this form field that lets me select an added Category..
<select name="Category" id="categorytitle" class="form-control">
<?php
$sql = "SELECT id,title FROM category";
$stmt = $conn->query($sql);
while ($DataRows = $stmt->fetch()){
$id = $DataRows["id"];
$CategoryName = $DataRows["title"];
?>
<option value=""><?php echo $CategoryName; ?></option>
<?php } ?>
</select>
above all that I have this to inset the data into the database in a table called posts...
<?php
if(isset($_POST["Submit"])){
$posttitle = $_POST["posttitle"];
$Category = $_POST["Category"];
$image = $_FILES["image"]["name"];
$target = "../uploads/".basename($_FILES["image"]["name"]);
$posttext = $_POST["postdescription"];
$admin = "phillip";
date_default_timezone_set("Europe/London");
$CurrentTime=time();
$DateTime=strftime("%B-%d-%Y %H:%M:%S",$CurrentTime);
if(empty($posttitle)){
$_SESSION["ErrorMessage"] = "Post title cannot be empty";
redirect_to("addnewpost.php");
} elseif (strlen($posttitle)<10){
$_SESSION["ErrorMessage"] = "Post title should be greater than 10 characters";
redirect_to("addnewpost.php");
} else {
//All is good insert into the database
$sql = "INSERT INTO posts(datetime,title,category,author,image,post)";
$sql .= "VALUES(:dateTime,:postTitle,:categoryName,:adminName,:imageName,:postDescription)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':dateTime',$DateTime);
$stmt->bindValue(':postTitle',$posttitle);
$stmt->bindValue(':categoryName',$Category);
$stmt->bindValue(':adminName',$admin);
$stmt->bindValue(':imageName',$image);
$stmt->bindValue(':postDescription',$posttext);
$Execute=$stmt->execute();
move_uploaded_file($_FILES["image"]["tmp_name"],$target);
if($Execute){
$_SESSION["SuccessMessage"]="Post with id : ".$conn->lastInsertId()." Added Successfully";
redirect_to("addnewpost.php");
} else {
$_SESSION["ErrorMessage"]="Something went wrong. Try again";
redirect_to("addnewpost.php");
}
}
}
?>
Here is a screengrab showing that the category fields are empty. I do have display errors enabled but none are showing up. Any thoughts appreciated...
Thank you Nigel and Felippe. I just took out the option value so it's just this instead...
<option><?php echo $CategoryName; ?></option>
That's made it all work perfectly. Been looking at this for hours as well.
Thank you both.
<select name="Category" id="categorytitle" class="form-control">
<?php
$sql = "SELECT id,title FROM category";
$stmt = $conn->query($sql);
while ($DataRows = $stmt->fetch()){
$id = $DataRows["id"];
$CategoryName = $DataRows["title"];
?>
<option value="<?php echo $CategoryName; ?>"><?php echo $CategoryName; ?></option>
<?php } ?>
</select>
This is more like it

Select all data after selecting another option

I am trying to create a submission on a form where I can show all results from a table as well as show individual results. I can achieve the page load to show all until the form is submitted, however when I then try and select all again im struggling.
On page load im simply doing:
<?php
if (isset($_POST['submit'])) {
$teamData = $_POST['teamData'];
var_dump($teamData);
$sql = "SELECT * FROM team WHERE dashboardId = 1 AND id = $teamData";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$teamName = $row['name'];
}
}
} else {
$teamName = 'All';
echo 'no submission yet';
}
?>
Setting the variable to say 'all'
<p>Team: <?php echo $teamName; ?></p>
Once an option has been selected it check the database and uses the name of and sets it. However in the dropdown list if i want to show all results again i get an error of:
Undefined variable: teamName
which makes sense because of my form:
<form method="POST" action="">
<select name="teamData">
<option selected value="" disabled>Select your team</option>
<option value="allTeamData">All team data</option>
<?php teamMembers(); ?>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
I am just struggling to understand the logic of how to select all again from the drop down.
$teamName = 'All'; // Initialise the variable at top
// Change the condition to this for better restriction
if ($_POST && isset($_POST['submit'])) {
$teamData = $_POST['teamData'];
var_dump($teamData);
$sql = "SELECT * FROM team WHERE dashboardId = 1 AND id = $teamData";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$teamName = $row['name'];
}
}
}

Calling method from another php file

So I'm trying my hand at creating php methods from scratch. My classes aren't exactly classes yet, I'm still working on that. Anyway, my issue's I can't seem to get the values I expect from my database. Here's a snippet of my code:
file1.php
<?php function dbConnect() {
$connection = mysqli_connect("localhost", "music_root", "", "music");
if($connection->connect_error) {
return null;
}
return $connection;}
function getCategory() {
$cn = dbConnect();
if($cn == null) {
echo "Failed to connect to database.";
} else {
$fetchQuery = mysqli_query($cn, "SELECT * FROM tbl1 ORDER BY 'Name'") or die(mysqli_error($cn));
if(mysqli_num_rows($fetchQuery) > 0) {
while($item = mysqli_fetch_array($fetchQuery)) {
return $item["Name"];
}
}
}} ?>
Here's the snippet of how I call the above method in file2.php
<?php ini_set("display_errors", 1);
include_once("file1.php");
$con = dbConnect();
$updateStat = false; ?>
<div>
<label>Genre</label>
<select id="genre" name="genre" value="Please select genre">
<option value="<?php $con->getCategory() ?>"></option>
</select>
</div>
I've tried printing a message at the start of the method to see if the it's being called but the message did not print either so I was wondering, what am I possibly missing here?
I think you have serveral mistakes in your code ... i guess, you don't use OOP (classes) so i modfiy a example which should work .. .if not, please post error messages
file1.php
function getCategory($cn) {
$out = array();
if($cn == null) {
echo "Failed to connect to database.";
} else {
$fetchQuery = mysqli_query($cn, "SELECT * FROM tbl1 ORDER BY 'Name'") or die(mysqli_error($cn));
if(mysqli_num_rows($fetchQuery) > 0) {
while($item = mysqli_fetch_array($fetchQuery)) {
$out[] = $item["Name"];
}
}
return $out;
}
}
fil2.php
<?php
ini_set("display_errors", 1);
require_once("file1.php");
$con = dbConnect();
$updateStat = false;
$res = getCategory($con);
?>
<div>
<label>Genre</label>
<select id="genre" name="genre" value="Please select genre">
<?php
foreach($res as $cat):
?>
<option value="<?php echo $cat ?>"><?php echo $cat ?></option>
<?php endforeach;?>
</select>

select query in view file in codeigniter

This is my simple php html code.
<select id="district" name="district">
<option value="">Select district</option>
<?php
$sql="SELECT * FROM district";
$result = mysqli_query($sql);
while($row = mysqli_fetch_array($result))
{
$district_id = $row['district_id'] ;
$district_name = $row['district_name'];
?>
<option value="<?php echo $district_id;?>"><?php echo $district_name;?></option>
<?php
}
?>
</select>
But it's not working. database is autoloaded.What will be the problem.
you are using direct query not with CI db instance so you will not getting db connection try in CI way
$sql ="SELECT * FROM district";
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {?>
<option value="<?php echo $row->district_id;?>"><?php echo $row->district_name;?></option>
<?php }
}
or
$this->db->from('district');
$query = $this->db->get();
if($query->num_rows > 0 ) {
foreach ($query->result() as $row) {
// do your stuff
}
}
Better method to work with MVC framework:- use model for db queries and return data on view via controller (do not use direct query on view)
May be your get CI instance wirte you CI query directly
$CI =& get_instance();
$CI->load->model('modelname');
$result = $CI->modelname->functionname();
If you must access db directly from, view try this:
$this->load->view('view_name',["db"=>$this->db,"other_data=>"data"]);
//$this->db //CI db instance
In view you can now do:
$db->query("select * from table")->result();
please try this
<select id="district" name="district">
<option value="">Select district</option>
$result = mysqli_query($sql);
while($row = $result->fetch_array())
{
$district_id = $row['district_id'] ;
$district_name = $row['district_name'];
?>
<option value="<?php echo $district_id;?>"><?php echo $district_name;?></option>
<?php } ?>

Categories