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 } ?>
Related
I would like to save variable from database to <option>.
PHP code:
<?php
$query = $db->prepare("SELECT * FROM classes");
$query->execute();
$result = $query->fetchAll();
?>
<script>var select_class = document.getElementById('select_class');</script>";
<?php
foreach ($result as $to_result)
{
?>
<script>
var option = document.createElement('option');
option.value = "<?php echo($to_result['name']); ?>";
select_class.appendChild(option);
</script>
<?php
}
?>
HTML code:
<select id="select_class"></select>
Database:
ID_class[1] = something
...
ID_class[12] = something
TypeError: select_class is null
But why? I dont know what is my problem.
There were several mistakes in you code. For example, you reopened a script tag while the old one wasn't even closed.
Besides that, I don't think that the javascript was needed in this code. I've simplified it for you:
<select id="select_class">
<?php
$query = $db->prepare("SELECT * FROM classes");
$query->execute();
$result = $query->fetchAll();
foreach ($result as $to_result)
{
?>
<option value="<?php echo $to_result['name']; ?>">
<?php echo $to_result['name']; ?>
</option>
<?php
}
?>
</select>
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'];
}
}
}
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>
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>
I've been using mysql and it did what I want, but as my project is getting larger, I decided to opt for mysqli.
I looked at the tutorial at enter link description here which was really straight forward up until the point where I want to display some data
stored procedure (connect.php)
<?php
function db_connect() {
// Define connection as a static variable, to avoid connecting more than once
static $con;
// Try and connect to the database, if a connection has not been established yet
if(!isset($con)) {
// Load configuration as an array. Use the actual location of your configuration file
$config = parse_ini_file('config.ini');
$con = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
}
// If connection was not successful, handle the error
if( $con === false) {
// Handle error - notify administrator, log to a file, show an error screen, etc.
return mysqli_connect_error();
}
return $con;
}
function db_query($query) {
// Connect to the database
$con = db_connect();
// Query the database
$result = mysqli_query( $con,$query);
return $result;
}
function db_error() {
$con = db_connect();
return mysqli_error($con);
}
function db_select($query) {
$rows = array();
$result = db_query($query);
// If query failed, return `false`
if($result === false) {
return false;
}
// If query was successful, retrieve all the rows into an array
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
function db_quote($value) {
$con = db_connect();
return "'" . mysqli_real_escape_string($con,$value) . "'";
}
?>
php/html
<div class="grid_4">
<div class="left-1">
<h2 class="top-1 p3">Find a property</h2>
<form id="form-1" method="post" class="form-1 bot-1" action="prop_result.php">
<div class="select-1">
<label>Select Area</label>
<select name="field4" id="field4" >
<?php
$rows = db_select("SELECT id,city_id,area FROM area");
if($rows === false) {
$error = db_error();
}else
{
while($rows=mysqli_fetch_assoc($result))
{
?>
<option value=""><?php $rows['
area'];?></option>
<?php
}}
?>
</select>
</div>
What I don't understand is how to use the stored procedure in a while loop so it will output the data in the fields ID and Area so my select box and any other input can be properly populated based on the query
current
I've tried different ways :
<?php
$rows = db_select("SELECT id,city_id,area FROM area");
if($rows === false) {
$error = db_error();
}
while($rows=mysqli_fetch_assoc($result))
{
?>
<option value=""><?php $rows['
area'];?></option>
<?php
}
?>
and
$rows = db_select("SELECT id,city_id,area FROM area");
if($rows === false) {
$error = db_error();
}
{
?>
<option value=""><?php $rows['
area'];?></option>
<?php
}
?>
and
<?php
$rows = db_select("SELECT area_id from property");
if($rows === false) {
$error = db_error();
}
{
echo "<option value='".$rows['id']."'>".$rows[$col4]."</option>";
}
?>
None of these output any data. Echoing $rows gives no data. I don't know what the logic is for using the stored procedure to display the output.
Any help would be appreciated, if any other information is required to assist in resolving this issue, please let me know.
Awesome to hear that the data is returning. Try this out for size...
foreach($rows as $key => $value){
foreach($value as $k => $v){
if($k == 'id'){
$newID = $v;
}
if($k == 'type'){
$newType = $v
}
}
echo "<option value='".$newID."'>".$newType."</option>";
}
with this you should be able to make it work for you liking.
Edit: Didnt see the additional arrays until later...the nested loop should suite you better.
Siniseus way works but its too much code for a simple task. I did work with it to finally come to this
<select name="field4" id="field4" >
<?php
$rows = db_select("SELECT id, city_id,area FROM area");
foreach($rows as $row){
echo "<option value='".$row['id']."'>".$row['area']."</option>";
}
?>
</select>
Simple, clean and really straight forward without too many variables.
$rows = db_select ("Select Query")foreach($rows as $row){
do this
}