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.
Related
Following code in SiteController works fine with echo, but not with yii-method setflash(). Maybe, I have to reconfigure my config-file(main-local.php)?
Any other ideas how to keep setflash() doing its job?
public function actionScript() { //A new method, programmed by Thomas Kipp
$model = new myScriptForm();
$fileName = 'file';
$uploadPath = Yii::getAlias('#uploading');
if (isset($_FILES[$fileName])) {
$file = \yii\web\UploadedFile::getInstanceByName($fileName);
if ($file->saveAs($uploadPath . '/' . $file->name)) {
echo"<script>alert('Hallo');</script>";
//echo \yii\helpers\Json::encode($file);
}
}
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->fileImage = UploadedFile::getInstance($model, 'fileImage');
$model->avatar = UploadedFile::getInstances($model, 'avatar');
if ($model->fileImage) {
Yii::$app->session->setFlash('success', 'File has been uploaded');
echo "<font size='4'><br><br><br><center>File <font color='red'> "
. "$model->fileImage<font color='black'> successfully uploaded."
. "<br>It's available in folder 'uploadedfiles' </font></font color></center>";
$model->fileImage->saveAs(Yii::getAlias('#uploadedfilesdir/' . $model->fileImage->baseName . '.' . $model->fileImage->extension));
} else {
Yii::$app->session->setFlash('error', 'There has nothing to be uploaded');
echo"<font size='4'><br><br><br><center>No Upload-file selected.<br>"
. "Nothing moved into folder 'uploadedfiles'</font></center>";
}
if ($model->avatar) {
$counter = 0;
foreach ($model->avatar as $avatar) {
Yii::$app->session->setFlash('success', 'Avatar has been uploaded');
echo "<font size='4'><br><center>File <font color='red'> "
. "$avatar<font color='black'> successfully uploaded."
. "<br>It's available in folder 'uploadedfiles' </font></font color></center>";
$avatar->saveAs(Yii::getAlias('#uploadedfilesdir/' . $avatar->baseName . $counter . '.' . $avatar->extension));
$counter++;
}
} else {
Yii::$app->session->setFlash('error', 'There has nothing to be uploaded');
echo"<font size='4'><br><center>No Upload-file selected.<br>"
. "Nothing moved into folder 'uploadedfiles' </font></center>";
}
return $this->render('myScript', ['model' => $model]);
} else {
return $this->render('myScript_Formular', ['model' => $model]);
}
}
once you have assign the value with eg:
Yii::$app->session->setFlash('error', 'There has nothing to be uploaded');
be sure that in your view eg: myScript.php
you properly echo the value setted
<?= Yii::$app->session->getFlash('error'); ?>
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.
<?php function getCurrencyFor($arr, $findCountry) {
foreach($arr as $country) {
if ($country->name->common == $findCountry) {
$currency = $country->currency[0];
$capital = $country->capital;
$region = $country->region;
break;
}
}
return $country();
}
$json = file_get_contents("https://raw.githubusercontent.com/mledoze/countries/master/countries.json");
$arr = json_decode($json);
// Call our function to extract the currency for Angola:
$currency = getCurrencyFor($arr, "Aruba");
echo $country('$capital');
echo $country('$currency');
echo $country('$region');
?>
I followed this post - https://stackoverflow.com/a/38906191/3939981
If I rewrite the code inside function, it works
<?php function getCurrencyFor($arr, $findCountry) {
foreach($arr as $country) {
if ($country->name->common == $findCountry) {
$currency = $country->currency[0];
$capital = $country->capital;
$region = $country->region;
echo $capital;
echo $currency;
echo $region;
break;
}
}
return $currency;
}
$json = file_get_contents("https://raw.githubusercontent.com/mledoze/countries/master/countries.json");
$arr = json_decode($json);
// Call our function to extract the currency for Angola:
$currency = getCurrencyFor($arr, "Aruba");
?>
Maybe some parts of the code did not work..Any comments and thoughs
You could use this code. Note that if you want a function to return three values, you should create an array with those values, and return that array. I also renamed the function, since it does not only return currency information:
function getCountryInfo($arr, $findCountry) {
foreach($arr as $country) {
if ($country->name->common == $findCountry) {
return array(
"currency" => $country->currency[0],
"capital" => $country->capital,
"region" => $country->region
);
}
}
}
$json = file_get_contents("https://raw.githubusercontent.com/mledoze/countries/master/countries.json");
$arr = json_decode($json);
// Call our function to extract the currency for Angola:
$country = getCountryInfo($arr, "Aruba");
echo $country['capital'] . "<br>";
echo $country['currency'] . "<br>";
echo $country['region'] . "<br>";
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......
I have the following jquery ajax request
$(document).ready(function(){
var friendrequest = $(".friendrequest").val();
$(".afriendreq").click(function(){
$(".afriendreq").hide();
$.ajax({ type: "POST", url:"functions/ajaxfriends.php", data:"friendrequest" ,success:function(result){
$(".cfriendreq").show();
}});
});
});
And it gets the input from here
while ($row = mysql_fetch_array($search)) {
d
?>
<div id="search_container">
<div id="search_image"><img src="<?php echo $row['picture'] ?>"></img></div>
<input type="hidden" value="<?php echo $row['id'] ?>" id="friendrequest" ></input>
<div id="search_name"> <?php echo $row['first_name'] . " " . $row['last_name']; ?> </div>
<div id="search_friend"><a class="afriendreq">Send Friend Request</a><a class="cfriendreq" style="display:none;">Cancel Friend Request</div>
</div><?php
echo "<br />";
}
?>
Unfortunately it's not working though. Can anyone find the problem because it's bugging me?
Also the functions/ajaxfriends.php is
<?php
include 'functions.php';
if (isset($_POST['friendrequest'])){
$friendrequest= $_POST['friendrequest'];
$friendrequest= filter ($_POST['friendrequest']);
$sql_connectfriend = " INSERT INTO friends (`useridone` ,`useridtwo` ,`request`) VALUES ('$_SESSION[user_id]', '$friendrequest', '1' ";
$search = mysql_query($sql_connectfriend, $link) or die("Insertion Failed:" . mysql_error());
}
?>
Can anyone see why?
Thanks in advance.
Try:
$.ajax({
url: 'functions/ajaxfriends.php',
type: 'POST',
data: { friendrequest: friendrequest },
success: function(result) {
$('.cfriendreq').show();
}
});