I need to move data from filesystem to database
main folder is home with files and subfolders on various levels
my idea is to loop trough all folders using DirectoryIterator - and get filename and content of each file inside the current folder
this code shows Fatal error:
Uncaught UnexpectedValueException: DirectoryIterator... on line 53
I think the problem is actually with line 72 but all my attempts are unsuccessful
Please help
function go($path){
global $db;
$it = new DirectoryIterator($path); // line 53
foreach ($it as $a){
if ($a->isDot()){continue;}
if($a->isDir()){
$fopath = $it->getPathname();
$foname = $a->getFilename();
$foid = uniqid();
$sq = "insert into nts (id, what, title) values (:aid, :awhat, :atitle)";
$st = $db->prepare($sq);
$st->execute([":aid" => $foid, ":awhat" => 'fo', ":atitle" => $foname]);
$arr = array_filter(glob($fopath . "/*"), 'is_file');
foreach($arr as $el){
$fiid = uniqid();
$finame = basename($el, '.txt');
$story = file_get_contents($el);
$sq = "insert into nts (id, what, par, title, story) values (:aid, :awhat, :apar, :atitle, :astory)";
$st = $db->prepare($sq);
$st->execute([":aid" => $fiid, ":awhat" => 'fi', ":apar" => $foid, ":atitle" => $finame, ":astory" => $story]);
}
go("{$path}{$a->getPathname()}/"); // line 72
}
}
}}
}
go("home/");
Related
After reading all others questions about the HY093 i cant figure out what is causing the error.
i have 3 file to proses INSERT query :
1. controller.php
2. module.php
3. query.php
controller.php
$this->ModelProduct = new ModelProduct($this->db);
$param_new = "':code' =>124,':name' =>".$_POST['post_name']."";
$so_result = $this->ModelProduct->AddNew($param_new);
module.php
define('tbl_all_product','product');
define('field_product','code,name');
define('value_product',':code,:name');
function AddNew($param_new)
{
$insert = $this->insert(tbl_all_product,field_product,value_product,$param_new);
}
query.php
public function insert($tbl, $field, $val, $param_new)
{
$sql = "INSERT INTO ".$tbl." (".$field.") VALUES (".$val.")";
$query = $this->db->prepare($sql);
$query->execute(array($param_new));
}
and this information after debug
$tbl = "product";
$field = "code,name";
$val = ":code,:name";
$param_new = "':code' => 124,':name' => DELL";
$sql = "INSERT INTO product (code,name) VALUES (:code,:name)";
$query = PDOStatement#10 {
"queryString" => "INSERT INTO product (code,name) VALUES (:code,:name)"
};
what is the problem?
You are building the param_new wrong, here's why
$_POST['post_name'] = 'someName';
$param_new = "':code' =>124,':name' =>".$_POST['post_name']."";
print_r(array($param_new));
/*output
Array
(
[0] => ':code' =>124,':name' =>someName
)
*/
This is what you eventually pass to execute(), an array with a single element, containing a comma delimited string.
Build param_new as an array from the beginning:
$_POST['post_name'] = 'someName';
$param_new = array(':code' => 124,':name' => $_POST['post_name']);
print_r($param_new);
/*output
Array
(
[:code] => 124
[:name] => someName
)
*/
and pass it over to execute as it is, not encapsulating it in another array
$query->execute($param_new);
Language: PHP 5
Framework: Joomla 3
I have a single dimension array that I get from get_file_array(). I need to break down the names of the files and eventually query the database for more information. For ease of iteration, I was hoping to add a new dimension to my array rather than create parallel arrays. I thought of iterating through the existing array and adding it one node at a time to a new, specifically multidimensional, perhaps associative array, but this seems inelegant. Is there a way to add a dimension to an existing array in PHP? Here's what I tried last, which obviously doesn't work but conveys the spirit of what I want to accomplish:
require_once "../components/com_esms/models/officelookup.php";
class filearray extends JApplicationCli
{
var $dir = null;
//var_dump($dir);
//error_log("filecopy CWD: ".getcwd());
//error_log("filecopy files: ".print_r($dir, true));
function __construct()
{
$this->dir = scandir("../esms_reports/", 0);
parent::__construct();
}
public function get_file_array()
{
//$this->out('Hello World');
unset($this->dir[0]);
unset($this->dir[1]);
$fa = array_values($this->dir);
return $fa;
}
}
$arr_filearray_obj = new filearray();
$dir = $arr_filearray_obj->get_file_array();
//error_log("filecopy files: ".print_r($dir, true));
/*
foreach($dir as $filename)
{
$fa_underscore = explode("_", $filename);
error_log("filecopy lotid: ".$fa_underscore[1]);
}
*/
//$officeid = array();
for($i = 0; $i < count($dir); $i++)
{
$fa_underscore = explode("_", $dir[$i]);
//error_log("filecopy lotid: ".$fa_underscore[1]);
//error_log("filecopy number of lots: ".$i);
$fa_dash = explode("-", $fa_underscore[1]);
$dir[i][1] = $fa_dash[1];
}
error_log("filecopy officeids: ".print_r($dir, true));
//$result = file_get_contents("http://192.168.1.250/systemname/index.php/option=com_esms&view=officelookup&format=json&officeID=".$officeid[0]);
$officelookup = new EsmsModelofficelookup();
for($o = 0; $o < count($dir); $o++)
{
$result = $officelookup->get_offices($dir[$o][1]);
}
error_log("filecopy JSON: ".$result);
echo("DONE!");
EDIT: Here's an example of the file names I am manipulating. The point is to get the client id, query it, check if it has a parent client id and make a folder structure based on that, using the client names, not IDs.
DDR_1426112931-429_031215.pdf or typeofreport_lotid-clientid_date.pdf
What I would want to add to the array would be the results of my database query, which is a JSON encoded structure containing the client's information and the parent client information, if it exists. It looks something like this:
Array
(
[id] => 123
[name] => Dummy
[parent] => 321
)
Array
(
[id] => 321
[name] => DummyParent
[parent] =>
)
I try insert some articles from a PHP script but i don´t get it. I need to know what fields are required and how I can create the query to do it.
Now, I´m write the next code:
foreach($RSS_DOC->channel->item as $RSSitem){
$alias = md5($RSSitem->title);
$fetch_date = date("Y-m-j G:i:s"); //NOTE: we don't use a DB SQL function so its database independent
$item_title = $RSSitem->title;
$item_description = $RSSitem->description;
$item_date = date("Y-m-j G:i:s", strtotime($RSSitem->pubDate));
$item_url = $RSSitem->link;
// Does record already exist? Only insert if new item...
$item_exists_sql = "SELECT alias FROM jos_content where alias = ".$alias;
$item_exists = mysqli_query($enlace,$item_exists_sql);
if(mysqli_num_rows($item_exists)<1){
$mensaje = "<p>".$item_description."</p>Publicado: ".$item_date."<br/><a href='".$item_url."'>Ver noticia original</a>";
$item_insert_sql = "INSERT INTO jos_content(title, alias, introtext, state, catid, created, created_by, access,featured) VALUES ('" .$item_title. "', '" . $alias. "', '" . $mensaje. "',1, 10,'".$fetch_date."',448,1,1)";
$insert_item = mysqli_query($enlace,$item_insert_sql);
}
}
First order of business is to create the article data object. I use a method to scrub out an existing id or asset_id references in case I'm migrating article data from one instance to another. This could be replaced by your logic to build out the article data object as well. Just be sure to use an associative array:
function processArticleData($obj) {
$data = array();
foreach ($obj as $key => $value) {
$data[$key] = $value;
}
$data['id'] = 0;
unset($data['asset_id']);
return $data;
}
Next you load the JTable content class, bind the data and save. Joomla does all the rest:
function addArticle($obj) {
// Initialise variables;
$data = processModuleData($obj);
$table = &JTable::getInstance('content');
// Bind the data.
if (!$table->bind($data))
{
echo "<h1>Error Binding Article Data</h1>";
return false;
}
// Check the data.
if (!$table->check())
{
echo "<h1>Error Checking Article Data</h1>";
return false;
}
// Store the data.
if (!$table->store())
{
echo "<h1>Error Storing Article Data</h1>";
return false;
}
return $table->get('id');
}
The benefits of this approach is it removes any "guessing" about required fields or potential errors, as if there is an issue with the data Joomla will throw an exception or error stating what the issue was. If you wanted/needed to get real fancy, you could even load the JForm object for content, bind your data to it and then validate before binding to the JTable object.
Creating the data object has only two requirements. The first is to use an associative array and the second all key names match columns in the #__content table. An example data object would look like this:
$data = array(
'title' => $title,
'alias' => $alias,
'introtext' => $introtext,
'fulltext' => $fulltext,
'catid' => $catid,
'images' => '',
'urls' => '',
'attribs' => '',
'metakey' => '',
'metadesc' => '',
'metadata' => '',
'language' => '',
'xreference' => '',
'created' => JFactory::getDate()->toSql(),
'created_by' => JFactory::getUser()->id,
'publish_up' => JFactory::getDate()->toSql(),
'publish_down' => JFactory::getDbo()->getNullDate(),
'state' => 1
);
I use some more Joomla helper functions to make my job easier, but this should provide a good starting point for you to get the ball rolling.
* EDIT *
Noticed a typo which I corrected. Not sure if you copy/pasted but switch the below line for the array declaration above and test again:
$data = processModuleData($obj);
This script should do it....assuming it exists in the root of your site:
if (!defined('_JEXEC')) {
define( '_JEXEC', 1 );
define ('JPATH_BASE', 'c:\\wamp\\www\\mysiteroot');
require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );
$mainframe = JFactory::getApplication('site');
}
function getContentTable($type = 'Content', $prefix = 'JTable', $config = array())
{
return JTable::getInstance($type, $prefix, $config);
}
function addArticle($title, $alias)
{
$table = getContentTable();
$table->title = $title;
$table->alias = $alias;
$table->catid = 2;
$table->state = 1;
// and so on!
// then save it
$table->store();
}
$result = addArticle("foo", "bar");
I have read through many posts regarding previous/next and I am still very much stuck.
I have a page which shows an image and related data. This is obtained from a database. The images are located within the website folder in folders per album. So an image folder may contain 1, 2 or 100 images.
I have a function as follows for this data:-
function get_images_album($artist_id) {
$artist_id = (int)$artist_id;
$images = array();
$image_query = mysql_query("SELECT `image_album_id`, `member_id`, `artist_id`,
`albumname`, `ext`, `timestamp` FROM `album_images`
WHERE `artist_id`=$artist_id AND `member_id`=".$_SESSION['member_id']);
while ($images_row = mysql_fetch_assoc($image_query)) {
$images[] = array(
'id' => $images_row['image_album_id'],
'album' => $images_row['artist_id'],
'albumname' => $images_row['albumname'],
'ext' => $images_row['ext'],
'timestamp' => $images_row['timestamp']
);
}
return $images;
}
The page shows the correct image and data per the url on localhost. Site/album_view.php?artist_id=4&image_album_id=4.
On the html page the code is:-
$images = get_images_album($artist_id);
if (empty($images)) {
echo 'There are no Images in this album.';
}else{
foreach ($images as $key => $val) {
}
}
?>
I had understood that if I echo $key and current($val) I would get the array index nos. and image id for the current page. In the case above this would be 0 and 4. However I always get the last index details of the array, which happens to be 13 and 2181 for the particular album.
I know all the data is there as I have echoed the array and all seems ok.
I do not know why.
Going on from what I have I cannot work out how to proceed to get the next and previous settings Thank you.
An easier way to go about this might be to change your get_images_album function slightly:
function get_images_album($artist_id) {
$artist_id = (int)$artist_id;
$images = array();
$image_query = mysql_query("SELECT `image_album_id`, `member_id`, `artist_id`,
`albumname`, `ext`, `timestamp` FROM `album_images`
WHERE `artist_id`=$artist_id AND `member_id`=".$_SESSION['member_id']);
While ($images_row = mysql_fetch_assoc($image_query)) {
// $images[] = array(
// instead, make your images array a hash and key it on the album_id
$images[$images_row["image_album_id"]] = array(
'id' => $images_row['image_album_id'],
'album' => $images_row['artist_id'],
'albumname' => $images_row['albumname'],
'ext' => $images_row['ext'],
'timestamp' => $images_row['timestamp']
);
}
return $images;
}
now you can eliminate your foreach loop and just get the album you're looking for:
$images = get_images_album($artist_id);
if (empty($images)) {
echo 'There are no Images in this album.';
}else{
$album_images = $images[$image_album_id];
// do stuff with the $album_images hash
var_dump($album_images);
}
I am trying to trieve a list of files where a field ARTICLE_NO is a certain number. At the moment, I have a files table, with columns ARTICLE_NO, FILENAME and USERNAME. There is one record, with values 1, x.txt and user respectively. $pk is assigned to 1 in my php code. However, the following code only produces NULL, and I am unsure why.
$filesQuery = "SELECT FILENAME FROM FILES WHERE ARTICLE_NO = ?";
if ($getFiles = $con->prepare($filesQuery)) {
$getFiles->bind_param("s", $pk);
$getFiles->execute();
$getFiles->bind_result($FILENAME);
$files = array();
while ($getFiles->fetch()) {
$filenames = array(
'FILENAME' => $FILENAME,
);
$files[] = $filenames;
}
}
var_dump($files['FILENAME']);
foreach ($files as $filenames)
{
$filesList = '<p>'. $files['FILENAME'] .'' . "\n";
}
You're accessing the array you built up wrongly. When dealing with 1 result row from the database, $files is an array containing 1 other array looking like this:
$files = array ( 0 => array ( 'FILENAME' => 'x.txt' ) );
So, to access the value under FILENAME, you need to use:
var_dump($files[0]['FILENAME']);
or
foreach($files as $file_data) { echo $file_data['FILENAME']; }