List images from directory by function - php

I'm using this function:
function getmyimages($qid){
$imgdir = 'modules/Projects/uploaded_project_images/'. $qid .''; // the directory, where your images are stored
$allowed_types = array('png','jpg','jpeg','gif'); // list of filetypes you want to show
$dimg = opendir($imgdir);
while($imgfile = readdir($dimg))
{
if(in_array(strtolower(substr($imgfile,-3)),$allowed_types))
{
$a_img[] = $imgfile;
sort($a_img);
reset ($a_img);
}
}
$totimg = count($a_img); // total image number
for($x=0; $x < $totimg; $x++)
{
$size = getimagesize($imgdir.'/'.$a_img[$x]);
// do whatever
$halfwidth = ceil($size[0]/2);
$halfheight = ceil($size[1]/2);
$mytest = 'name: '.$a_img[$x].' width: '.$size[0].' height: '.$size[1].'<br />'. $a_img[$x]. '';
}
return $mytest;
}
And I call this function between a while row as:
$sql_select = $db->sql_query('SELECT * from '.$prefix.'_projects WHERE topic=\''.$cid.'\'');
OpenTable();
while ($row2 = $db->sql_fetchrow($sql_select)){
$qid = $row2['qid'];
$project_query = $db->sql_query('SELECT p.uid, p.uname, p.subject, p.story, p.storyext, p.date, p.topic, p.pdate, p.materials, p.bidoptions, p.projectduration, pd.id_duration, pm.material_id, pbo.bidid, pc.cid FROM ' . $prefix . '_projects p, ' . $prefix . '_projects_duration pd, ' . $prefix . '_project_materials pm, ' . $prefix . '_project_bid_options pbo, ' . $prefix . '_project_categories pc WHERE p.topic=\''.$cid.'\' and p.qid=\''.$qid.'\' and p.bidoptions=pbo.bidid and p.materials=pm.material_id and p.projectduration=pd.id_duration');
while ($project_row = $db->sql_fetchrow($project_query)) {
//$qid = $project_row['qid'];
$uid = $project_row['uid'];
$uname = $project_row['uname'];
$subject = $project_row['subject'];
$story = $project_row['story'];
$storyext = $project_row['storyext'];
$date = $project_row['date'];
$topic = $project_row['topic'];
$pdate = $project_row['pdate'];
$materials = $project_row['materials'];
$bidoptions = $project_row['bidoptions'];
$projectduration = $project_row['projectduration'];
//Get the topic name
$topic_query = $db->sql_query('SELECT cid,title from '.$prefix.'_project_categories WHERE cid =\''.$cid.'\'');
while ($topic_row = $db->sql_fetchrow($topic_query)) {
$topic_id = $topic_row['cid'];
$topic_title = $topic_row['title'];
}
//Get the material text
$material_query = $db->sql_query('SELECT material_id,material_name from '.$prefix.'_project_materials WHERE material_id =\''.$materials.'\'');
while ($material_row = $db->sql_fetchrow($material_query)) {
$material_id = $material_row['material_id'];
$material_name = $material_row['material_name'];
}
//Get the bid methode
$bid_query = $db->sql_query('SELECT bidid,bidname from '.$prefix.'_project_bid_options WHERE bidid =\''.$bidoptions.'\'');
while ($bid_row = $db->sql_fetchrow($bid_query)) {
$bidid = $bid_row['bidid'];
$bidname = $bid_row['bidname'];
}
//Get the project duration
$duration_query = $db->sql_query('SELECT id_duration,duration_value,duration_alias from '.$prefix.'_projects_duration WHERE id_duration =\''.$projectduration.'\'');
while ($duration_row = $db->sql_fetchrow($duration_query)) {
$id_duration = $duration_row['id_duration'];
$duration_value = $duration_row['duration_value'];
$duration_alias = $duration_row['duration_alias'];
}
}
echo '<br/><b>id</b>--->' .$qid. '<br/><b>uid</b>--->' .$uid. '<br/><b>username</b>--->' .$uname. '<br/><b>subject</b>--->'.$subject. '<br/><b>story1</b>--->'.$story. '<br/><b>story2</b>--->'.$storyext. '<br/><b>postdate</b>--->'.$date. '<br/><b>categorie</b>--->'.$topic_title . '<br/><b>project start</b>--->'.$pdate. '<br/><b>materials</b>--->'.$material_name. '<br/><b>bid methode</b>--->'.$bidname. '<br/><b>project duration</b>--->'.$duration_alias.'<br /><br /><br/><b>image url</b>--->'.getmyimages($qid).'<br /><br />';
}
CloseTable();
The result outputs only the "last" file from the directories.
If I do an echo instead of a return $mytest;, it reads the whole directory but ruins the output.

You are always overwriting $mytest in your loop:
for($x=0; $x < $totimg; $x++)
{
$size = getimagesize($imgdir.'/'.$a_img[$x]);
// do whatever
$halfwidth = ceil($size[0]/2);
$halfheight = ceil($size[1]/2);
$mytest = 'name: '.$a_img[$x].' width: '.$size[0].' height: '.$size[1].'<br />'. $a_img[$x]. '';
}
return $mytest;
So after the loop, $mytest contains the last value that was generated in the loop. You might want to return an array instead:
$mytest = array();
for($x=0; $x < $totimg; $x++)
{
$size = getimagesize($imgdir.'/'.$a_img[$x]);
// do whatever
$halfwidth = ceil($size[0]/2);
$halfheight = ceil($size[1]/2);
$mytest[] = 'name: '.$a_img[$x].' width: '.$size[0].' height: '.$size[1].'<br />'. $a_img[$x]. '';
}
return $mytest;
But of course you also have to change your other function in order to deal with the returned array.

Related

PHP file unable to extract and split image from database after made changes to the file

I have this issue on one of servers, Up until last week, the feed it was pulling the content from was working fine. Now suddenly since last few days, when I made the change to extract category field from database since then it is not extracting the image from the feed but is able to extract all of other content. (This server was set up by previous developer).
I keep getting this error:
going to get file 2020-07-23T15:41:05
going to put /var/www/SpanishMix/
!! problem getting remote file ( 2020-07-23T15:41:05 ) in checkNGet ** trying replace , digiv/2105318.jpg
This is the code in php file:
<?php
set_time_limit(90);
ini_set('memory_limit', '128M');
$xurl = 'feedlink.com/feed/getXML.php';
$locs = 'server ip';
$locvid = '/var/www/SpanishMix/';
function decrypto($inStr)
{
$key = '';
$encrypted = $inStr;
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
return $decrypted;
}
function dis($v)
{
echo "<pre>\n";
print_r($v);
echo "\n</pre>\n<hr>\n";
}
// --------------------- grab XML
$c = file_get_contents($xurl);
if (strlen($c) < 100) {
exit('couldnt get data from CMS');
}
// --------------------- parse into usable array of objects
$sa = array();
$ta1 = explode('_ENDI_', $c);
foreach ($ta1 as $i) {
$ta2 = explode('_ENDF_', $i);
if ((strlen($ta2[0]) > 4) && (strlen($i) > 200)) {
$to = new stdClass();
$to->uid = $ta2[0];
$to->vurl = "";
$to->body = $ta2[1];
$to->people = trim($ta2[2]);
$to->headline = trim($ta2[3]);
$to->category = trim($ta2[4]);
$to->abstract = trim($ta2[5]);
$to->pubdate = trim($ta2[7]);
$to->storyid = trim($ta2[6]);
$to->iurl = trim($ta2[8]);
$tmpia = explode('.com/', $to->iurl);
$to->cpi = $tmpia[1];
$to->iloc = 'http://' . $locs . '/SpanishMix/' . $tmpia[1];
// code for durability date
$tmpda = explode('-', $to->pubdate);
$oldy = $tmpda[0];
$newy = $oldy + 1;
$newys = str_replace($oldy, $newy, $to->pubdate);
$to->durdate = $newys;
$to->gotv = 0;
$to->fs = 0;
if ($to->uid > 10000) {
$sa[$to->uid] = $to;
}
}
}
dis($sa);
// --------------------- scan vids dir, parse into array including filesize
$va = array();
$dir = $locvid . "*.jpg";
foreach (glob($dir) as $file) {
$tv = new stdClass();
$tv->fn = $file;
$tv->s = filesize($file);
array_push($va, $tv);
}
dis($va);
// --------------------- check through stories array structure marking those already with video
$vtg = '';
$itg = '';
$uidtg = '';
// loop through each story
foreach ($sa as $s) {
$found = 0;
foreach ($va as $v) {
// hack out matchable filename from video and story arrays
$tfn = '/var/www/SpanishMix/' . $s->cpi;
if ($tfn == $v->fn) {
$found = 1;
}
}
// if outer looop variable says no video found for this story, make this storey's video URL next to get
if (!$found) {
echo "<br>setting itg to $s->iurl<br>\n";
$itg = $s->iurl;
$uidtg = $s->uid;
}
}
echo "<hr><h1> getting video part</h1><br><br>";
// --------------------- elect first story entry with no file
if ($itg) {
// split img url to take
$ifa = explode('.com/', $itg);
$itg = $itg;
$outfile = '/var/www/SpanishMix/' . $ifa[1];
echo "\n<br><b>going to get file $itg<br>going to put $outfile</b><br>\n";
$remoteFile = file_get_contents($itg);
if (!$remoteFile) {
echo "!! problem getting remote file ( $itg ) in checkNGet\n\n";
} else {
$res = file_put_contents($outfile, $remoteFile);
if ($res) {
echo "put remote image file ( $outfile ) success !\n\n\n";
// NOW COPY LOCAL FILE TO FUNNY FILENAME
$cpifn = '/var/www/SpanishMix/digiv/' . $uidtg . '.jpg';
echo "* about to copy $outfile to $cpifn\n\n";
copy($outfile, $cpifn);
} else {
echo "put remote image file ( $outfile ) fail :( \n\n\n<br><br>";
}
}
}
$tt = '';
$tm = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<videonews>
<news>
<name>BBCC**storyid**</name>
<title>**headline**</title>
<subtitle>**abstract**</subtitle>
<text>**body**</text>
<keywords>**people**</keywords>
<date>**pubdate**</date>
<durability>**durdate**</durability>
<category>**category**</category>
<subcategory>Famosos</subcategory>
<image>
<file format="image">**iloc**</file>
</image>
</news>
</videonews>
';
$tb = '';
$out = $tt;
foreach ($sa as $s) {
if ($s->uid == $uidtg) {
$tfn = "$locs/SpanishMix/" . $tfna[3];
$tmpt = str_replace('**body**', $s->body, $tm);
//$tmpt = str_replace('**vidfs**', $s->fs, $tmpt);
$tmpt = str_replace('**headline**', $s->headline, $tmpt);
$tmpt = str_replace('**people**', $s->people, $tmpt);
$tmpt = str_replace('**abstract**', $s->abstract, $tmpt);
$tmpt = str_replace('**storyid**', $s->storyid, $tmpt);
$tmpt = str_replace('**category**', $s->category, $tmpt);
$tmpt = str_replace('**pubdate**', $s->pubdate, $tmpt);
$tmpt = str_replace('**durdate**', $s->durdate, $tmpt);
$tmpt = str_replace('**iloc**', $s->iloc, $tmpt);
$copyA2 = explode('SpanishMix/', $s->iloc);
$copyImageFN = $copyA2[1];
$copyNewImageFN = 'digiv/' . $uidtg . '.jpg';
echo "\n ** trying replace $copyImageFN, $copyNewImageFN\n";
$tmpt = str_replace($copyImageFN, $copyNewImageFN, $tmpt);
$out .= "$tmpt\n\n";
}
}
$out .= $tb;
if ($uidtg) {
echo "</pre><TEXTAREA cols='120' rows='80'>$out</TEXTAREA>\n";
echo "<hr>";
$ox = '/var/www/SpanishMix/digiv/' . $uidtg . '.xml';
$written = file_put_contents($ox, $out);
echo "\nALSO putting : xml to $ox [", $written, "]<br>\n";
} else {
echo "\n NO UIDTG [", $uidtg, "] ! \n not putting any files";
}
I would really appreciate some help on this.

PHP Error 500 Internal Server Error in Codeigniter 3 When large Transaction

I have a problem when execute large transaction in Codeigniter 3.
I create transaction for migrating old data like below:
// Controller
public function migrate_document_get()
{
$this->benchmark->mark('code_start');
$data = $this->Delivery_order_model->read_data_class_from_stock();
foreach ($data as $obj) {
$parameters = $this->Delivery_order_model->read_data_for_do($obj->class_no);
$this->Delivery_order_model->create_data($parameters);
}
$this->benchmark->mark('code_end');
$data['message'] = "Finish migrate document DO";
$data['execution_time'] = round($this->benchmark->elapsed_time('code_start', 'code_end')) . " seconds";
$this->response($data, REST_Controller::HTTP_OK);
}
// Model
function create_data($data)
{
$error = array();
$affected_rows = 0;
$this->mysql->trans_start();
foreach ($data as $row) {
$sql_insert_product = "";
$class_no = $row['class_no'];
$article_vendor = $row['article_vendor'];
$style = $row['style'];
$sku_promo = $row['sku_promo'];
$retail = $row['retail'];
$unique_id = $this->generate_unique_id($class_no, $article_vendor, $style, $sku_promo, $retail);
$sku_no = $class_no . $unique_id . $style . $sku_promo . $retail;
$article_no = $class_no . $style . $sku_promo . $retail;
$res_field = $unique_id . $style . $sku_promo;
$format = array();
$format['dept_no'] = $row['dept_no'];
$format['class_no'] = $class_no;
$format['sku_no'] = $sku_no;
if (!empty($row['ref_no'])) {
$format['ref_no'] = $row['ref_no'];
}
$format['article_vendor'] = $article_vendor;
$format['article_no'] = $article_no;
$format['res_field'] = $res_field;
$format['style'] = $style;
$format['category_no'] = $row['category_no'];
$format['size_no'] = $row['size_no'];
$format['color_no'] = $row['color_no'];
$format['material_no'] = $row['material_no'];
$format['unique_id'] = $unique_id;
$format['sku_promo'] = $sku_promo;
if (!empty($row['exp_promo']) and $row['sku_promo'] != "00") {
$format['exp_promo'] = date('Y-m-d', strtotime(str_replace('/', '-', str_replace("'", "", $row['exp_promo']))));
}
$format['season_code'] = date('ym');
$format['retail'] = $retail;
$format['tag_type'] = $row['tag_type'];
if (!empty($row['image'])) {
$format['image'] = $row['image'];
}
$format['time_create'] = date('Y-m-d H:i:s');
$sql_insert_product = $this->mysql->insert_ignore_string("msr_product", $format);
// Transaction 1 -> INSERT msr_product
$this->mysql->query($sql_insert_product);
$sql_insert_do = "";
$format_doc = "DO" . $class_no . date('Ymd');
$do_id = $this->generate_do_id($format_doc);
$doc_no = $format_doc . $do_id;
$store_no = $row['store_no'];
// INSERT msr_do
$format_insert = array();
$format_insert['do_no'] = $doc_no;
$format_insert['store_no'] = $store_no;
$format_insert['sku_no'] = $sku_no;
$format_insert['do_date1'] = date('Y-m-d', strtotime(date('Ymd')));
$format_insert['do_date2'] = date('Y-m-d', strtotime('60 day', strtotime(date('Ymd'))));
$format_insert['do_status'] = 1;
$format_insert['user_input'] = $row['nik'];
$format_insert['ts_input'] = date('Y-m-d H:i:s');
$format_insert['status_item'] = 0;
$format_insert['qty_store'] = $row['qty'];
$format_update['qty_store'] = "qty_store + " . $row['qty'];
$sql_insert_do = $this->mysql->insert_on_duplicate_update_string("msr_do", $format_insert, $format_update, true, false);
// Transaction 2 -> INSERT msr_do
$this->mysql->query($sql_insert_do);
$affected_rows += $this->mysql->affected_rows();
}
$this->mysql->trans_complete();
if ($this->mysql->trans_status() === FALSE) {
$error = $this->mysql->error();
$error['sql_product'] = $sql_insert_product;
$error['sql_do'] = $sql_insert_do;
}
return $this->commonutil->format_output($affected_rows, $error);
}
When I execute method above in loop,
I facing an issue with error 500 internal server error.
but when I execute method like below one by one, not in the loop it's running normally.
// Controller
public function create_post()
{
$this->benchmark->mark('code_start');
$parameters = $this->post();
if (!empty($parameters)) {
$validate_param = $this->validate_parameter_create($parameters[0]);
if ($validate_param->run() == TRUE) {
$save = $this->Delivery_order_model->create_data($parameters);
if (!empty($save) and $save['total_affected'] > 0) {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_OK;
$output['error'] = false;
$output['message'] = "Success create delivery order list.";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_OK);
} else {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_NOT_MODIFIED;
$output['error'] = true;
$output['error_detail'] = $save['error'];
$output['message'] = "Failed create delivery order list!";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_NOT_MODIFIED);
}
} else {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_UNPROCESSABLE_ENTITY;
$output['error'] = true;
$output['error_detail'] = $validate_param->error_array();
$output['message'] = "Required JSON Array! [{.....}]";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_UNPROCESSABLE_ENTITY);
}
} else {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_UNPROCESSABLE_ENTITY;
$output['error'] = true;
$output['message'] = "Required parameters!";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_UNPROCESSABLE_ENTITY);
}
}
// Model
function create_data($data)
{
$error = array();
$affected_rows = 0;
$this->mysql->trans_start();
foreach ($data as $row) {
$sql_insert_product = "";
$class_no = $row['class_no'];
$article_vendor = $row['article_vendor'];
$style = $row['style'];
$sku_promo = $row['sku_promo'];
$retail = $row['retail'];
$unique_id = $this->generate_unique_id($class_no, $article_vendor, $style, $sku_promo, $retail);
$sku_no = $class_no . $unique_id . $style . $sku_promo . $retail;
$article_no = $class_no . $style . $sku_promo . $retail;
$res_field = $unique_id . $style . $sku_promo;
$format = array();
$format['dept_no'] = $row['dept_no'];
$format['class_no'] = $class_no;
$format['sku_no'] = $sku_no;
if (!empty($row['ref_no'])) {
$format['ref_no'] = $row['ref_no'];
}
$format['article_vendor'] = $article_vendor;
$format['article_no'] = $article_no;
$format['res_field'] = $res_field;
$format['style'] = $style;
$format['category_no'] = $row['category_no'];
$format['size_no'] = $row['size_no'];
$format['color_no'] = $row['color_no'];
$format['material_no'] = $row['material_no'];
$format['unique_id'] = $unique_id;
$format['sku_promo'] = $sku_promo;
if (!empty($row['exp_promo']) and $row['sku_promo'] != "00") {
$format['exp_promo'] = date('Y-m-d', strtotime(str_replace('/', '-', str_replace("'", "", $row['exp_promo']))));
}
$format['season_code'] = date('ym');
$format['retail'] = $retail;
$format['tag_type'] = $row['tag_type'];
if (!empty($row['image'])) {
$format['image'] = $row['image'];
}
$format['time_create'] = date('Y-m-d H:i:s');
$sql_insert_product = $this->mysql->insert_ignore_string("msr_product", $format);
// Transaction 1 -> INSERT msr_product
$this->mysql->query($sql_insert_product);
$sql_insert_do = "";
$format_doc = "DO" . $class_no . date('Ymd');
$do_id = $this->generate_do_id($format_doc);
$doc_no = $format_doc . $do_id;
$store_no = $row['store_no'];
// INSERT msr_do
$format_insert = array();
$format_insert['do_no'] = $doc_no;
$format_insert['store_no'] = $store_no;
$format_insert['sku_no'] = $sku_no;
$format_insert['do_date1'] = date('Y-m-d', strtotime(date('Ymd')));
$format_insert['do_date2'] = date('Y-m-d', strtotime('60 day', strtotime(date('Ymd'))));
$format_insert['do_status'] = 1;
$format_insert['user_input'] = $row['nik'];
$format_insert['ts_input'] = date('Y-m-d H:i:s');
$format_insert['status_item'] = 0;
$format_insert['qty_store'] = $row['qty'];
$format_update['qty_store'] = "qty_store + " . $row['qty'];
$sql_insert_do = $this->mysql->insert_on_duplicate_update_string("msr_do", $format_insert, $format_update, true, false);
// Transaction 2 -> INSERT msr_do
$this->mysql->query($sql_insert_do);
$affected_rows += $this->mysql->affected_rows();
}
$this->mysql->trans_complete();
if ($this->mysql->trans_status() === FALSE) {
$error = $this->mysql->error();
$error['sql_product'] = $sql_insert_product;
$error['sql_do'] = $sql_insert_do;
}
return $this->commonutil->format_output($affected_rows, $error);
}
I already resizing on DB temp space
and I already check the method it's running normally
what's wrong with that, please give me some advice.

How to find and make sum of different numbers from array?

I've read some texts and searched topics, but nothing help me. I'm beginner in PHP. I have array where are variables $qA01_1 up to $qA30_5 and their values can be different 0 or 1 or 5. From array I would like to find all variables with value 1 and make sum. Same for number 5.
$qA01_1 = $_SESSION['qA01_1'];
$qA01_2 = $_SESSION['qA01_2'];
$qA01_3 = $_SESSION['qA01_3'];
$qA01_4 = $_SESSION['qA01_4'];
$qA01_5 = $_SESSION['qA01_5'];
$qA02_1 = $_SESSION['qA02_1'];
$qA02_2 = $_SESSION['qA02_2'];
$qA02_3 = $_SESSION['qA02_3'];
$qA02_4 = $_SESSION['qA02_4'];
$qA02_5 = $_SESSION['qA02_5'];
$qA03_1 = $_SESSION['qA03_1'];
$qA03_2 = $_SESSION['qA03_2'];
$qA03_3 = $_SESSION['qA03_3'];
$qA03_4 = $_SESSION['qA03_4'];
$qA03_5 = $_SESSION['qA03_5'];
$qA04_1 = $_SESSION['qA04_1'];
$qA04_2 = $_SESSION['qA04_2'];
$qA04_3 = $_SESSION['qA04_3'];
$qA04_4 = $_SESSION['qA04_4'];
$qA04_5 = $_SESSION['qA04_5'];
$qA05_1 = $_SESSION['qA05_1'];
$qA05_2 = $_SESSION['qA05_2'];
$qA05_3 = $_SESSION['qA05_3'];
$qA05_4 = $_SESSION['qA05_4'];
$qA05_5 = $_SESSION['qA05_5'];
$qA06_1 = $_SESSION['qA06_1'];
$qA06_2 = $_SESSION['qA06_2'];
$qA06_3 = $_SESSION['qA06_3'];
$qA06_4 = $_SESSION['qA06_4'];
$qA06_5 = $_SESSION['qA06_5'];
$qA07_1 = $_SESSION['qA07_1'];
$qA07_2 = $_SESSION['qA07_2'];
$qA07_3 = $_SESSION['qA07_3'];
$qA07_4 = $_SESSION['qA07_4'];
$qA07_5 = $_SESSION['qA07_5'];
$qA08_1 = $_SESSION['qA08_1'];
$qA08_2 = $_SESSION['qA08_2'];
$qA08_3 = $_SESSION['qA08_3'];
$qA08_4 = $_SESSION['qA08_4'];
$qA08_5 = $_SESSION['qA08_5'];
$qA09_1 = $_SESSION['qA09_1'];
$qA09_2 = $_SESSION['qA09_2'];
$qA09_3 = $_SESSION['qA09_3'];
$qA09_4 = $_SESSION['qA09_4'];
$qA09_5 = $_SESSION['qA09_5'];
$qA10_1 = $_SESSION['qA10_1'];
$qA10_2 = $_SESSION['qA10_2'];
$qA10_3 = $_SESSION['qA10_3'];
$qA10_4 = $_SESSION['qA10_4'];
$qA10_5 = $_SESSION['qA10_5'];
$qA11_1 = $_SESSION['qA11_1'];
$qA11_2 = $_SESSION['qA11_2'];
$qA11_3 = $_SESSION['qA11_3'];
$qA11_4 = $_SESSION['qA11_4'];
$qA11_5 = $_SESSION['qA11_5'];
$qA12_1 = $_SESSION['qA12_1'];
$qA12_2 = $_SESSION['qA12_2'];
$qA12_3 = $_SESSION['qA12_3'];
$qA12_4 = $_SESSION['qA12_4'];
$qA12_5 = $_SESSION['qA12_5'];
$qA13_1 = $_SESSION['qA13_1'];
$qA13_2 = $_SESSION['qA13_2'];
$qA13_3 = $_SESSION['qA13_3'];
$qA13_4 = $_SESSION['qA13_4'];
$qA13_5 = $_SESSION['qA13_5'];
$qA14_1 = $_SESSION['qA14_1'];
$qA14_2 = $_SESSION['qA14_2'];
$qA14_3 = $_SESSION['qA14_3'];
$qA14_4 = $_SESSION['qA14_4'];
$qA14_5 = $_SESSION['qA14_5'];
$qA15_1 = $_SESSION['qA15_1'];
$qA15_2 = $_SESSION['qA15_2'];
$qA15_3 = $_SESSION['qA15_3'];
$qA15_4 = $_SESSION['qA15_4'];
$qA15_5 = $_SESSION['qA15_5'];
$qA16_1 = $_SESSION['qA16_1'];
$qA16_2 = $_SESSION['qA16_2'];
$qA16_3 = $_SESSION['qA16_3'];
$qA16_4 = $_SESSION['qA16_4'];
$qA16_5 = $_SESSION['qA16_5'];
$qA17_1 = $_SESSION['qA17_1'];
$qA17_2 = $_SESSION['qA17_2'];
$qA17_3 = $_SESSION['qA17_3'];
$qA17_4 = $_SESSION['qA17_4'];
$qA17_5 = $_SESSION['qA17_5'];
$qA18_1 = $_SESSION['qA18_1'];
$qA18_2 = $_SESSION['qA18_2'];
$qA18_3 = $_SESSION['qA18_3'];
$qA18_4 = $_SESSION['qA18_4'];
$qA18_5 = $_SESSION['qA18_5'];
$qA19_1 = $_SESSION['qA19_1'];
$qA19_2 = $_SESSION['qA19_2'];
$qA19_3 = $_SESSION['qA19_3'];
$qA19_4 = $_SESSION['qA19_4'];
$qA19_5 = $_SESSION['qA19_5'];
$qA20_1 = $_SESSION['qA20_1'];
$qA20_2 = $_SESSION['qA20_2'];
$qA20_3 = $_SESSION['qA20_3'];
$qA20_4 = $_SESSION['qA20_4'];
$qA20_5 = $_SESSION['qA20_5'];
$qA21_1 = $_SESSION['qA21_1'];
$qA21_2 = $_SESSION['qA21_2'];
$qA21_3 = $_SESSION['qA21_3'];
$qA21_4 = $_SESSION['qA21_4'];
$qA21_5 = $_SESSION['qA21_5'];
$qA22_1 = $_SESSION['qA22_1'];
$qA22_2 = $_SESSION['qA22_2'];
$qA22_3 = $_SESSION['qA22_3'];
$qA22_4 = $_SESSION['qA22_4'];
$qA22_5 = $_SESSION['qA22_5'];
$qA23_1 = $_SESSION['qA23_1'];
$qA23_2 = $_SESSION['qA23_2'];
$qA23_3 = $_SESSION['qA23_3'];
$qA23_4 = $_SESSION['qA23_4'];
$qA23_5 = $_SESSION['qA23_5'];
$qA24_1 = $_SESSION['qA24_1'];
$qA24_2 = $_SESSION['qA24_2'];
$qA24_3 = $_SESSION['qA24_3'];
$qA24_4 = $_SESSION['qA24_4'];
$qA24_5 = $_SESSION['qA24_5'];
$qA25_1 = $_SESSION['qA25_1'];
$qA25_2 = $_SESSION['qA25_2'];
$qA25_3 = $_SESSION['qA25_3'];
$qA25_4 = $_SESSION['qA25_4'];
$qA25_5 = $_SESSION['qA25_5'];
$qA26_1 = $_SESSION['qA26_1'];
$qA26_2 = $_SESSION['qA26_2'];
$qA26_3 = $_SESSION['qA26_3'];
$qA26_4 = $_SESSION['qA26_4'];
$qA26_5 = $_SESSION['qA26_5'];
$qA27_1 = $_SESSION['qA27_1'];
$qA27_2 = $_SESSION['qA27_2'];
$qA27_3 = $_SESSION['qA27_3'];
$qA27_4 = $_SESSION['qA27_4'];
$qA27_5 = $_SESSION['qA27_5'];
$qA28_1 = $_SESSION['qA28_1'];
$qA28_2 = $_SESSION['qA28_2'];
$qA28_3 = $_SESSION['qA28_3'];
$qA28_4 = $_SESSION['qA28_4'];
$qA28_5 = $_SESSION['qA28_5'];
$qA29_1 = $_SESSION['qA29_1'];
$qA29_2 = $_SESSION['qA29_2'];
$qA29_3 = $_SESSION['qA29_3'];
$qA29_4 = $_SESSION['qA29_4'];
$qA29_5 = $_SESSION['qA29_5'];
$qA30_1 = $_POST['qA30_1'];
$qA30_2 = $_POST['qA30_2'];
$qA30_1 = (isset($_POST['qA30_1'])) ? $_POST['qA30_1'] : 0;
$qA30_2 = (isset($_POST['qA30_2'])) ? $_POST['qA30_2'] : 0;
$qA30_3 = (isset($_POST['qA30_3'])) ? $_POST['qA30_3'] : 0;
$qA30_4 = (isset($_POST['qA30_4'])) ? $_POST['qA30_4'] : 0;
$qA30_5 = (isset($_POST['qA30_5'])) ? $_POST['qA30_5'] : 0;
Here is my proposal which do not work. I thing that I should to do something with "array" .
// Sum of all numbers 1
$sumOne = 0;
for ($i = 0; $i <= 3; $i++) {
for($j = 0; $j <= 9; $j++) {
for($k = 1; $k <= 5; $k++){
$u = 'qA_' . $i . $j. '_' . $k;
if ($u==1){
$sumOnet+=1;
}
}
}
}
echo "<br/>SumOne:" . " " . round($sumOne[0], 0);
You really should stick with an array. If you define an array within the $_SESSION array and use that it will be much simpler:
$_SESSION['data']['qA01_1'] = 0;
$_SESSION['data']['qA01_2'] = 1;
$_SESSION['data']['qA01_3'] = 5;
$counts = array_count_values($_SESSION['data']);
if(isset($counts[0])) { echo $counts[0]; } // sum of any 0s is 0 so here is the count
if(isset($counts[1])) { echo $counts[1]; } // sum of any 1s will be the count
if(isset($counts[5])) { echo $counts[5] * 5; }
If I understand the question correctly, you want to sum up all individual values in your array.
You can use array_count_values() for that, it returns you the number of occurances of each value where the value itself is the key:
foreach (array_count_values($_SESSION) as $value => $count) {
echo 'sum of ' . $value . ' values: ' . ($value * $count) . "<br>";
}
No idea where the POST variables fit in though...

unable to save looped data from excel in cakephp

$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.

Previous/next button in PHP

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!

Categories