So in my platform i have a functionality which reads email, first name and last name from a csv file and then save them in database on to an array. All is working fine in my computers, but however in 2 of my co workers pc the list is returning 0 elements and it has 37, however running it in multiple browsers on my 2 computers it works perfectly fine. We are all using the same list to test.
<form action="" method="POST" enctype="multipart/form-data">
<label>Nome da lista:</label>
<input class="form-control" typr="text" name="nome" placeholder="Nome" /></br>
<label>Lista (Ficheiro CSV):</label>
<input type="file" name="file" id="file">
<button type="submit" id="enviar" name="submit" style="max-width:100px; background: #ed1a3d; margin-top:10px;" class="btn btn-primary btn-lg btn-block btn-icon-split">
Criar
</button>
</form>
<?php
global $user;
if(isset($_POST['submit'])) {
if ($_FILES['file']['tmp_name']) {
$nome = $_POST['nome'];
$file = $_FILES['file']['tmp_name'];
$user->criarLista($nome, $file);
} else {
$user->mensagem(1, "Não existe nenhum ficheiro");
}
}
?>
And this is the criarLista function (Which means create list ):
public function criarLista($nome,$file){
$user = $this->user;
$get = $this->connect->query("SELECT * FROM users WHERE email = '$user'");
$fetch = $get->fetch_array(MYSQLI_ASSOC);
$user_id = $fetch['id'];
if($insert = $this->connect->prepare("INSERT INTO lista(user_id,nome) VALUES(?,?)")){
$insert->bind_param("is", $user_id,$nome);
$insert->execute();
$list_id = $insert->insert_id;
$file = preg_replace('#\\x1b[[][^A-Za-z]*[A-Za-z]#', '', $file);
$file = strip_tags($file);
$lines = file($file);
$emails = array();
$fnames = array();
$lnames = array();
$linha = 0;
foreach($lines as $line) {
if($linha == 0){
}else{
if (strpos($line, ',') !== false) {
$arr = explode(",", $line);
// Email \ FNAME | LAST
$emailx = trim($arr[0]);
$emailx = trim(preg_replace("/[\\n\\r]+/", "", $emailx));
array_push($emails,$emailx);
if(isset($arr[1])){
$fname = trim($arr[1]);
$fname = str_replace('"','',$fname);
array_push($fnames,$fname);
}
if(isset($arr[2])){
$lname = trim($arr[2]);
array_push($lnames,$lname);
}
}else{
array_push($emails,trim($line));
}
}
$linha++;
}
array_map('trim', $emails);
array_map('trim', $fnames);
array_map('trim', $lnames);
$emails = implode(",",$emails);
$fnames = implode(",",$fnames);
$lnames = implode(",",$lnames);
if($insert_list = $this->connect->prepare("INSERT INTO listas(lista_id,email,primeiro_nome,ultimo_nome) VALUES(?,?,?,?)")){
$insert_list->bind_param("isss", $list_id,$emails,$fnames,$lnames);
$insert_list->execute();
$this->mensagem(2,"Lista adicionada com sucesso");
}else{
echo
'
<div class="alert alert-danger">
Erro: '.$this->connect->error.'
</div>
';
}
}else{
echo
'
<div class="alert alert-danger">
Erro: '.$this->connect->error.'
</div>
';
}
}
Is there anything that may create this incompability between some computers?
Related
We are creating a function that exports data from a table to a CSV. However, the code seems to redirect to a blank page. I'm not certain what's going on as I have checked the database and table connections. I could be missing something simple, but staring at the code over and over is making it hard to figure out what's wrong.
<?php
require_once('connection.php');
session_start();
if (!$_SESSION['user']) {
header("Location: index.php"); // If session is not set that redirect to Login Page
}
//set successful imported rows count to 0
$successCount = 0;
if(isset($_POST['submit'])){
$skip = mysqli_real_escape_string($csvDatabase, $_POST['header']);
$colNumber = mysqli_real_escape_string($csvDatabase, $_POST['SUIDnumber']);
$colNumber = $colNumber - 1;
$filename = $_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0) {
for($i=0; $i<count($filename); $i++) {
$file = $filename[$i];
//open file in read only
$files = fopen($file, "r");
//skips first line
fgets($files);
//get data from csv & uses comma to find separate values
while (($getData = fgetcsv($files, 0, ",")) !== FALSE)
{
$fail = FALSE;
//store SUID from 2nd line in csv
$suid = $getData[$colNumber];
if (strlen($suid) === 9 && ctype_digit($suid) ) {
// start ldap look up
$basedn="***";
//Connect to server
$ds=ldap_connect("***");
if ($ds) {
//bind with our special account that retrieves more attributes
$ldaprdn = '***'; // ldap rdn or dn
$ldappass = '***'; // associated password
$r=ldap_bind($ds,$ldaprdn,$ldappass); // this is an authenticated bind
if (substr($suid, 0, 1) === ";" || is_numeric($suid)) {
if ($r) {
//filter to all objectclasses that the SUID we are looking for
$filter = "(&(objectClass=*)(syrEduSUID={$suid}))";
//We are only interested in retrieving these attributes
$justthese = array("displayName", "syrEduLevel", "syrEduProgramDesc", "syrEduProgram", "mail", "eduPersonPrimaryAffiliation", "eduPersonAffiliation" , "uid");
// Search SUID
$sr=ldap_search($ds, $basedn, $filter, $justthese );
//Need to test if the search succeeded. FALSE value means it failed
//if ($sr!==FALSE) {
//Search found something. Now return Attributes and their values - note, there can be multiple values per attribute. We need to make sure the search only returned one result
$entry = ldap_get_entries($ds, $sr);
// if we have only one result, return the values, if not, we have a problem
if ($entry["count"] == 1) {
// get student name and email from suid
$studentName = mysqli_real_escape_string($csvDatabase, $entry[0]['displayname'][0]);
$studentEmail = mysqli_real_escape_string($csvDatabase, $entry[0]['mail'][0]);
$studentAffiliation = mysqli_real_escape_string($csvDatabase, $entry[0]['edupersonprimaryaffiliation'][0]);
$studentProgram = mysqli_real_escape_string($csvDatabase, $entry[0]['syreduprogramdesc'][0]);
$studentEduLevel = mysqli_real_escape_string($csvDatabase, $entry[0]['syredulevel'][0]);
$netID = mysqli_real_escape_string($csvDatabase, $entry[0]['uid'][0]);
$successCount++;
// close ldap
ldap_close($ds);
} else {
$msg = "Ldap search returned 0 or more than one result";
$fail = TRUE;
}
//} else {
// $msg = "Search failed";
// $fail = TRUE;
//}
}
} else {
$msg = "Bind failed";
$fail = TRUE;
}
} else {
$msg = "LDAP connection failed";
$fail = TRUE;
}
//split full name
$studentName = trim($studentName);
$last_name = (strpos($studentName, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $studentName);
$first_name = trim( preg_replace('#'.$last_name.'#', '', $studentName ) );
//inserts data into import table
$sql = "INSERT into import (suid, firstName, lastName, studentEmail, studentAffiliation, studentProgram, studentEduLevel. netID) values ('$suid', '$first_name', '$last_name', '$studentEmail', '$studentAffiliation', '$studentProgram', '$studentEduLevel', '$netID')";
if (!$fail) {
if (mysqli_query($csvDatabase, $sql)) {
//once imported properly, export csv
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($csvDatabase);
}
}
}
}
}
//closes file
fclose($files);
$query = "SELECT suid, firstName, lastName, studentEmail, studentAffiliation, studentProgram, studentEduLevel, netID from import ORDER BY id DESC LIMIT {$successCount}";
$result = mysqli_query($csvDatabase, $query);
if ($result->num_rows > 0) {
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data-export.csv');
$output = fopen("php://output", "w");
$headers = array('SUID', 'First Name', 'Last Name', 'Student Email', 'Student Affiliation', 'studentProgram', 'Student Edu Level', 'NetID');
fputcsv($output, $headers);
while($row = mysqli_fetch_assoc($result))
{
fputcsv($output, $row);
}
fclose($output);
//then delete records in database
$deletesql = "DELETE FROM import ORDER BY id DESC LIMIT {$successCount}";
if (mysqli_query($csvDatabase, $deletesql)) {
//echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($csvDatabase);
}
}
} else {
echo "You did not upload a CSV file or the CSV file is blank.";
}
} else {
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CSV Import</title>
<link rel="stylesheet" href="css/foundation.min.css" />
<link rel="stylesheet" href="css/app.css" />
</head>
<body>
<!-- nav -->
<div class="top-bar">
<div class="top-bar-left">
<ul class="menu">
</ul>
</div>
<div class="top-bar-right">
</div>
</div>
<div class="row" style="margin-top: 5%;">
<div class="medium-12 columns">
<h3>Import CSVs for Student Data</h3>
<div class="callout secondary">
<form name="upload_excel" method="post" enctype="multipart/form-data">
<fieldset class="large-4 cell">
<legend>Does the CSV have a header in the first row?</legend>
<input type="radio" name="header" value="yes" id="yesHeader"><label for="yesHeader">Yes</label>
<input type="radio" name="header" value="no" id="noHeader"><label for="noHeader">No</label>
</fieldset>
<label for="SUIDnumber">
What number column is the SUID field in?
<input type="number" value="" id="SUIDnumber" name="SUIDnumber" required>
</label>
<p>Upload your CSV(s) with SUIDs. You will then be prompted to download the exported data.</p>
<input type="file" id="files" name="file[]" accept=".csv" multiple><br>
<input type="submit" class="button" id="submit" name="submit" value="Import CSV">
</form>
</div>
</div>
</div>
<script src="js/vendor/jquery.min.js"></script>
<script src="js/vendor/what-input.min.js"></script>
<script src="js/foundation.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
<?php } ?>
Was able to find the solution by moving the export CSV function. Thank you all for your help.
We are creating a function that exports data from a table to a CSV then deletes the data from the table. We have created the ability for the user to select if there is a header in the first row of the CSV (yes or no radio buttons). However, when no is selected, the function only runs for the very first row but doesn't continue to loop the other rows. Any ideas on what is missing?
<?php
require_once('connection.php');
session_start();
if (!$_SESSION['user']) {
header("Location: index.php"); // If session is not set that redirect to Login Page
}
//set successful imported rows count to 0
$successCount = 0;
if(isset($_POST['submit'])){
$skip = mysqli_real_escape_string($csvDatabase, $_POST['header']);
$colNumber = mysqli_real_escape_string($csvDatabase, $_POST['SUIDnumber']);
$colNumber = $colNumber - 1;
//get filename
$filename = $_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0) {
for($i=0; $i<count($filename); $i++) {
$file = $filename[$i];
//open file in read only
$files = fopen($file, "r");
//skips first line
if ($skip === "yes") {
fgetcsv($files, 10000, ",");
}
//get data from csv & uses comma to find separate values
while (($getData = fgetcsv($files, 10000, ",")) !== FALSE)
{
$fail = FALSE;
//store SUID from pre-set line in csv
$suid = $getData[$colNumber];
if (strlen($suid) === 9 && ctype_digit($suid) ) {
// start ldap look up
$basedn="***";
//Connect to server
$ds=ldap_connect("***");
if ($ds) {
//bind with our special account that retrieves more attributes
$ldaprdn = '***'; // ldap rdn or dn
$ldappass = '**'; // associated password
$r=ldap_bind($ds,$ldaprdn,$ldappass); // this is an authenticated bind
if (substr($suid, 0, 1) === ";" || is_numeric($suid)) {
if ($r) {
//filter to all objectclasses that the SUID we are looking for
$filter = "(&(objectClass=*)(syrEduSUID={$suid}))";
//We are only interested in retrieving these attributes
$justthese = array("displayName", "syrEduLevel", "syrEduProgramDesc", "syrEduProgram", "mail", "eduPersonPrimaryAffiliation", "eduPersonAffiliation", "uid" );
// Search SUID
$sr=ldap_search($ds, $basedn, $filter, $justthese );
$entry = ldap_get_entries($ds, $sr);
// if we have only one result, return the values, if not, we have a problem
if ($entry["count"] == 1) {
// get student name and email from suid
$studentName = mysqli_real_escape_string($csvDatabase, $entry[0]['displayname'][0]);
$studentEmail = mysqli_real_escape_string($csvDatabase, $entry[0]['mail'][0]);
$studentAffiliation = mysqli_real_escape_string($csvDatabase, $entry[0]['edupersonprimaryaffiliation'][0]);
$studentProgram = mysqli_real_escape_string($csvDatabase, $entry[0]['syreduprogramdesc'][0]);
$studentEduLevel = mysqli_real_escape_string($csvDatabase, $entry[0]['syredulevel'][0]);
$netID = mysqli_real_escape_string($csvDatabase, $entry[0]['uid'][0]);
$successCount++;
// close ldap
ldap_close($ds);
} else {
$msg = "Ldap search returned 0 or more than one result";
$fail = TRUE;
}
}
} else {
$msg = "Bind failed";
$fail = TRUE;
}
} else {
$msg = "LDAP connection failed";
$fail = TRUE;
}
//split full name
$studentName = trim($studentName);
$last_name = (strpos($studentName, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $studentName);
$first_name = trim( preg_replace('#'.$last_name.'#', '', $studentName ) );
//inserts data into import table
$sql = "INSERT into import (suid, firstName, lastName, studentEmail, studentAffiliation, studentProgram, studentEduLevel, netID) values ('$suid', '$first_name', '$last_name', '$studentEmail', '$studentAffiliation', '$studentProgram', '$studentEduLevel', '$netID')";
if (!$fail) {
if (mysqli_query($csvDatabase, $sql)) {
//once imported properly, export csv
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($csvDatabase);
}
}
}
}
//closes file
fclose($files);
$query = "SELECT suid, firstName, lastName, studentEmail, studentAffiliation, studentProgram, studentEduLevel from import ORDER BY id ASC LIMIT {$successCount}";
$result = mysqli_query($csvDatabase, $query);
if ($result->num_rows > 0) {
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data-export.csv');
$output = fopen("php://output", "w");
$headers = array('SUID', 'First Name', 'Last Name', 'Student Email', 'Student Affiliation', 'studentProgram', 'Student Edu Level');
fputcsv($output, $headers);
while($row = mysqli_fetch_assoc($result))
{
fputcsv($output, $row);
}
fclose($output);
//then delete records in database
$deletesql = "DELETE FROM import ORDER BY id DESC LIMIT {$successCount}";
if (mysqli_query($csvDatabase, $deletesql)) {
//echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($csvDatabase);
}
}
}
} else {
echo "You did not upload a CSV file or the CSV file is blank.";
}
} else {
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CSV Import</title>
<link rel="stylesheet" href="css/foundation.min.css" />
<link rel="stylesheet" href="css/app.css" />
</head>
<body>
<!-- nav -->
<div class="top-bar">
<div class="top-bar-left">
<ul class="menu">
</ul>
</div>
<div class="top-bar-right">
</div>
</div>
<div class="row" style="margin-top: 5%;">
<div class="medium-12 columns">
<form name="upload_excel" method="post" enctype="multipart/form-data">
<h3>Import CSVs for Student Data</h3>
<div class="callout secondary">
<fieldset class="large-4 cell">
<legend>Does the CSV have a header in the first row?</legend>
<input type="radio" name="header" value="yes" id="yesHeader"><label for="yesHeader">Yes</label>
<input type="radio" name="header" value="no" id="noHeader"><label for="noHeader">No</label>
</fieldset>
<label for="SUIDnumber">
What number column is the SUID field in?
<input type="number" value="" id="SUIDnumber" name="SUIDnumber" required>
</label>
<p>Upload your CSV(s) with SUIDs. You will then be prompted to download the exported data.</p>
<input type="file" id="files" name="file[]" accept=".csv" multiple><br>
<input type="submit" class="button" id="submit" name="submit" value="Import CSV">
</div>
</form>
</div>
</div>
<script src="js/vendor/jquery.min.js"></script>
<script src="js/vendor/what-input.min.js"></script>
<script src="js/foundation.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
<?php } ?>
For my application, there are three levels of users:
top level (00)
mid "district" level
lower level
The interface built allows users to create messages that will be distributed to a mobile app.
I had it working fine, but was then later tasked to add the mid-level. Now, even though the messages appear to update properly, I am encountering an issue that, instead of displaying "Message Updated" and the form after a message is submitted, I am receiving the "You do not have permission to access this page" message.
This does NOT occur with the mid/district level, only the lower and upper levels. Some reason, for these two, it is not properly reading $_SESSION['store'] after the form is submitted (though it works as expected when the page is loaded normally, not via POST).
I would greatly appreciate any guidance:
<?php
session_start();
function format($input) {
$input = trim($input);
$input = stripcslashes($input);
$input = htmlspecialchars($input);
return $input;
}
$con = new PDO("sqlite:managers.db");
$store = $_SESSION['store'];
$stores;
$file;
$district;
$file = "messages/" . $store . ".txt";
if(!file_exists($file)) {
$temp = fopen($file, "w"); // create file
fclose($temp);
}
if(strpos("d", $store) == 0) {
$district = true;
$sql = "SELECT district FROM managers WHERE store = '$store'";
$statement = $con->query($sql);
$row = $statement->fetch();
$storesArray = explode(",", $row[0]);
}
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$newMessage = format($_POST['message']);
$writer = fopen($file, "w");
fwrite($writer, $newMessage);
fclose($writer);
if($district) {
foreach($storesArray as $store) {
$fileName = "messages/d" . $store . ".txt";
if(!file_exists($fileName)) {
$temp = fopen($fileName, "w"); // create file
fclose($temp);
}
$writer = fopen($fileName, "w");
fwrite($writer, $newMessage);
fclose($writer);
}
}
}
$handler = fopen($file, "r");
$currentMessage = fread($handler, filesize($file));
fclose($handler);
?>
// some code omitted //
<?php
if($store == "" || $store == null) {
echo "<p>You do not have permission to view this page</p>";
} else {
echo "<h2>Manage Messages"; if($store == "00") {
echo "<a href='admin.php'><input type='button' id='adminBack' value='Back' /></a></h2>";
} else {
echo "<a href='adminUI.php'><input type='button' id='adminBack' value='Back' /></a></h2>";
}
if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "<h2>Message Updated!</h2>";
}
echo "<form class='admin' class='col-md-6' method='post' action='manageMessages.php'>
<div class='form-group'>
<label for='message'> Message: </label>
<textarea class='form-control' id='message' name='message' >$currentMessage</textarea>
<input type='submit' value='Post Message' />
</div>
</form>";
}
?>
</div>
<!-- end page specific content -->
The login page that sets the session:
<?php
session_start();
function format($input) {
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input);
return $input;
};
$store; $pass; $valid;
echo "<script>function redirect() {
location.assign('manageMessages.php');
}
function adminRedirect() {
location.assign('admin.php');
}</script>";
if($_GET['logout']) {
session_unset();
session_destroy();
}
if($_SERVER['REQUEST_METHOD'] == "POST") {
if(!empty($_POST['store']) && !empty($_POST['pass'])) {
$store = format($_POST['store']);
$pass = format($_POST['pass']);
$con = new PDO("sqlite:managers.db");
$sql = "SELECT *FROM managers WHERE store = '$store' AND password = '$pass'";
$statement = $con->query($sql);
$rows = $statement->fetchAll();
$count = count($rows);
if($count != 1) {
$valid = false;
} else {
$valid = true;
}
}
else {
$valid = false;
}
}
?>
// excess code //
<?php
$location;
if($valid) {
$_SESSION['store'] = $store;
if($store == "00") {
echo "<script>setTimeout(adminRedirect(), 1);</script>";
} else {
echo "<script>setTimeout(redirect(), 1);</script>";
} } elseif ($valid === false) {
echo "<h3>Please enter a valid store/password combination!</h3>";
}
?>
<h2>Admin Login</h2>
<form class="admin" method="post" action="adminUI.php">
<div class="form-group">
<label for="store">Store Number: </label>
<input type="text" class="form-control" name="store" id="store" />
<label for="pass">Password:</label>
<input type="text" class="form-control" name="pass" id="pass" />
<input type="submit" value="Login" />
</div>
</form>
Your $store variable is being overwritten by your foreach:
foreach($storesArray as $store)
You must use a different name for that foreach, something like:
foreach($storesArray as $store2)
I am copying a youtube video tutorial for private messaging. The rest of the tutorial works fine, but as soon as I add this function to my site, my entire site goes blank and nothing is shown? No errors or anything, just a white screen? Have I done something wrong here? Here is the function:
<?php
function fetch_user_ids($usernames){
foreach ($usernames as &$name){
$name = mysql_real_escape_string($name);
}
$result = mysql_query("SELECT `userid`, `username` FROM `users` WHERE `username` IN ('" . implode("', '", $usernames) . "')");
$names = array();
while (($row = mysql_fetch_assoc($result)) !== false){
$names[$row['username']] = $row['userid'];
}
return $names;
}
?>
Here is the script to send the information:
<?php
if (isset($_POST['to'], $_POST['subject'], $_POST['body'])){
$errors = array();
if (empty($_POST['to'])){
$errors[] = 'You must enter atleast one name.';
}else if (preg_match('#^[a-z, ]+$#i', $_POST['to']) === 0){
$errors[] = 'The list of names you gave does not look valid.';
}else{
$usernames = explode(',', $_POST['to']);
foreach ($usernames as &$name){
$name = trim($name);
}
$user_ids = fetch_user_ids($usernames);
if (count($user_ids) !== count($usernames)){
$errors[] = 'The following users could not be found: ' . implode(', ', array_diff($usernames, array_keys($user_ids)));
}
}
if (empty($_POST['subject'])){
$errors[] = 'The subject cannot be empty';
}
if (empty($_POST['body'])){
$errors[] = 'You body must have some text!';
}
if (empty($errors)){
//Send message
}
}
if (isset($errors)){
if (empty($errors)){
echo '<div class="msg success">Your message has been sent ! return</div>';
}else{
foreach ($errors as $error){
echo '<div class="msg error">', $error, '</div>';
}
}
}
?>
<form action="" method="POST">
<div>
<label for="to">To</label>
<input type="text" name="to" id="to" />
</div>
<div>
<label for="subject">Subject</label>
<input type="text" name="subject" id="subject" />
</div>
<div>
<textarea name="body" rows="10" cols="110"></textarea>
</div>
<div>
<input type="submit" value="send" />
</div>
</form>
If I take away the "function" part, I can print the data, so it must be something to do with the function element?
I would suggest changing the !== to != and seeeing if that works, it could be interpreting it has a number and not as a bool
Make it simpler. Inside foreach, get rid of &$name and replace it with $name. Also check if your database is returning nothing.
foreach ($usernames as $name){
$name = mysql_real_escape_string($name);
}
$result = mysql_query("SELECT `userid`, `username` FROM `users` WHERE `username` IN ('" . implode("', '", $usernames) . "')");
// Check if the query itself is failing or not here:
if(!$result) die("Failed to perform query");
$names = array();
// Check if the database is returning any rows or not:
print_r(mysql_num_rows($result));
while($row = mysql_fetch_assoc($result)){
$names[$row['username']] = $row['userid'];
}
return $names;
I want to import csv into mysql using codeigniter.
This is my source code.
view
<?php $this->load->view("admin/v_header");?>
<?php $this->load->view("admin/v_top_menu");?>
<?php $this->load->view("admin/v_sidebar");?>
<div class="content">
<div class="header">
<h1 class="page-title">Import Data Dosen</h1>
</div>
<?php $this->load->view("admin/v_alert_msg");?>
<form class="form-horizontal" action="<?php echo base_url();?>admin/save_dosen" method="POST" enctype="multipart/form-data">
<fieldset>
<legend>Import Data Dosen</legend>
<div class="control-group">
<label class="control-label"><b>Pilih File :</b></label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-barcode"></i></span>
<input type="file" name="csv_dosen" id="csv_dosen"/>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-primary">
<i class="icon-ok icon-white"></i>Save
</button>
</div>
</div>
</fieldset>
</form>
</div>
<?php $this->load->view("admin/v_footer");?>
library
<?php
error_reporting(0);
class Csv_impot {
var $csvfile, $delimitatore, $nometable;
var $_FIELD;
function csv_import($cf = "", $del = "", $nt = "") {
$this->csvfile = $cf;
$this->delimitatore = $del;
$this->nometable = $nt;
}
function export() {
$csvhandle = file($this->csvfile);
$field = explode($this->delimitatore, $csvhandle[0]);
$kolom = "";
foreach ($field as $array_kolom) {
$kolom.="`" . trim($array_kolom) . "`,";
}
$kolom = trim(substr($kolom, 0, -1));
//echo $kolom;
for ($i = 1; $i <= count($csvhandle); $i++) {
$valori = explode($this->delimitatore, $csvhandle[$i]);
$values = "";
foreach ($valori as $val) {
$val = trim($val);
if (eregi("NULL", $val) == 0)
$values.="'" . addslashes($val) . "',";
else
$values.="NULL,";
}
$values = trim(substr($values, 0, -1));
$query = "INSERT INTO " . $this->nometable . "(" . $kolom . ") values(" . trim($values) . ");";
$QUERY[$i] = $query;
}
return $QUERY;
}
}
controller
function import_dosen()
{
$this->data['title']="Import Data Dosen";
$this->load->view("admin/v_import_dosen", $this->data);
}
function save_dosen()
{
if(isset($_FILES['csv_dosen']['name']))
{
$csv_dosen=$_FILES['csv_dosen']['name'];
$handle = fopen($csv_dosen,"r");
$this->load->library('csv_import');
$csv=new csv_import(".$handle.",",","dosen");
$query=$csv->export();
$this->m_dosen->eksekusi($query);
// $check_file= explode(".", $csv_dosen);
// if(strtolower($check_file[1])=="csv")
// {
// $csv_dosen=$_FILES['csv_dosen']['temp_name'];
// $handle = fopen($csv_dosen,"r");
// while (($data = fgetcsv($handle, 1000,",")) !== FALSE)
// {
// echo "haha";
// }
// }
// else{echo "bukan file csv";}
//$handle = fopen($csv_dosen,"r");
//$csv_dosen_type=$_FILES['csv_dosen']['type'];
//$csv_dosen_size=$_FILES['csv_dosen']['size'];
}
//echo $handle;
}
models
<?php
class M_dosen extends CI_model
{
function __contruct()
{
parent::__construct();
}
function eksekusi($query)
{
//echo "<br/>";
//echo count($query);
for($i=1;$i<count($query);$i++)
{
$this->db->query($query[$i]);
//echo $query[$i];
//echo "<br/>"
}
}
}
?>
when I run this code, an erro display that [function.fopen]: failed to open stream: No such file or directory.
How I solved this promblem?
I hope you can help to solve this problem.
Thanks.
As per your library, you have to pass file name to your Csv_impot constructor. But you are passing file Handler.
so change your code as below.
//general oops method:
$csv=new csv_import($csv_dosen,",","dosen");
//In CI,
$this->load->library('csv_import',array($csv_dosen,",","dosen")); // no need to create object again. Array of values will be parameter for constructor.