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......
Related
I am trying to display some values using MQTT on a PHP based page. The PHP code contains the subscriber. I am using Bluemix IoT service for the MQTT broker. Also, the messages are published via Python code on local machine.
When I try to display values on pages using page refresh, the page sometimes fails to display the values. There is no problem at the publisher end as the values are successfully displayed by Bluemix IoT service.
My code is as follows:
<?php
// include class
require('phpMQTT.php');
// set configuration values
if( getenv("VCAP_SERVICES") ) {
// get MySQL service configuration from Bluemix
$services = getenv("VCAP_SERVICES");
$services_json = json_decode($services, true);
$mysql_config = $services_json["iotf-service"][0]["credentials"];
$org_id = $mysql_config["org"];
$port = $mysql_config["mqtt_u_port"];
$username = $mysql_config["apiKey"];
$password = $mysql_config["apiToken"];
}
// set configuration values
$config = array(
'org_id' => $org_id,
'port' => $port,
'app_id' => 'm',
'iotf_api_key' => $username,
'iotf_api_secret' => $password,
'device_id' => 'trial',
'qos' => 1
);
global $Val_A;
global $Val_B;
global $Val_C;
global $Val_D;
//Read already existing file
$ini_b = parse_ini_file("data.ini",true);
$Val_A = $ini_b['Data']['A'];
$Val_B = $ini_b['Data']['B'];
$Val_C = $ini_b['Data']['C'];
$Val_D = $ini_b['Data']['D'];
$config['server'] = $config['org_id'] . '.messaging.internetofthings.ibmcloud.com';
$config['client_id'] = 'a:' . $config['org_id'] . ':' . $config['app_id'];
#echo $config['client_id'];
// initialize client
$mqtt_dev = new phpMQTT($config['server'], $config['port'], $config['client_id']);
$mqtt_dev->debug = false;
// connect to broker
if(!$mqtt_dev->connect(true, null, $config['iotf_api_key'], $config['iotf_api_secret'])){
echo 'ERROR: Could not connect to IoT cloud';
exit();
}
else
{
#echo "Success";
}
$topics['iot-2/type/newdevice/id/' . $config['device_id'] . '/evt/status/fmt/json'] =
array('qos' =>1, 'function' => 'getLocation');
$mqtt_dev->subscribe($topics, 1);
$elapsedSeconds = 0;
while ($mqtt_dev->proc(true)) {
#echo json_encode($json);
if (count($location) == 2) {
break;
}
if ($elapsedSeconds == 5) {
break;
}
$elapsedSeconds++;
sleep(1);
}
// disconnect
//I have tried commenting this too
$mqtt_dev->close();
function getLocation($topic, $msg) {
global $location;
global $json;
$json = json_decode($msg);
$Val_A = $json->A;
$Val_B = $json->B;
$Val_C = $json->C;
$Val_D = $json->D;
//Read already existing file
$ini_backup = parse_ini_file("data.ini",true);
$ValA_b = $ini_backup['Data']['A'];
$ValB_b = $ini_backup['Data']['B'];
$ValC_b = $ini_backup['Data']['C'];
$ValD_b = $ini_backup['Data']['D'];
if($Val_A != 0)
{
$ValA_b = $Val_A;
}
else
{
$Val_A = $ValA_b;
}
if($Val_B != 0)
{
$ValB_b = $Val_B;
}
else
{
$Val_B = $ValB_b;
}
if($Val_C != 0)
{
$ValC_b = $Val_C;
}
else
{
$Val_C = $ValC_b;
}
if($Val_D != 0)
{
$ValD_b = $Val_D;
}
else
{
$Val_D = $ValD_b;
}
$file = fopen("data.ini","w");
fwrite($file,"[Data]". "\n" );
fwrite($file,"A =" . $ValA_b . "\n" );
fwrite($file,"B =" . $ValB_b . "\n" );
fwrite($file,"C =" . $ValC_b . "\n" );
fwrite($file,"D =" . $ValD_b . "\n" );
fclose($file);
return $location;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="refresh" content="5" >
<div id="footer">
This page will automatically reload every 5 seconds. <br/>
</div>
<label for="A">A</label>
<input type="text" value="<?php echo $Val_A ?>" />
<label for="B">B</label>
<input type="text" value="<?php echo $Val_B ?>" />
<label for="C">C</label>
<input type="text" value="<?php echo $Val_C ?>" />
<label for="D">D</label>
<input type="text" value="<?php echo $Val_D ?>" />
</body>
</html>
Can some one guide where am I going wrong?
Rather than using meta to specify the refresh, try using php header("Refresh:5");
There is an old stack overflow thread discussing using meta versus header for refrseh in php.
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>";
}
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
I have one little problem with checkboxes in yii. I have modal popup, where i have form for update.
Here is my controller:
public function actionUpdateroomrow(){
$model = Rooms::findOne($_POST['id']);
$model -> room_number_of_people = $_POST['room_number_of_people'];
$model -> room_name = $_POST['room_name'];
if(isset($_POST['room_air_conditioning']))
$model -> room_air_conditioning = $_POST['room_air_conditioning'];
else $model -> room_air_conditioning = false;
$model->update();
if (isset ($_POST['room_multimedia_id'])){
foreach($_POST['room_multimedia_id'] as $key => $value){
$model2 = RoomMultimediaData::findOne($value);
$model2 -> room_multimedia_data_value = $key;
var_dump($model2 -> errors);
}
}
$this->redirect('index');
}
Where is problem? In this row.
<div class="form-group">
<?php foreach($room_multimedia as $rm){ ?>
<label><?= $rm->room_multimedia_title ?></label><input type="checkbox" name="room_multimedia_id[<?= $rm->Checkmultimediadata($room->room_id,$rm->room_multimedia_id)->room_multimedia_data_id ?>]" value="<?= $rm->room_multimedia_id ?>"/>
<?php } ?>
</div>
This is row from update formular and im not really sure, where i failed.
In RoomMultimedia.php, modul i have this:
public function Checkmultimediadata($room_id,$room_multimedia){
return RoomMultimediaData::find()->where('room_id='.$room_id.' and room_multimedia_id='.$room_multimedia.'')->one();
}
Warning from yii:
PHP Warning – yii\base\ErrorException
Creating default object from empty value
$model2 -> room_multimedia_data_value = $key;
Can you help me solve this?
Thank you all! :)
Is it possible to get data from file then add it in my database in mysql. I'm using codeigniter. My code only asks inputs from the user. Please help please. It is required by my professor so that if the user wants to input for example 100 data he/she doesn't manually input the data thus get the data from another database.
my view page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Students</title>
</head>
<body>
<div id="container">
<h1>Student's Page</h1>
<div id="body">
<div id="div2">
<?php
echo form_open('main/addToRegistrar');
?>
<br>
<?php
echo "<p>ID: ";
echo form_input('id');
echo "</p>";
echo "<p>First Name: ";
echo form_input('first_name');
echo "</p>";
echo "<p>Middle Name: ";
echo form_input('middle_name');
echo "</p>";
echo "<p>Last Name: ";
echo form_input('last_name');
echo "</p>";
echo "<p>";
echo form_submit('ADD', 'ADD');
echo "<p>";
echo form_close();
?>
<a href='<?php echo base_url()."main/admin"; ?>'>Home!</a>
</div>
</div>
<p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds </p>
</div>
</body>
</html>
my controller
public function addToRegistrar(){
if($this->session->userdata('is_logged_in')){
$this->load->model('model_users');
$this->model_users->addToRegistrar();
$this->load->view('view_addAteneoStudents');
} else{
redirect('main/restricted');
}
}
my model
public function addToRegistrar(){
$fname = $this->input->post('first_name');
$mname = $this->input->post('middle_name');
$lname = $this->input->post('last_name');
$id = $this->input->post('id');
$data = array(
'id' => $id,
'first_name' => $fname ,
'middle_name' => $mname ,
'last_name' => $lname
);
if($this->db->insert('registrar', $data)){
echo "Successfully added";
}
}
You must have an option to upload files (csv recommended) and upload it to your server. Here is a quick how:
view:
<html>
<body>
<form action="<?php echo base_url();?>" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
controller:
public function addToRegistrar()
{
if($this->session->userdata('is_logged_in')){
$this->load->model('model_users');
$this->model_users->addToRegistrar();
$this->load->view('view_addAteneoStudents');
} else{
redirect('main/restricted');
}
}
model:
function addToRegistrar()
{
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
$filename = "upload/" . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $filename);
//parse the uploaded file and insert to database
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = $row;
}
$this->db->insert_batch('registrar', $data);
fclose($handle);
}
}
}
}
NOTE: Your csv file should have the same column count as your database table 'registrar'.
More about reading csv files here.