I'm using Laravel 5. I wanted to list all the database names in
dropdown, but I always end up fetching the last value. I already use
foreach loop, still nothing happens. Here's my code:
public function create(Request $request)
{
//echo "<pre>";
$sqlconn = mysqli_connect('127.0.0.1', 'root', '1234');
$showdb = "SHOW DATABASES";
$dbconn = mysqli_query($sqlconn, $showdb);
$dbnames = array();
while ($row=mysqli_fetch_assoc($dbconn)) {
$dbnames = $row;
foreach ($dbnames as $dbname => $value) {
if ($value != "information_schema" && $value != "performance_schema" && $value != "test" && $value != "mysql") {
//$dblists = implode(":", array($value));
$dblists = $value;
//print_r($dblists);
}
}
}
//die();
}
And here's my html codes:
<div class="col-md-12">
<div class="form-group #if($errors->has('description')) has-error #endif">
<div class="col-xs-2">
<label for="reports_description" class="control-label"><h5><b>Select Database:</b></h5></label>
</div>
<div class="col-xs-5">
<select class="form-control">
<option>---SELECT---</option>
<option value="{{$dblists}}">{{$dblists}}</option>
</select>
</div>
</div>
</div>
Controller:
public function create(Request $request) {
$databases = \DB::select('show databases');
return view('view.name', compact('databases'));
}
View:
#foreach($databases as $database)
<p>{{ $database->Database }}<p>
#endforeach
Related
In my document archive system, have an edit view that should allow a user to edit certain data about the file they uploaded and even re-upload a file if need be. For some reason the edit view is not opening because it is says the variable am stating in the form is undefined.
I have tried changing the form details but nothing is working.
This is the edit.blade.php
<h3 class="box-title"><i class="fa fa-edit"></i> Edit Document</h3>
</div><!-- /.box-header -->
<div class="box-body">
{!! Form::open(['action' => ['DocumentsController#update', $doc->id],
'method' => 'PUT', 'enctype' => 'multipart/form-data']) !!}
{{ csrf_field() }}
<div class="form-group">
<label for="student_id">Student ID</label>
<select class="form-control" name="student_id">
#foreach($students as $student)
<option value="{{ $student->$id }}">{{ $student->$id }}
</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="category_id">Category</label>
<select class="form-control" name="category_id">
#foreach($categories as $category)
<option value="{{ $category->$id }}">{{ $category->name }}
</option>
#endforeach
</select>
</div>
This is the update funtion in the documents controller
public function update(Request $request, $id)
{
$this->validate($request, [
'file' => 'nullable|max:1999|unique:documents',
'category_id' => 'nullable|integer',
]);
$doc = Document::findOrFail($id);
$doc->category_id = $request->input('category_id');
//$doc->file = $path;
$doc->mimetype = Storage::mimeType($path);
$size = Storage::size($path);
if ($size >= 1000000) {
$doc->filesize = round($size/1000000) . 'MB';
}elseif ($size >= 1000) {
$doc->filesize = round($size/1000) . 'KB';
}else {
$doc->filesize = $size;
}
// determine whether it expires
if ($request->input('isExpire') == true) {
$doc->isExpire = false;
$doc->expires_at = null;
}else {
$doc->isExpire = true;
$doc->expires_at = $request->input('expires_at');
}
if($request->hasFile('file'))
{
// filename with extension
$fileNameWithExt = $request->file('file')
>getClientOriginalName();
// filename
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
// extension
$extension = $request->file('file')-
>getClientOriginalExtension();
// filename to store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
// upload file
$path = $request->file('file')->storeAs('public/uploaded
files/'.$user_id, $fileNameToStore);
Storage::delete('public/uploaded files/'. $doc->file);
$doc->file = $path;
}
$doc->save();
return redirect('documents')->with('flash_message','Successfully
Updated!');
Edit function in Controller
public function edit($id)
{
$doc = Document::findOrFail($id);
$categories = Category::all();
$cate = array();
foreach($categories as $category)
{
$cate[$category->id] = $category->name;
}
return view('documents.edit')->withDocuments($doc)->withCategories($cate);
//compact('doc','categories'));
}
this is the error
Undefined variable: doc (View:
C:\xampp\htdocs\unzadms\resources\views\documents\edit.blade.php)
I expect to be able edit the necessary file details.
Seens like $doc is undefined as it says, you should make sure you are using the $doc variable on the edit.blade.php file, especific on the controler that handles the display.
You should post that controller if you still need help.
Update: Take a look on the documentation:
https://laravel.com/docs/5.4/views#passing-data-to-views
Solution:
return view('documents.edit', ['doc' => $doc,'categories' => $cate]);
I used a drop down button to select an option from the given options. But when I selected an option it does not display that in the box. And I it gives chance only once to select an option. For the drop down I retrieve data from the database.
This is the view code (Its inside Assign_Inquiries)
<select id = "counsellorname" name="counsellornamename" class="btn btn-default dropdown-toggle">
<option value = "0"> Select Category Name</option>
<?php
foreach($result as $row){
echo "<option value = ".$row['email'].">".$row['fname']." ".$row['lname']."</option>";
}
?>
</select>
Its really great if someone can help me. Thanks inadvance
This is the controller code
<?php
class Assign_Inquiries_Controller extends CI_Controller{
function index(){
$this->load->model('Assign_Inquiries_Model');
$data['result'] = $this->Assign_Inquiries_Model->index();
//print_r($data);
$this->load->view('Assign_Inquiries',$data);
}
}
?>
This is the model code
<?php
class Assign_Inquiries_Model extends CI_Model{
function index(){
$this->db->select('first_name,last_name,email');
$where = "status =3";
$this->db->where($where);
$query = $this->db->get('user');
foreach ($query -> result() as $row) {
$data[] = array(
'fname' => $row->first_name,
'lname' => $row->last_name,
'email' => $row->email
);
}
return $data;
}
}
?>
Change your model code as below: use result_array() which returns the result in array format.
function index(){
$this->db->select('first_name,last_name,email');
$this->db->where('status',3);
$query = $this->db->get('user');
return $query ->result_array();
}
In view you loop must be like this....
foreach($result as $row){
echo "<option value = ".$row['email'].">".$row['first_name']." ".$row['last_name']."</option>";
}
How can i upload csv file and save data in to my mysql database.
according to id.in cakephp 3
i am unable to do that. can any one help me.
my controller
public function import() {
if(isset($_POST["submit"])){
if($_FILES['file']['csv']){
$filename = explode('.', $_FILES['file']['csv']);
debug($filename);
if($filename[1]=='csv'){
$handle = fopen($_FILES['file']['csv'], "r");
while ($data = fgetcsv($handle)){
$item1 = $data[0];
// $item2 = $data[1];
// $item3 = $data[2];
// $item4 = $data[3];
$Applicants = $this->Applicants->patchEntity($Applicants, $item1);
$this->Applicants->save($Applicants);
}
fclose($handle);
}
}
}
$this->render(FALSE);
}
my view:
<div class="col-md-8">
<?= $this->Form->create('Applicants',['type' => 'file','url' => ['controller'=>'Applicants','action' => 'import'],'class'=>'form-inline','role'=>'form',]) ?>
<div class="form-group">
<label class="sr-only" for="csv"> CSV </label>
<?php echo $this->Form->input('csv', ['type'=>'file','class' => 'form-control', 'label' => false, 'placeholder' => 'csv upload',]); ?>
</div>
<button type="submit" class="btn btn-default"> Upload </button>
<?= $this->Form->end() ?>
</div>
Your question is a bit unclear what do you want to do in the controller do you want to update the existing records or save new data. If you want to update then only you need to use patchEntity.
The patchEntity should have a database entity fetched where in you can change or update the data as per your need, so in case if your first column contains the id of the Applications table then below code can work and in $data you can write whatever fields you want to update or add
So you can use the below code block instead
public function import() {
if(isset($_POST["submit"])){
if($_FILES['file']['csv']){
$filename = explode('.', $_FILES['file']['csv']);
debug($filename);
if($filename[1]=='csv'){
$handle = fopen($_FILES['file']['csv'], "r");
while ($data = fgetcsv($handle)){
$item1 = $data[0];
$data = array(
'fieldName' => $item1
);
// $item2 = $data[1];
// $item3 = $data[2];
// $item4 = $data[3];
$Applicant = $this->Applicants->newEntity($data);
$this->Applicants->save($Applicant);
}
fclose($handle);
}
}
}
$this->render(FALSE);
}
If you have more specific code/requirement then please share, so that I can help you out accordingly.
Here is my Solution to upload csv file and save database
public function import($id = NULL) {
$data = $this->request->data['csv'];
$file = $data['tmp_name'];
$handle = fopen($file, "r");
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($row[0] == 'id') {
continue;
}
$Applicants = $this->Applicants->get($row[0]);
$columns = [
'written_mark' => $row[1],
'written_comments' => $row[2],
'viva_mark' => $row[3],
'viva_comments' => $row[4]
];
$Applicant = $this->Applicants->patchEntity($Applicants, $columns);
$this->Applicants->save($Applicant);
}
fclose($handle);
$this->set('title','Upload Student CSV File Input Number and others');
return $this->redirect($this->referer());
}
I have around 700 product list in my Databse table.
I am using bootstrap's tokenfield for auotcomplete, i have to use auto complete in search textbox.
I am getting syntax error :
SyntaxError: missing ] after element list
...B','Lino Perros Men's Leather Wallet - Pink','Lenovo A269i','Lenovo S660 - Tita**
in console.
<?php $t = $this->general_model->auto_complete_sug(); ?>
$( document ).ready(function() {
$('#tokenfield-2').tokenfield({
autocomplete: {
source: <?=$t?>,
delay : 100
},
limit: 1,
minLength: 1,
showAutocompleteOnFocus: true
});
});
<input type="text" class="span2" name="search" id="tokenfield-2" placeholder="Search...">
In my model: I have created this functions:
public function auto_complete_sug()
{
$data = $this->auto_complete_token_fun();
$data1 = explode(',', $data);
$data1 = array_unique($data1);
foreach ($data1 as $value1) {
$temparr[] = $value1;
}
$str = '[';
$c = count($temparr);
$counter = 0;
foreach ($temparr as $val) {
$counter++;
$str .= "'".$val."'";
if($counter < $c){
$str .= ",";
}
}
$str .= ']';
return $str;
}
public function auto_complete_token_fun()
{
// $this->db->query("SET GLOBAL group_concat_max_len = 10000000");
$q = $this->db->query("SELECT GROUP_CONCAT( sub_category_name ) AS scname
FROM `tbl_subcategory` WHERE status = 'Active' ");
if($q->num_rows() > 0)
{
$d = $q->row_array();
return $d['scname'];
}
else
{
return '';
}
}
Please help!!
I use CodeIgniter 2.1.3, PHP and MySQL.
Hello, I want to display data from database. Always I display by foreach($results as $data), but now I want do display all data in few step. Display first record and when user click next then display next row from database. I now that I must use mysql_fetch_row() but I don't know how I can do it...
This is my model:
public function play($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get("quiz");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
controler:
public function index()
{
$config = array();
$config["base_url"] = base_url() . "index.php/main_menu/Quiz/index";
$config["total_rows"] = $this->quiz_model->record_count();
$config["per_page"] = 11;
$config["uri_segment"] = 4;
$this->pagination->initialize($config);
$page = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
$data["results"] = $this->quiz_model->play($config["per_page"], $page);
$data["links"] = $this->pagination->create_links();
$this->load->view('left_column/quiz_open', $data);
}
Pagination is not important.
and view:
<form>
<?php
if (empty($results)) {
}
else {
foreach($results as $data) { ?>
<label style='width:450px;'> <b>   <?php echo $data->pytanie?> </b> </label>
<label style='width:300px;'> <input type="radio" name="Wiek" value=<?php echo $data->odp1 ?> /> <?php echo $data->odp1 ?> </label>
<label style='width:300px;'> <input type="radio" name="Wiek" value=<?php echo $data->odp2 ?> /> <?php echo $data->odp2 ?> </label>
<label style='width:300px;'> <input type="radio" name="Wiek" value=<?php echo $data->odp3 ?> /> <?php echo $data->odp3 ?> </label>
<?php }
}?>
<label style='width:300px;'> <input type="submit" name="Wyslij" id="Wyslij" value="  WyĆlij  "/> </label>
</form>
There is an inbuilt Pagination class provided by codeIgniter. You can find it in user guide.
Define a start index variable in the function where u want to use pagination as zero.
public function pagination($start_index = 0)
{
$result = $this->model->get_results($data); //this $data is the argument which you are passing to your model function. If you are using database to get results array.
$items_per_page = 10; //this is constant variable which you need to define
$filtered_result = array_splice($result, $start_index, ITEM_PER_PAGE_USERS);
$model['$filtered_result'] = $filtered_result;
$total_rows = count($result);
$model['page_links'] = create_page_links (base_url()."/controlelr_name/pagination",ITEM_PER_PAGE_USERS, $total_rows);
$this->load->view('controller_name/view_file_name', $model);
}
This is a generalised function for pagination. You can keep this function in one helper file where you keep all generalised functions.
function create_page_links($base_url, $per_page, $total_rows)
{
$CI = & get_instance();
$CI->load->library('pagination');
$config['base_url'] = $base_url;
$config['total_rows'] = $total_rows;
$config['per_page'] = $per_page;
$CI->pagination->initialize($config);
return $CI->pagination->create_links();
}
This create page links function is a generic function.............for more explanation check pagination class from user guide......