I need to access an .xlsb file that does the same function as this code that accesses a .csv file:
<?php
$file1 = __DIR__ . '/download/Trabalhos.csv';
$csv1 = file($file1);
foreach ($csv1 as $row1 => $line1) {
$row1++;
$column1 = str_getcsv($line1, ';');
if ($row1 == 2) {
$column1[6]."<br>";
$valor1 = $column1[6];
}
}
$file2 = __DIR__ . '/download/produtividade do trabalho.csv';
$csv2 = file($file2);
foreach ($csv2 as $row2 => $line2) {
$row2++;
$column2 = str_getcsv($line2, ';');
if ($row2 == 3) {
$column2[9]."<br>";
$valor2 = $column2[9];
}
}
$file3 = __DIR__ . '/download/inatividade do trabalho.csv';
$csv3 = file($file3);
foreach ($csv3 as $row3 => $line3) {
$row3++;
$column3 = str_getcsv($line3, ';');
if ($row3 == 2) {
$column3[0]."<br>";
$valor3 = $column3[0];
}
}
$total = $valor1 * $valor2 * $valor3;
?>
Access the .xlsb file, scroll through the columns and rows, and display the row value on the screen.
Example: "Line 2, Column G(In this case, G = 6)
"A = 0
B = 1
C = 2)"
...
I want it to show me the value of row 2 that is in column G(6).
As in the first if ...
if ($row1 == 2) {
$column1[6]."<br>";
$valor1 = $column1[6];
}
You can use the PHP Excel library from EasyXLS.
$xls = new COM("EasyXLS.ExcelDocument");
$rows = $xls->easy_ReadXLSBActiveSheet_AsList("Trabalhos.xlsb");
for ($row1=0; $row1<$rows->size(); $row1++)
{
$rowLine = $rows->elementAt($row1);
if ($row1 == 2) {
$column1[6]."<br>";
$valor1 = $row->elementAt(6);
}
}
You can find some more code samples about importing data from xlsb file.
For your purpose you can use PHPOffice/PHPExcel
Related
I am importing some data into a mysql table from an xls file.
On the data, i want to use the mysqli_real_escape_string function, before i insert it into the sql table.
My question is that: where should i put the array_map with the escape function in this code below?
Thanks for help.
if(isset($_POST['submitButton']))
{
if($_FILES['file']['size'] != 0 )
{
if($_FILES["file"]["size"] > 5242880 ) { $error[] = "A fájl mérete maximum 5 MB lehet."; }
$filename = $_FILES['file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $fajl_types)) { $error[] = "Nem engedélyezett fájl típus."; }
if(count($error) == 0 )
{
$path = "../imports/" . date( "Y-m-d" ) . '-' . rand(1, 9999) . '-' . $_FILES['file']['name'];
if(move_uploaded_file($_FILES['file']['tmp_name'], $path ))
{
$file_name = basename($path);
$objPHPExcel = PHPExcel_IOFactory::load('../imports/'.$file_name);
$dataArr = array();
foreach($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
for ($row = 1; $row <= $highestRow; ++ $row) {
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
$dataArr[$row][$col] = $val;
}
}
}
unset($dataArr[1]); // since in our example the first row is the header and not the actual data
$user_pass = "";
$user_reg_date = date("Y-m-d-H:i:s");
$user_last_login = "";
$user_aktivation = "";
$user_vevocsoport = (int)0;
$user_newpass = "";
$user_imported = (int)1;
foreach($dataArr as $val)
{
$sql = "INSERT INTO user
(
user_vnev,
user_knev
)
VALUES
(
'".$val['0']."',
'".$val['1']."'
)";
$import = mysqli_query($kapcs, $sql) or die("IMPORT-ERROR - " . mysqli_error($kapcs));
$ok = 1;
}
}
else
{
$error[] = "A fájl feltöltése nem sikerült.";
}
}
}
else
{
$error[] = "Nem választott ki fájlt.";
}
}
You can add it when building the query. Like this, the escaping and building the query, which are both related to each other, are close to each other in your code.
foreach($dataArr as $val)
{
$escapedVals = array_map(function($value) use ($kapcs) {
return mysqli_real_escape_string($kapcs, $value);
}, array_slice($val, 0, 2));
$sql = 'INSERT INTO user
(
user_vnev,
user_knev
)
VALUES
(
"' . implode ('","', $escapedVals) . '"
)';
$import = mysqli_query($kapcs, $sql) or die("IMPORT-ERROR - " . mysqli_error($kapcs));
$ok = 1;
}
I'm want string out of the column data.
But it failed.
<?php
$conn = mysql_connect("localhost", "nantawat", "12345678") or die(mysql_error());
$select_db = mysql_select_db("my_db", $conn) or die(mysql_error());
$select_tbl = mysql_query("SELECT * FROM log", $conn);
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
if (!isset($i[1])) {
for ($j = 0; $j <= 200; $j++) {
$i[$j] = null;
}
}
$name = $i[0];
$mama = $i[1];
$no = $i[2];
$a = $i[3];
$b = $i[4];
echo $name . "</br>";
echo $mama . $no . $a . $b . "</br>";
}
while ($data = mysql_fetch_object($select_tbl)) {
echo $data->data . "<br>";
}
?>
But i want output =
bus
car
bike
aabus
car
bike
aabus
car
bike
aabus
ddd
ee
And i not
Notice: Undefined offset: 3 in C:\xampp\htdocs\logs\New folder
(2)\explode.php on line 21
Notice: Undefined offset: 4 in C:\xampp\htdocs\logs\New folder
(2)\explode.php on line 22
Thank You.
You should just do what you want to do.
You want to connect to database then do it:
$conn = mysql_connect("localhost", "nantawat", "12345678") or die(mysql_error());
I suggest you to use mysqli library instead of mysql (mysql is deprecated in new php versions and totally removed in php7)
$conn = mysqli_connect("localhost", "nantawat", "12345678", "my_db") or die(mysql_error());
You want to query on log table, then do it:
$select_tbl = mysqli_query($conn, "SELECT * FROM log");
You want to fetch info from your result, then do it:
while ($row = mysqli_fetch_array($select_tbl)) {
echo $row['id_user'];
echo $row['id_doc'];
echo $row['date'];
echo $row['data'];
}
You want to explode data, then do it:
while ($row = mysqli_fetch_array($select_tbl)) {
echo $row['id_user'];
echo $row['id_doc'];
echo $row['date'];
$data = explode(',', $row['data']);
foreach ($data as $d) {
if ($d !== '') { // because before first comma or after last can be empty
echo $d . PHP_EOL;
}
}
}
If you want to save database result in variables:
If you are getting only one row of database, you can save them in variables directly:
$id_user = '';
$id_doc = '';
$date = '';
$data = array();
id ($row = mysqli_fetch_array($select_tbl)) {
$id_user = $row['id_user'];
$id_doc = $row['id_doc'];
$date = $row['date'];
$tempData = explode(',', $row['data']);
foreach ($tempData as $d) {
if ($d !== '') {
$data[] = $d;
}
}
}
And if you have multiple rows of database you need to save them all in a total array:
$array = array();
id ($row = mysqli_fetch_array($select_tbl)) {
$id_user = $row['id_user'];
$id_doc = $row['id_doc'];
$date = $row['date'];
$data = array();
$tempData = explode(',', $row['data']);
foreach ($tempData as $d) {
if ($d !== '') {
$data[] = $d;
}
}
$array[] = array(
'id_user' => $id_user,
'id_doc' => $id_doc,
'date' => $date,
'data' => data,
);
}
And finally use this to see what structure your final array has:
echo '<pre>';
pront_r($array);
echo '</pre>';
First off it is not wise to store comma seperated values in a single cell and you are using deprecated mysql_ functions. I think your solution can be found in using a foreach instead of the isset part:
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
foreach ($i as $q){
echo $q . '<br/>';
}
}
If you still want to access your variables $name, $mama, $no and $ab, you can use isset for those specifically.
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
if (isset($i[0])){
$name = $i[0];
echo $name . '<br>'; //only echo if it exists
}
if (isset($i[1])){
$mama= $i[1];
echo $mama. '<br>'; //only echo if it exists
}
//try it yourself for $no and $ab
}
Try:
while ($row = mysqli_fetch_array($select_tbl)) {
extract($row);
/* Using extract method can get the array key value as variable
Below variables are available
$id_user;
$id_doc;
$date;
$data; */
}
$inputFileName = $_FILES["file"]["tmp_name"];
$objReader = PHPExcel_IOFactory::createReader('Excel5');
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($inputFileName);
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow(); // e.g. 10
$highestColumn = $objWorksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 5
$Player_name = '';
$Activity_name = '';
$Domain_id = '';
$Activity_description = '';
$Activity_date;
$player_id_owner = '';
$DomainCount = '';
echo '<table>' . "\n";
for ($row = 5; $row <= $highestRow -1; ++$row)
{
echo '<tr>' . "\n";
for ($col = 0; $col <= $highestColumnIndex; ++$col)
{
echo '<td>' . $objWorksheet->getCellByColumnAndRow($col, $row)->getValue() . '</td>' . "\n";
$Domain_name = $objWorksheet->getCellByColumnAndRow(0, $row)->getValue();
$Activity_name = $objWorksheet->getCellByColumnAndRow(1, $row)->getValue();
$Activity_description = $objWorksheet->getCellByColumnAndRow(2, $row)->getValue();
$Player_name = $objWorksheet->getCellByColumnAndRow(8, $row)->getValue();
$Activity_date = $objWorksheet->getCellByColumnAndRow(10, $row)->getFormattedValue();
echo '</tr>' . "\n";
echo '</table>' . "\n";
}
$playerCount = $this->PlayerCount($Player_name);
echo "Current player name is: ".$Player_name;
echo "Current player count is: ".$playerCount;
if($playerCount == 0)
{
$email = str_replace(' ', '', "$Player_name#nsn.com");
$player_type_id = 2;
$password = "password123";
$this->Activity->create('Player');
$this->request->data['name'] = $Player_name;
$this->request->data['player_type_id'] = $player_type_id;
$this->request->data['email'] = $email;
$this->request->data['password'] = $password;
if ($this->Player->save($this->request->data))
{
$this->flashSuccess(__('Player saved successfully!'. $Player_name));
echo ("Player saved successfully!". $Player_name);
}
else
{
$this->flashError(__('Error while trying to save Player.'));
debug($this->Activity->validationErrors);
}
}
$color = "#99CCFF";
$abbr = "TD";
$description = $Domain_name;
$player_type_id = 1;
$player_id_owner = $this->findPlayerId($Player_name);
//$player_id_owner = $this->Activity->findId($Player_name);
//echo h($id = $player_id_owner['Player']['id'] );
//debug($player_id_owner);
echo "Current Domain name is: ".$Domain_name;
$domainCount = $this->DomainCount($Domain_name);
echo "Current Domain count is: ".$domainCount;
if($domainCount == 0)
{
$inactive = 0;
$this->Activity->create('Domain');
$this->request->data['name'] = $Domain_name;
$this->request->data['color'] = $color;
$this->request->data['abbr'] = $abbr;
$this->request->data['icon'] = 'fa fa-bolt';
$this->request->data['description'] = $description;
$this->request->data['player_type_id'] = $player_type_id;
$this->request->data['player_id_owner'] = $player_id_owner['Player']['id'] ;
$this->request->data['inactive'] = $inactive;
if ($this->Domain->save($this->request->data))
{
$this->flashSuccess(__('Domain saved successfully!'. $Domain_name));
echo ("Domain saved successfully!". $Domain_name);
}
else
{
$this->flashError(__('Error while trying to save domain.'));
debug($this->Activity->validationErrors);
}
}
$activityCount = $this->ActivityCount($Activity_name);
echo "Current activity name is: ".$Activity_name;
echo "Current Activity count is: ".$activityCount;
if($activityCount == 0)
{
$Domain_id = $this->findDomainId($Domain_name);
//debug($Domain_id);
$this->Activity->create('Activity');
$this->request->data['name'] = $Activity_name;
$this->request->data['domain_id'] = $Domain_id['Domain']['id'];
$this->request->data['description'] = $Activity_description;
$this->request->data['inactive'] = 0;
$this->request->data['new'] = 1;
$this->request->data['xp'] = 100;
$Activity_date = PHPExcel_Style_NumberFormat::toFormattedString($Activity_date, 'YYYY-MM-DD h:mm:ss');
$this->request->data['created'] = $Activity_date;
$this->request->data['reported'] = 0;
$this->request->data['player_id_owner'] = $player_id_owner['Player']['id'];
$this->request->data['acceptance_votes'] = 1;
$this->request->data['rejection_votes'] = 1;
if ($this->Activity->save($this->request->data))
{
$this->flashSuccess(__('Activity saved successfully!'. $Activity_name));
echo ("Activity saved successfully!". $Activity_name);
}
else
{
$this->flashError(__('Error while trying to save activity.'));
debug($this->Activity->validationErrors);
}
}
}
I have this function that reads and save domain, activity and player from an excel file. when the excel file contains only 1 row, it functions well, but if the excel contains more than 1 file, only the last row are save but all the activities from all rows are saved, i tried to debug it, i echo every loop and it reads all the row and i try to insert an echo after the saving method to know if it success and it works but when i check it in database, only the last line are saved but the activities are all saved. Kindly help me on this thanks.
Reset the model with $this->Activity->clear();
As the CakePHP book states:
When calling save in a loop, don’t forget to call clear().
The clear method resets the model before saving the data. If you do not use clear(), the ID of the saved row is still in the model, thus the next call to save overwrites the previously saved row.
See the CakePHP book on the clear method:
This method can be used to reset model state and clear out any unsaved data and validation errors.
I´m pretty much entirely new to PHP, so please bear with me.
I´m trying to build a website running on a cms called Core. I'm trying to make it so that the previous/next buttons cycle through tags rather than entries. Tags are stored in a database as core_tags. Each tag has it own tag_id, which is a number. I've tried changing the excisting code for thep previous/next buttons, but it keeps giving me 'Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /home/core/functions/get_entry.php on line 50'.'
Any help would be greatly appreciated.
Get_entry.php:
<?php
$b = $_SERVER['REQUEST_URI'];
if($entry) {
$b = substr($b,0,strrpos($b,"/")) . "/core/";
$id = $entry;
$isPerma = true;
} else {
$b = substr($b,0,mb_strrpos($b,"/core/")+6);
$id = $_REQUEST["id"];
}
$root = $_SERVER['DOCUMENT_ROOT'] . $b;
$http = "http://" . $_SERVER['HTTP_HOST'] . substr($b,0,strlen($b)-5);
require_once($root . "user/configuration.php");
require_once($root . "themes/".$theme."/configuration.php");
require_once($root . "functions/session.php");
if(is_numeric($id)) {
$type = "entry";
} else {
$type = "page";
}
$id = secure($id);
if($type == "page") {
$data = mysql_query("SELECT p.* FROM core_pages p WHERE p.page_title = \"$id\"");
$page_clicks = 0;
while($p = mysql_fetch_array($data)) {
$url = $p["page_url"];
$path = $root . "user/pages/" . $url;
$page_clicks = $p['hits']+1;
require($path);
}
mysql_query("UPDATE core_pages p SET
p.hits = $page_clicks
WHERE p.page_title = $id");
}
if($type == "entry") {
// queries the dbase
$data_tags = mysql_query("SELECT entry_id,entry_title FROM core_entries WHERE entry_show = 1 ORDER BY entry_position DESC") or die(mysql_error());
$navArr=array();
while($tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC)){
array_push($navArr,$tmparray['entry_id']);
}
function array_next_previous($array, $value) {
$index = array_search($value,$array);
//if user clicked to view the very first entry
if($value == reset($array)){
$return['prev'] = end($array);
$return['next'] = $array[$index + 1];
//if user clicked to view the very last entry
}else if($value == end($array)){
$return['prev'] = $array[$index - 1];
reset($array);
$return['next'] = current($array);
}else{
$return['next'] = $array[$index + 1];
$return['prev'] = $array[$index - 1];
}
return $return;
}
$data = mysql_query("SELECT e.* FROM core_entries e WHERE e.entry_id = $id AND e.entry_show = 1");
$entry_clicks = 0;
if(#mysql_num_rows($data) < 1) {
die("Invalid id, no entry to be shown");
}
while($e = mysql_fetch_array($data)) {
$nextPrevProject = array_next_previous($navArr,$id);
$entry_id = $e['entry_id'];
$entry_title = $e['entry_title'];
// DATE
$t = $e["entry_date"];
$y = substr($t,0,4);
$m = substr($t,5,2);
$d = substr($t,8,2);
$entry_date = date($date_format,mktime(0,0,0,$m,$d,$y));
$entry_text = $e['entry_text'];
$entry_extra1 = $e['entry_extra1'];
$entry_extra2 = $e['entry_extra2'];
$entry_client = $e['entry_client'];
$entry_position = $e['entry_position'];
$entry_hits = $e['hits']+1;
$entry_new = $e['entry_new'];
if($entry_new == 1) {
$isNew = true;
} else {
$isNew = false;
}
if($nice_permalinks) {
$entry_perma = "$http".$entry_id;
} else {
$entry_perma = "$http"."?entry=$entry_id";
}
$data_e2t = #mysql_query("SELECT e2t.tag_id FROM core_entry2tag e2t WHERE e2t.entry_id = $entry_id");
$tag_str = "";
while($e2t = #mysql_fetch_array($data_e2t)) {
$tag_id = $e2t["tag_id"];
$data_tags = #mysql_query("SELECT t.tag_text FROM core_tags t WHERE t.tag_id = $tag_id");
while($t = #mysql_fetch_array($data_tags)) {
$tag_text = $t["tag_text"];
$tag_str = $tag_str . "<a class=\"tag-link\" name=\"tag".$tag_id."\" href=\"#tag-"._encode($tag_text)."\">".$tag_text."</a>".$separator_tags;
}
}
$entry_tags = substr($tag_str,0,strlen($tag_str)-strlen($separator_tags));
$layout_path = $root . "user/uploads/" . treat_string($entry_title) . "/layout.php";
if(is_file($layout_path) && (#filesize($layout_path) > 0)) {
require($layout_path);
} else {
require($theme_path . "parts/entry.php");
}
}
mysql_query("UPDATE core_entries e SET
e.hits = $entry_hits
WHERE e.entry_id = $id");
}
if($isPerma) {
echo "<a class=\"index-link\" href=\"$http\">back to index</a>";
}
?>
You have not defined $data_entries, before using it here:
while($tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC)){
array_push($navArr,$tmparray['entry_id']);
}
That is why you get the very descriptive error message.
Did you mean to use $data_tags?
Use: "SELECT p.* FROM core_pages p WHERE p.page_title = '".$id."'
Note: mysql_connect is not sql-injection save. If you use mysql_connect, change to PDO.
$data_entries is not defined on line 50, then mysql_fetch_array return an exception of null value given.
Try to change $tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC) to $tmparray = mysql_fetch_array($data_tags,MYSQL_ASSOC).
Hope this help!
I have here my php code and txt file. I want to display 6 lines in .txt file randomly at the output of php. How can i do it. I try my code but it only display the first 6 lines.
Thanks!
Php:
require_once "config.php";
$txt_file = file_get_contents($database);
$rows = explode("\n", $txt_file);
array_shift($rows);
$i = 0;
foreach($rows as $row => $data)
{
$row_data = explode('&id=', $data);
$info[$row]['name'] = $row_data[0];
$info[$row]['id'] = $row_data[1];
$name = $info[$row]['name'];
$id = $info[$row]['id'];
echo $name."<BR>";
echo $id."<BR><BR>";
if (++$i == "6") break;
}
Txt file:
ABC&id=1
DEF&id=2
GHI&id=3
<?
// read file content into array
// http://fi2.php.net/file
$txt_file = file($database);
// pick six elements randomly
// http://fi2.php.net/array_rand
foreach( array_rand($txt_file, count($txt_file)>6 ? 6 : count($txt_file)) as $row => $data)
{
$row_data = explode('&id=', $data);
$info[$row]['name'] = $row_data[0];
$info[$row]['id'] = $row_data[1];
$name = $info[$row]['name'];
$id = $info[$row]['id'];
echo $name."<BR>";
echo $id."<BR><BR>";
}
?>