vendredi 29 mai 2015

Get Bot Margin to AddPage - FPDF

My PDF file is a table completed with values from a server.
And if the next line created is too large to display on the end of the page, I want to add a new page, then insert my new line.

I guess I must do some maths with $height_of_cell (which I calculate), getY() and margin-bottom but I don't know, and I didn't find how to get this last value.
Does anyone know ? Thank you !

Laravel 4.2 - PHP Error reporting turned off

My Laravel 4.2 application runs happily with undefined variables or array indexes.

I have placed

ini_set('display_errors',1);
error_reporting(E_ALL|E_STRICT);

in many places in my code in an attempt to get this happen.

The php.ini contains

error_reporting = E_ALL

Debugging is true in app.php.

I have grep'd all of the Laravel and vendor code and my code to look for locations where error reporting may have been turned off, but none seems relevant.

Non-Laravel web applications on the same server crash and/or report properly for these kinds of errors.

PHP is 5.6.8 on Fedora and 5.5. on Centos.

connecting to MS access with php when defined password for database

I am trying to connect Ms Access DataBase from php . My codes like this in config.php

 define('DBNAMEACCESS',  '\\'."\\xxx.xxx.xxx.xxx\\test\\test.accdb");
        define('DBACCESSPASSWORD', 'mypassword');
        define('DBACCESSUSERNAME', '');

and in process.php like this:

     include './config.php';
   if (!file_exists(DBNAMEACCESS)) {
            die("Could not find database file.");
        }
 try{
            $dbName=DBNAMEACCESS;
            $username=DBACCESSUSERNAME;
            $password=DBACCESSPASSWORD;
             $dba = odbc_connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=$dbName",$username, $password);

   if ($dba) {
/*......*/
} else
            {
                die("Could not connect to access database");
            }
             }
        catch (Exception $ex) {
//            var_export($ex);
                setmessage($ex) ;
        }

when the password is defined for access file , I get this error on this line: My error: odbc_connect(): SQL error: [Microsoft][ODBC Microsoft Access Driver] Cannot open database '(unknown)'. It may not be a database that your application recognizes, or the file may be corrupt., SQL state S1000 in SQLConnect in this line

         $dba = odbc_connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=$dbName",$username, $password);

and when the password is not defined for access file,My codes execute correctly.

CSS IDs not working when extension is hidden

I developed my site with extensions visible, but when I finished and wanted to make it to production. Now I did a htaccess to hide extensions and add a trailing slash, when people click on a button which redirects/links to #tab1, the url becomes: http://ift.tt/1FHzXSQ

And the CSS ID doesn't open up (the tab).

Is there a way to fix this?

Thanks in advance

zend gdata and google spreadsheet not connecting

ive been using Zend Gdata for a while now, and today im getting an error of

Notice: Undefined offset: ClientLogin.php on line 150

via php, this has been working for a while now, and today without changing anything it stopped working, im guessing some deprecated service on behalf of google with the zend gdata maybe the Zend_Gdata_ClientLogin::getHttpClient( ) method or something, can any one confirm or help me with this issue. the code im using to connect is as follows:

    require_once('Zend/Loader.php');
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Docs');
Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');
require_once 'Zend/Gdata.php';
require_once 'Zend/Gdata/AuthSub.php';
require_once 'Zend/Gdata/Spreadsheets.php';
require_once 'Zend/Gdata/Spreadsheets/DocumentQuery.php';
require_once 'Zend/Gdata/Spreadsheets/ListQuery.php';
require_once 'Zend/Loader.php';


$sourceUser = "myemail";
$sourcePass = "mysuperawesomepassword";
$service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$sourceClient = Zend_Gdata_ClientLogin::getHttpClient($sourceUser, $sourcePass, $service);
$connection = new Zend_Gdata_Spreadsheets($sourceClient);

i am using the zend gdata with the google spreadsheets

also the error points specifically to this line

$sourceClient = Zend_Gdata_ClientLogin::getHttpClient($sourceUser, $sourcePass, $service);

as i said, i was using this for a while now, and nothing has changed on my end

foreach loop in json encode array

I am sending preformatted HTMl with AJAX JSON, JSON have below code,

I am trying pull data array from DB and echoing array data, I am not able to put foreach loop in json_encode, because seems my code is wrong at foreach loop,

How can i achieve that?

echo json_encode(array('returnnews' => '<div class="news-item-page">
                                    <h3 class="text-info" style="margin-top:0">'.$latestnews->news_subject.'</h3>
                                    '.$latestnews->news_content.'


                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <ul class="list-inline blog-tags">
                                            <li>
                                                <i class="fa fa-tags"></i>'.
                                                foreach($news_tag_array as $tag){
                                                <a href="javascript:;">
                                                echo $tag </a>
                                               }

                                            </li>
                                        </ul>
                                    </div>
                               </div>'));

Zend Form ->addValidator('Digits') not working

I am trying to add validator to my Text field as i am expecting user to only enter positive integers. But its not working neither showing any error message if we enter value like '-50'. The code is, $AddInventory = new Zend_Form_Element_Text('AddInventory'); $AddInventory->setAttrib('dojoType',"dijit.form.ValidationTextBox");
$AddInventory->setAttrib('maxlength','40') ->setAttrib('style','width:200px') ->setAttrib('required',"false") ->addValidator('NotEmpty') ->addFilter('StripTags') ->addValidator('Digits')
->removeDecorator("DtDdWrapper") ->removeDecorator("Label") ->removeDecorator('HtmlTag');

Ajax call onSubmit not working

I have a log-in form. Before do the log-in I would like to make sure that username and password are true.. I am trying to achieve this with ajax, but so far it is not working..

in my form I am calling the function check_user onSubmit. This is my code.

    function check_user(e){
        var username = $('#username').val();
        var password = $('#password').val();

        if(username.length>1 && password.length>1){
        e.preventDefault(); // I added this but still it is not working
        alert('alive'); // this is working          

                jQuery.ajax({
                    type : "POST",
                    url : "check_user.php",
                    data : 'username=' + username +"&password=" + password,
                    cache : false,
                    success : function(response) {
                        if (response == 1) {
                        return true;                    
                        } else {        
                        $('#username').css('border', '2px red solid');
                        document.getElementById("username").placeholder = "Wrong username or password";
                        $('#password').css('border', '2px red solid');
                        document.getElementById("password").placeholder = "Wrong username or password";                     
                        return false;                   
                        }
                    }
                });     
        }else{
//this is working
            $('#username').css('border', '2px red solid');
            document.getElementById("username").placeholder = "Wrong username or password";
            $('#password').css('border', '2px red solid');
            document.getElementById("password").placeholder = "Wrong username or password";
            return false;   
        }
    }

In my PHP file check_user.php I have also this code:

$fp = fopen("debug.txt", "a") or die("Couldn't open log file for writing.");
        fwrite($fp, PHP_EOL ."inside");
        fflush($fp);
        fclose($fp);

No debug.txt is created so I assume that the ajax call never happens..

I use the same ajax code when doing the registration to check if the username or email already exists in the database, and the ajax there is working ok. In my example the ajax call never happens and it goes straight to the action="login.php"

Build PHP array with string and result 2 dimensional arrays

I have a smart problem in PHP, I build an array with a string, and at the same time I cut some images. buildProject.php is include in index.php (session_start(); for _session is on the top of it).

buildProject.php

<?php
  $list_projet = array(
    0 => 'img0_pres',
    1 => 'img1_pres',
    2 => 'img2_pres',
  );
  $height_decoup = 500;
  $projet = array();

  foreach ($list_projet as $key => $value) {
    $name_source = $value;
    $img_source_file = 'images/projet/'.$name_source.'.jpg';
    $img_source = imagecreatefromjpeg($img_source_file);

    $width = imagesx($img_source);
    $height = imagesy($img_source);
    $ratio = ceil($height/$height_decoup);
    $img_dest_height = $height_decoup;

    $nb_img_decoup = 1;
    $img_source_y = 0;

    while ($nb_img_decoup <= $ratio) {
      if ($nb_img_decoup == $ratio) {
        $img_dest_height = $height - $height_decoup*($ratio-1);
      }
      $img_dest = imagecreatetruecolor($width,$img_dest_height);
      imagecopy($img_dest, $img_source, 0, 0, 0, $img_source_y, $width, $img_dest_height);
      $img_dest_file = 'images/projet/'.$name_source.'_'.$nb_img_decoup.'.jpg';
      imagejpeg($img_dest, $img_dest_file);

      $projet[$key][$nb_img_decoup] = $img_dest_file; // I SUPPOSE AN ERROR HERE
      $img_source_y += $height_decoup;
      $nb_img_decoup++;
    }
    imagedestroy($img_source);
    imagedestroy($img_dest);
  }
  echo $img_dest_file[0]; // give me an 'i' and suppose give me an error
  echo $projet[0][1][0]; // idem...

  $_SESSION['txt'] = $projet;
?>

After build it, I send it to getProjet.php to find it on main.js with getJSON. My Probleme is $img_dest_file transform alone in array and i need a string!

I thinks the problem is on buildProject.php but I put the other files maybe there are an other error can do that.

getProject.php

<?php
session_start();
$projet = $_SESSION['txt'];

if(isset($_GET['list']) && $_GET['list']>=0){
    echo json_encode($projet[$_GET['list']]);
} ?>

main.js

$.getJSON('php/getProject.php?list=' + index, function(data) {
    length = data.length;
    console.log(data+' //// '+length); // [object object] //// undefined
    console.log(data[1].length); // 29 (total of caracteres...)
    console.log(data[1]); // images/projet/img0_pres_1.jpg
    console.log(data[1][0]); // i
}

So in main.js data=([object object]) and I need data=([object]). I think it's because when i run buildProject.php $img_dest_file transform alone in array and it's normaly just a string not an array.

If someone has an idea why $img_dest_file transform alone in array?

Thanks for reading. If you have question I can specify more.

CSS not being executed in Woocommerce Wordpress template file

I have a fully functional Wordpress custom theme. I have just installed Woocommerce and followed this guide. I have followed the very basic instructions to copy page.php, rename it and modify the loop. I have done this and am able to use Woocommerce, however in the page.php file, I have a

<?php get_header(); ?>

command, which successfully displays that part of the layout in my normal wordpress pages. However, in the direct clone which is now called woocommerce.php, it is not working fully, The links show up, but without any of the associated css which is linked into the header file. Any ideas why two versions of the same file would mean only one correctly imports / interprets the css?

Here are the two web pages:

http://ift.tt/1KhbKno
http://ift.tt/1eCIbmf

Google Calendar API Time

When I try to format 2015-05-29T19:30:00+08:00 from google calendar api;

return \Carbon\Carbon::createFromTimeStamp(
        strtotime('2015-05-29T19:30:00+08:00')
        );

I get the result 2015-05-29 11:30:00 But the start date of the event in my google calendar is exactly 07:30PM One thing is that if I try to add a ->diffForHumans(); I get the result:

16 minutes ago (Note: the time I run the code is 7:46PM)

Can you help me to understand what is going on in here.

DOMDocument cannot change parentNode

I cannot change the DOMDocument parentNode from null. I have tried using both appendChild and replaceChild, but haven't had any luck.

Where am I going wrong here?

   error_reporting(E_ALL);

   function xml_encode($mixed, $DOMDocument=null) {
      if (is_null($DOMDocument)) {
          $DOMDocument =new DOMDocument;
          $DOMDocument->formatOutput = true;
          xml_encode($mixed, $DOMDocument);
          echo $DOMDocument->saveXML();
      } else {
          if (is_array($mixed)) {
              $node = $DOMDocument->createElement('urlset', 'hello');
              $DOMDocument->appendChild($node);
          }
      }
  }

  $data = array();

  for ($x = 0; $x <= 10; $x++) {
      $data['urlset'][] = array(
         'loc' => 'http://ift.tt/1FXudUi',
         'lastmod' => 'YYYY-MM-DD',
         'changefreq' => 'monthly',
         'priority' => 0.5
      );
  }

  header('Content-Type: application/xml');
  echo xml_encode($data);

?>

http://ift.tt/1FHzXCe

ZendX_JQuery_Form_Element_DatePicker doesn´t work

My datepicker doesn't work. I don't get any errors and instead of the datepicker appearing, my field looks like a dropdown and shows the formerly used dates.

I added to my bootstrap:

protected function _InitAutoload()
    {
        $view= new Zend_View();
        $viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
        $view->addHelperPath(’ZendX/JQuery/View/Helper/’, ‘ZendX_JQuery_View_Helper’);
        $viewRenderer->setView($view);
        Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
    }

I changed my datefield in my formclass like follows:

$datum= new ZendX_JQuery_Form_Element_DatePicker("datum", '',
                    array('defaultDate' => date('Y/m/d', time()))); 

My formclass extends ZendX_JQuery_Form.

In my layout.phtml I added:

$this->jQuery()->setLocalPath('http://localhost/zend/js/jquery/jquery-1.2.6.js')
 ->addStylesheet('http://localhost/zend/js/jquery/themes/ui.datepicker.css');
echo $this->jQuery();

Where is my error? Is there something missing somewhere?

Running code on every kernel boot

I would like a bundle to run code on every boot of the Symfony kernel. Is there a way to accomplish this? I need to be able to use the bundle configuration, therefore the constructor of the bundle class is not an option. Adding an event listener to kernel.request would be an option but it does not work for console scripts.

Multi mysql query returns Commands out of sync

i've created below function which include several mysql queries, which seem to create an issue. Cause when i run this function it returns following error:

Errormessage: Commands out of sync; you can't run this command now

i've tried to include next_result(), but does not do any difference?

function retrievePlayerTweets(){
    global $con;
    $query = $con->prepare("Select players.fullname, players.twitter_user, team.id as teamId FROM players, team WHERE players.teamId = team.id");
    $query->execute();
    $query->bind_result($fullname, $twitter_user, $teamId);

    while ($query->fetch()) {

        foreach(retrieveUserTweets($twitter_user) as $twitterData) {
            $id = $twitterData['id_str'];
            $text = $twitterData['text'];
            $name = $twitterData['user']['name'];
            $dateString = $twitterData['created_at'];
            $favoriteCount = $twitterData['favorite_count'];
            $date = date('Y-m-d H:i:s', strtotime($dateString));



                if ($insert_tweet = $con->prepare("INSERT IGNORE INTO tweets (`fullname`, `username`, `text`, `created`, `teamId`, `twitterId`, `favoriteCount`) VALUES (?, ?, ?, ?, ?, ?, ?)")) {

                    $insert_tweet->bind_param("ssssisi", $name, $twitter_user, $text, $date, $teamId, $id, $favoriteCount);
                    $insert_tweet->execute();
                    $con->next_result();

                } else {
                    die("Errormessage: ". $con->error);
                }






}

PHP SQL Server ODBC Driver

Trying to connect to a remote SQL Server (2008) on local network through a PHP (5.6.7) script running with MAMP on Mac OS Yosemite. I ran through the tutorial here.

I am was able to install and configure successfully. I can connect to SQL SErver through terminal services and query and pull data through 'isql'.

However, I can't seem to figure out how to enable the driver in php. I don't see the odbc.so extension file in the extensions folder, where I think it should be (then enabled in .ini file). Any ideas?

function broke after updating PHP

I have a little problem with a function which doesn't seem to fully work in new php version and I receive

Notice: String offset cast occurred in D:\xampp\htdocs\decode\bencoded.php on line 266
Notice: String offset cast occurred in D:\xampp\htdocs\decode\bencoded.php on line 270

Here is my function:

function bdecode($s, &$pos=0) {
  if($pos>=strlen($s)) {
    return null;
  }
  switch($s[$pos]){
  case 'd':
    $pos++;
    $retval=array();
    while ($s[$pos]!='e'){
      $key=bdecode($s, $pos);
      $val=bdecode($s, $pos);
      if ($key===null || $val===null)
        break;
      $retval[$key]=$val;
    }
    $retval["isDct"]=true;
    $pos++;
    return $retval;

  case 'l':
    $pos++;
    $retval=array();
    while ($s[$pos]!='e'){
      $val=bdecode($s, $pos);
      if ($val===null)
        break;
      $retval[]=$val;
    }
    $pos++;
    return $retval;

  case 'i':
    $pos++;
    $digits=strpos($s, 'e', $pos)-$pos;
    // Proger_XP: changed (int) -> (float) to avoid trimming of values exceeding
    //            signed int's max value (2147483647).
    $val=(float)substr($s, $pos, $digits);
    $pos+=$digits+1;
    return $val;

//  case "0": case "1": case "2": case "3": case "4":
//  case "5": case "6": case "7": case "8": case "9":
  default:
    $digits=strpos($s, ':', $pos)-$pos;
    if ($digits<0 || $digits >20)
      return null;
    $len=(float)substr($s, $pos, $digits);
    $pos+=$digits+1;
    $str=substr($s, $pos, $len);
    $pos+=$len;
    //echo "pos: $pos str: [$str] len: $len digits: $digits\n";
    return (string)$str;
  }
  return null;
}

i understand that i get a warning in the new php, but i have no idea how to fix it.

line 266 (before case 'd'): switch($s[$pos]){

line 270 (after case '1'): while ($s[$pos]!='e'){

eajaxupload for Yii always "failed"

We are currently trying to use the extension eajaxupload for Yii but it seems to be outputting failed everytime we try to upload a file.

We have tried

a) editing the file / minimum file sizes

b) playing around with the file path (may still be incorrect, if anyone knows what the path for locally using in xampp would be, let us know. Our uploads folder is in the root of the project.)

c) changing the htiaccess php file

d) permissions

we just don't know if the code itself is appearing wrong.

controller

/* UPLOADER */
    public function actionUpload(){
        Yii::import("ext.EAjaxUpload.qqFileUploader");
//        $folder = '/uploads/';
//        $folder=Yii::getPathOfAlias() .'/upload/';
        $folder=Yii::app()->baseUrl . '/uploads/';
        $allowedExtensions = array("jpg","png");//array("jpg","jpeg","gif","exe","mov" and etc...
        $sizeLimit = 10 * 1024 * 1024;// maximum file size in bytes
        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
        $result = $uploader->handleUpload($folder);
//        $return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
// 
//        $fileSize=filesize($folder.$result['filename']);//GETTING FILE SIZE
//        $fileName=$result['filename'];//GETTING FILE NAME
// 
//        echo $return;// it's array

        $result = $uploader->handleUpload($folder);

        $fileSize=filesize($folder.$result['filename']);//GETTING FILE SIZE
        $fileName=$result['filename'];//GETTING FILE NAME
        $result=htmlspecialchars(json_encode($result), ENT_NOQUOTES);

        echo $result;// it's array
    }

View

*$this->widget('ext.EAjaxUpload.EAjaxUpload',
                array(
                    'id'=>'uploadFile',
                    'config'=>array(
                        'action'=>'/upload/',
//                        'action'=>Yii::app()->createUrl('controllers/uploads/'),
                        'allowedExtensions'=>array("jpg","png"),//array("jpg","jpeg","gif","exe","mov" and etc...
                        'sizeLimit'=>10*1024*1024,// maximum file size in bytes
                        //'minSizeLimit'=>10*1024*1024,// minimum file size in bytes
                        'onComplete'=>"js:function(id, fileName, responseJSON){ alert(fileName); }",
                        'messages'=>array(
                            'typeError'=>"{file} has invalid extension. Only {extensions} are allowed.",
                            'sizeError'=>"{file} is too large, maximum file size is {sizeLimit}.",
                            'minSizeError'=>"{file} is too small, minimum file size is {minSizeLimit}.",
                            'emptyError'=>"{file} is empty, please select files again without it.",
                            'onLeave'=>"The files are being uploaded, if you leave now the upload will be cancelled."
                        ),
                        'showMessage'=>"js:function(message){ alert(message); }"

                    )*

Fullcalendar returning epoch time values to the database

I am using fullcalendar jquery plugin for my page.When i'm inserting new events using the fullcalendar plugin.., its returning me epoch time values instead of UTC timedate values.

Below is the code that inserts new data into the database on clicking a date.

    calendar.fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },
        editable: true,
        droppable: true, // this allows things to be dropped onto the calendar
        drop: function() {
            // is the "remove after drop" checkbox checked?
            if ($('#drop-remove').is(':checked')) {
                // if so, remove the element from the "Draggable Events" list
                $(this).remove();
            }
        },

        eventSources: [

            {

                url: '/v1/calendar/',
                type: 'GET',
                dataType:'json',


            },
           calendar.fullCalendar( 'addEventSource', response )
        ],

        selectable: true,
        selectHelper: true,
        select: function(start, end, allDay) {

            bootbox.prompt("New Event Title:", function(title) {
                var people_id=1;
                //var title=event.title;
                //var start=event.start;
                //var end=event.end;

                if (title !== null) {
                    calendar.fullCalendar('renderEvent',
                            {
                                people_id:people_id,
                                title: title,
                                start: start,
                                end: end,
                                allDay: allDay
                            },

                    true // make the event "stick"


                            );






                            $.ajax({
                                 url: '/v1/calendar',
                                 data: 'people_id='+people_id+'&title='+title+'&start='+start+'&end='+end,

                                 type: 'POST',
                                 dataType: 'json',
                                 success: function(response){
                                     bootbox.alert("Event Created!");

                                   console.log(response);
                                 },
                                 error: function(e){
                                   console.log(e.responseText);
                                 }
                               });  

                }
            });

The event is successfully added into the database...but the time is in epoch format.

the console response I'm getting is given below:

     {people_id: "1", evt_description: "testing", date1: "1431388800000", date2: "1431475200000", event_id: 4}

I'm using laravel framework at the backend I'm attaching my CalendarController below:

    <?php

class CalendarController extends \BaseController {

/**
 * Display a listing of calendar
 *
 * @return Response
 */
public function index()
{
    $event = DB::table('events')

    ->leftJoin('people','people.people_id','=','events.people_id')  
    ->leftJoin('people_roles','people_roles.people_id','=','events.people_id')      
    ->get(array('events.people_id','events.event_id','events.evt_description','events.date1','events.date2','events.time'));    
    //return View::make('people.show', compact('address'));
    //return Response::json($event);
    $id=array();
    $title=array();
    $start=array();
    $end=array();
    $i=0;
    foreach ($event as $events)
        {

            $id[$i]=$events->event_id;
            $title[$i]=$events->evt_description;
            $start[$i]=$events->date1;
            $end[$i]=$events->date2;
            $i++;           
        }
    return Response::json(array('id'=>$id,'title'=>$title,'start'=>$start,'end'=>$end));
}

/**
 * Show the form for creating a new calendar
 *
 * @return Response
 */
public function create()
{
    return View::make('calendar.create');
}

/**
 * Store a newly created calendar in storage.
 *
 * @return Response
 */
public function store()
{
    $events= Input::get('type');
    $events= new Events;
    $events->people_id = Input::get('people_id');
    $events->evt_description =Input::get('title');
    $events->date1 =Input::get('start');
    $events->date2 =Input::get('end');
    //$events->time =Input::get('time');

    $events->save();


    return Response::json($events);
    //return Redirect::route('calendar.index');
}

/**
 * Display the specified calendar.
 *
 * @param  int  $id
 * @return Response
 */
public function show($id)
{
    $calendar = Calendar::findOrFail($id);

    return View::make('calendar.show', compact('calendar'));
}

/**
 * Show the form for editing the specified calendar.
 *
 * @param  int  $id
 * @return Response
 */
public function edit($id)
{
    $calendar = Calendar::find($id);

    return View::make('calendar.edit', compact('calendar'));
}

/**
 * Update the specified calendar in storage.
 *
 * @param  int  $id
 * @return Response
 */
public function update($id)
{
    //$type=Input::get('type');
    $event_id= Input::get('event_id');
    $title= Input::get('title');
    $roles = DB::table('events')
                ->where('event_id','=',$event_id )
                ->update(array('evt_description' => $title));
    return Response::json(array('id'=>$event_id,'title'=>$title));



}

/**
 * Remove the specified calendar from storage.
 *
 * @param  int  $id
 * @return Response
 */
public function destroy()
{
//  Calendar::destroy($id);
$event_id= Input::get('eventid');
DB::table('events')->where('event_id','=',$event_id)->delete();

return Response::json($event_id);

//  return Redirect::route('calendar.index');
}

}

MySQL query runs ok in phpadmin but hangs in php

I have a fairly simple query which runs okay when I test it in phpMyAdmin:

   SELECT   
        c.customers_id,
        c.customers_cid,
        c.customers_gender,
        c.customers_firstname,
        c.customers_lastname,
        c.customers_email_address,
        c.customers_telephone,
        c.customers_date_added,
        ab.entry_company,
        ab.entry_street_address,
        ab.entry_postcode, 
        ab.entry_city,
        COUNT(o.customers_id) AS orders_number,
        SUM(ot.value) AS totalvalue, 
        mb.bonus_points
   FROM     
        orders AS o,
        orders_total AS ot,
        customers AS c, 
        address_book AS ab, 
        module_bonus AS mb
   WHERE 
        c.customers_id = o.customers_id 
        AND c.customers_default_address_id = ab.address_book_id 
        AND c.customers_id = mb.customers_id    
        AND o.orders_id = ot.orders_id 
        AND ot.class = 'ot_subtotal'    
 **  AND c.customers_gender  = 'm' AND c.customers_lastname LIKE 'Famlex'
    GROUP BY o.customers_id

The row marked with ** changes depending on filtering settings of the application making the query.

Now, when I test this in phpMyAdmin, the query takes a couple of seconds to run (which is fine, since there are thousands of entries and, as far as I know, when using COUNTs and SUMs indexes don't help) and the results are perfect, but when I run the exact same query in PHP (echoed before running), the MySQL thread loads a core to 100% and doesn't stop until I kill it.

If I strip the extra stuff to calculate the COUNT and SUM, the query finishes but the results are useless to me.

EXPLAIN:

1   SIMPLE  mb  ALL     NULL                        NULL        NULL        NULL                                48713       Using temporary; Using filesort
1   SIMPLE  ot  ALL     idx_orders_total_orders_id  NULL        NULL        NULL                                811725      Using where
1   SIMPLE  o   eq_ref  PRIMARY                     PRIMARY     4           db.ot.orders_id                     1           Using where
1   SIMPLE  c   eq_ref  PRIMARY                     PRIMARY     4           db.o.customers_id                   1           Using where
1   SIMPLE  ab  eq_ref  PRIMARY                     PRIMARY     4           db.c.customers_default_address_id   1

EXPLAIN after applying indexes and using joins:

1   SIMPLE  c   ref     PRIMARY,search_str_idx              search_str_idx          98      const                                   1       Using where; Using temporary; Using filesort
1   SIMPLE  mb  ALL     NULL                                NULL                    NULL    NULL                                    48713   Using where
1   SIMPLE  ab  eq_ref  PRIMARY                             PRIMARY                 4       db.c.customers_default_address_id       1    
1   SIMPLE  ot  ref     idx_orders_total_orders_id,class    class                   98      const                                   157004  Using where
1   SIMPLE  o   eq_ref  PRIMARY                             PRIMARY                 4       db.ot.orders_id                         1       Using where

Moving code outside the for statement gives me a white page - PHP

So I've written this code which takes names from a text file and puts it in a table, but my problem is after I put something else below $Data the code stops working and all I get is a white page. I've tried to set all of the errors to true so it displays errors, but with no luck and the PHP error log files is also empty.

If I add this piece of code ($nameParsed = rawurlencode($Data[1]);), or any other below $Data, I get a white page, but if I move it below the $Data to after the table it works and it is still within the for statement.

I'm completely baffled, why does this happen? There is nothing wrong with the variable $nameParsed and everything else seems to be correct.

    <?php
    for ($i = 0; $i <= $totalMembers - 1; $i++) {
        $currentLine = $lines[$i];
        $Data = explode("\t", $currentLine)
    ?>
    <tr>
    <td style='text-align: center;'><?php echo $i + 1; ?></td>
    <td class='member' style='padding-left:16px;'><?php echo $Data[1]; ?></td>
    <td style='padding-left:15px;'>117</td>
    <td class='member' style='text-align: center;'>94</td>
    <td class='member' style='text-align: center;'>94</td>
    <td class='member' style='text-align: center;'>94</td>
    <td class='member' style='text-align: center;'>97</td>
    <td class='member' style='text-align: center;'>92</td>
    <td class='member' style='text-align: center;'>70</td>
    <td class='member' style='text-align: center;'>94</td>
    </tr>
    <?php
    $nameParsed = rawurlencode($Data[1]);
    }

Copying files between two Debian Servers using php

My php website is hosted in Debain Machine and I want to move a file from that Machine to another Debain which is connected through VPN.

I tried shell_exec and scp , as mentioned here.

<?php
    $output = shell_exec('scp file1.txt dvader@deathstar.com:somedir');
    echo "<pre>$output</pre>";
?>

I also tried using SFTP

<?php

class SFTPConnection
{
    private $connection;
    private $sftp;

    public function __construct($host, $port=22)
    {
        $this->connection = @ssh2_connect($host, $port);
        if (! $this->connection)
            throw new Exception("Could not connect to $host on port $port.");
    }

    public function login($username, $password)
    {
        if (! @ssh2_auth_password($this->connection, $username, $password))
            throw new Exception("Could not authenticate with username $username " .
                                "and password $password.");

        $this->sftp = @ssh2_sftp($this->connection);
        if (! $this->sftp)
            throw new Exception("Could not initialize SFTP subsystem.");
    }

    public function uploadFile($local_file, $remote_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.http://sftp$sftp$remote_file", 'w');

        if (! $stream)
            throw new Exception("Could not open file: $remote_file");

        $data_to_send = @file_get_contents($local_file);
        if ($data_to_send === false)
            throw new Exception("Could not open local file: $local_file.");

        if (@fwrite($stream, $data_to_send) === false)
            throw new Exception("Could not send data from file: $local_file.");

        @fclose($stream);
    }
}

try
{
    $sftp = new SFTPConnection("localhost", 22);
    $sftp->login("username", "password");
    $sftp->uploadFile("/tmp/to_be_sent", "/tmp/to_be_received");
}
catch (Exception $e)
{
    echo $e->getMessage() . "\n";
}

?>

Simply My problem is that I am not able to move a file from one machine, where my php applicaton is working , to another machine which is connected through VPN.

CodeIgniter is_unique Error Message in Language File

When using CodeIgniter I like to set my error messages in application/language/english/form_validation_lang.php which works fine for every error message but does not seem to work for the is_unique message as it gives me the standard message of "The email field must contain a unique value."

My code:

$lang['is_unique'] = "The %s entered is already in use.";

how to upload multiple files, store their paths in different columns in a mysql database row

Hello i am trying to create a subscription form, that allows a user to fill in a form and upload multiple files. already i have gotten some directions on this site as regards uploading a file and storing their paths in a database using this.

     <form method="post" action="addMember.php" enctype="multipart/form-data">
    <p>
              Please Enter the Band Members Name.
            </p>
            <p>
              Band Member or Affiliates Name:
            </p>
            <input type="text" name="nameMember"/>
            <p>
              Please Enter the Band Members Position. Example:Drums.
            </p>
            <p>
              Band Position:
            </p>
            <input type="text" name="bandMember"/>
            <p>
              Please Upload a Photo of the Member in gif or jpeg format. The file name should be named after the Members name. If the same file name is uploaded twice it will be overwritten! Maxium size of File is 35kb.
            </p>
            <p>
              Photo:
            </p>
            <input type="hidden" name="size" value="350000">
            <input type="file" name="photo"> 
            <p>
              Please Enter any other information about the band member here.
            </p>
            <p>
              Other Member Information:
            </p>
<textarea rows="10" cols="35" name="aboutMember">
</textarea>
            <p>
              Please Enter any other Bands the Member has been in.
            </p>
            <p>
              Other Bands:
            </p>
            <input type="text" name="otherBands" size=30 />
            <br/>
            <br/>
            <input TYPE="submit" name="upload" title="Add data to the Database" value="Add Member"/>
          </form>
and the php code for inserting this

   <?php

//This is the directory where images will be saved
$target = "your directory";
$target = $target . basename( $_FILES['photo']['name']);

//This gets all the other information from the form
$name=$_POST['nameMember'];
$bandMember=$_POST['bandMember'];
$pic=($_FILES['photo']['name']);
$about=$_POST['aboutMember'];
$bands=$_POST['otherBands'];


// Connects to your Database
mysql_connect("yourhost", "username", "password") or die(mysql_error()) ;
mysql_select_db("dbName") or die(mysql_error()) ;

//Writes the information to the database
mysql_query("INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;

//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{

//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {

//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>

this stores the path of the uploaded file in the column "photo" below

id nameMember bandMember photo aboutMember otherBands

but what i want do is have mutiple upload fields and store their paths in different columns photo, photo1 , photo2 e.g

 <input type="file" name="photo"> 
 <input type="file" name="photo1"> 
 <input type="file" name="photo2"> 
id nameMember bandMember photo photo1 photo2 aboutMember otherBands

please how do i go about this

Drupal 7 View->Formate(Grid) - grouping field option issue

If I edit page view->Format(grid)->settings and hit apply changes button(without changing anything) 'Grouping field' is keep on increasing. For every changes 'Grouping field' just incrementing plz refer the attached image. How to avoid this.enter image description here

While loop inside a while loop from PDO query

Consider a situation where you have a mysql table FLAGS with a random amount of rows

ID  Language   Flag1               Flag2              Flag3             Flag4 
1   dutch      flanders_flag.png   dutch_flag.png 
2   french     wallonia_flag.png   french_flag.png    morocco_flag.png     
3   english    england_flag.png    ireland_flag.png   america_flag.png  scotland_flag.png

if i want to query these rows and put them into my html i use the while loop because i never know how much rows this table FLAGS has.

<?php
   $flagquery = $db->prepare ("SELECT * FROM flags");
   $flagquery->execute();
   while ($flagrow = $flagquery->fetch(PDO::FETCH_ASSOC)) {
?>
  <div class="col-md-1 col-sm-2 col-xs-6"> 
    <p><?php echo $flagrow['language']; ?></p>
    <p><?php echo $flagrow['flag1']; ?></p>
    <p><?php echo $flagrow['flag2']; ?></p>
    <p><?php echo $flagrow['flag3']; ?></p>
    <p><?php echo $flagrow['flag4']; ?></p>
  </div>
<?php
  }
?>

But as you can see in the FLAGS table you don't always have 4 flags a language so i would think you have to do a while loop inside this previous while loop to echo only the flags that are present in the FLAGS table instead of just echo all the flags even if they are empty.

Are my thoughts right? Or what would be the best way to handle my situation?

How to collect user data by asking questions in web application? [on hold]

For my web application I need to collect user data. However this has to be like LINKEDIN way. Once user login to website , linkedin ask questions in small windows or panels. In the same way I too want to implement. How to do this?? Any help is greatly appreciated. Im using PHP and Mysql to develop website. Thanks in Advance.

What does this operator do in PHP? [duplicate]

This question already has an answer here:

I'm currently trying to resolve a bug in another programmers code (who I can't contact). His code is as follows;

$prooms = mysqli_query($con, "select * from property_room where property_id='".(int)$property_id ."'") or die(mysqli_error($con));
    while($r = mysqli_fetch_array( $prooms )) {
        $rooms[]=array(
                        "room_name" => $r['property_room_name'],
                        "room_description" => $r['property_room_description'] ,
                        "room_length" => $r['property_room_length']?$r['property_room_dimension_unit']:NULL ,
                        "room_width" => $r['property_room_width']?$r['property_room_dimension_unit']:NULL ,
                        "room_dimension_unit" => $r['property_room_dimension_unit']?$r['property_room_dimension_unit']:NULL ,
                        "room_photo_urls" =>$r['property_room_images_url'] 
                    );
    }

For the line;

"room_length" => $r['property_room_length']?$r['property_room_dimension_unit']:NULL ,

Does this mean if $r['property_room_length'] is empty the string is set to NULL?

What I'm trying to achieve is that if $r['property_room_length'] is set to '0.00' I want the string to be set to NULL.

How to call controller class from Rest controller class in Codigniter 3.0

I have applied Rest server successfully as per explain in link.

Now I am trying to apply REST code in my login module. I have created new controller for login to apply REST API. My PHP code is as follows:

require APPPATH.'/libraries/REST_Controller.php';
class Login_api extends REST_Controller {

    function __construct()
    {
        // Construct our parent class
        parent::__construct();


        // Configure limits on our controller methods. Ensure
        // you have created the 'limits' table and enabled 'limits'
        // within application/config/rest.php
        $this->methods['validate_user_get']['limit'] = 500; //500 requests per hour per user/key
        $this->methods['validate_user_post']['limit'] = 100; //100 requests per hour per user/key
    }

     function validate_user_get()
    {
        if(!$this->get('username') && !$this->get('password'))
        {
            $this->response(NULL, 400);
        }

        // $user = $this->some_model->getSomething( $this->get('id') );

        //$user = @$users[$this->get('id')];
        //$user =array($this->get('username'),$this->get('password'));

        if($user)
        {
            $this->response($user, 200); // 200 being the HTTP response code
        }

        else
        {
            $this->response(array('error' => 'User could not be found'), 404);
        }
    }

    function validate_user_post()
    {


        //$this->Login->login_user($this->input->post('username'),$this->input->post('password'));

        //$this->some_model->updateUser( $this->get('id') );
        //$message = array('id' => $this->get('id'), 'name' => $this->post('name'), 'email' => $this->post('email'), 'message' => 'ADDED!');

        $this->response($message, 200); // 200 being the HTTP response code
    }

It works fine when I print static data using get and post function. But I want to pass data in my CI_controller function from Rest controller. So what can I do for it ?

I have tried below code but not succeed :

I have write this code in Validate_user_post function :

$this->load->library('../controllers/Login');
$this->Login->login_user($this->input->post('username'),$this->input->post('password'));

Codeigniter 3.0 Session conflict with REST API

Unable to save data in Database through ajax in CakePhp after passing my own array variable in save function?

This is my view ctp page ....

<h1>Add Post</h1>
<?php echo $this->form->create(null,array('url'=>array('controller'=>'posts','action'=>'ajaxAdd'),'id'=>'saveForm'));
echo $this->form->input('ajaxtitle');
echo $this->form->input('ajaxbody',array('rows'=>'3'));
echo $this->form->end('Save Post');
?>

<script>
    $(document).ready(function(){
    $("#saveForm").submit(function(){       
        var formData = $(this).serialize();
        var formUrl = $(this).attr('action');
        $.ajax({

            type:'POST',
            url:formUrl,
            data:formData,
            success: function(data,textStatus,xhr){
                alert(data);                                       
                }

        });
        return false;
    });
});
</script>

This is my PostsController function

class PostsController extends AppController
{

        public $name = 'Posts';
        public $helpers = array('Html', 'Form', 'Session');
        public $components  = array('RequestHandler');
public function ajaxAdd()
    {
        $this->autoRender=false;
          if($this->RequestHandler->isAjax()){
             Configure::write('debug', 0);
          }
            if(!empty($this->data)){
                $inputData = array();
                $inputData['Post']['title'] = $this->data['Post']['ajaxtitle'];
                $inputData['Post']['body'] = $this->data['Post']['ajaxbody'];
                $data = $this->Post->findByTitle($inputData['Post']['title']);
                $this->Post->create();
               if(empty($data))
               {                   
                  if($this->Post->save($inputData))
                      return "success"; 
                }else
                {
                 return "error";
               }
            }
        }
}

With array as $inputData in save , whenever i click over the submit button nothing is being saved in the database ,,

But when i pass $this->data in save function, columns like id,created and modified are filled but the title and body column are left blank.

My posts databse contains columns id,title,body,created,modified

Combining multiple relation query in one - laravel

I have 2 tables :- items and groups

groups table as below :-

create table groups (`id` int unsigned not null auto_increment, 
                     `group_name` varchar(255), 
                      primary key(`id`)
);

items table as follows :-

create table items (`id` int unsigned not null auto_increment, 
                    `group_for` int unsigned not null, 
                    `item_name` varchar(255), 
                     primary key(`id`), 
                     key `group_for` (`group_for`), 
                     constraint `fk_group_for` foreign key (`group_for`)                  references `groups`(`id`)

I have below two eloquent method :-

class Item extends \Eloquent {

    // Add your validation rules here
    public static $rules = [
        // No rules
    ];

    // Don't forget to fill this array
    protected $fillable = ['group_for', 'item_name'];


    public function divGet() {
        return $this->belongsTo('group', 'group_for', 'id');
    }
}

Group eloquent

class Group extends \Eloquent {

    // Add your validation rules here
    public static $rules = [
        // No Rules.
    ];

    // Don't forget to fill this array
    protected $fillable = ['group_name'];

    public function items() {
        return $this->hasMany('item', 'group_for', 'id');
    }
}

Now, I am running below query :-

$groupItem = array()

// Fetching all group row
$gGroup = Group::all();

// Checking if there is not 0 records
if(!is_null($gGroup)) {

    // If there are more than 1 row. Run for each row
    foreach($gGroup as $g) {
        $groupItem[] = Group::find($g->id)->items;
    }
}

As you can see above, if i have 10 groups than , Group::find.....->items query will run 10 query. Can i combine them in 1 query for all more than 1 records of Group::all() ?

How to create a button to run install script in magento?

I have created an install script.

But my requirement is, this script has to be run only when it is invoked manually. I have created a button in admin back-end. When I click that button the script has to be run. I have searched in Google. But I can't get any answer.

I don't know is it possible to do like this. How to prevent a script to be execute when that module loads first time.

One Symfony app with multiple domain

I have a Symfony2 app, only on 1 server, but because it's internationalised, I have multiple domain names ( not subdomains ). What I want to achieve is if a user change his language, I redirect to a different host and the user should be already logged in on the other locale.

jqueyr datetimepicker set to date depand on from date

I am using jQuery "datetimepicker" and I want to set the "to date" value depend on the "from date" value and the Select box value which contains following values.

1- Weekly (7+ days)
2- Monthly (30+ days)
3- Half Yearly (6+ months)
3- Yearly (1+ Year)

Example:

1- Select From Date: 2015-05-29
2- Duration Monthly
3- To date should be 2015-06-29

I am using following code to select date start date.

jQuery('#start_date').datetimepicker({
    format:'m/d/Y',
    closeOnDateSelect:true,
    timepicker:false
});

Please suggest.

Thanks

SOAP request not working in PHP

We have wsdl : http://ift.tt/1JbE0cv

IN PHP FILE : i have created a Class with some arrays in it..

class Crmtet {
   public $abc;
   public $abc2;
   public $abc3;
   public $abc4;
 }

$client = new SoapClient(http://ift.tt/1JbE0cv);
$obj = new Crmtet();

$obj->abc= "Test";
$obj->abc2= "Test2";
$obj->abc3= "Test3";
$obj->abc4= "Test4";

$result = $client->CRM_Warehouse_Master_Insert($obj)->CRM_Warehouse_Master_InsertResult;
echo"re".$result;


But i am getting below error :

Fatal error: Uncaught SoapFault exception: [soap:Server] Server was unable to process request. ---> Object reference not set to an instance of an object. in E:\EasyPHP-12.1\www\test\inserwarrecrm.php:60 Stack trace: #0 E:\EasyPHP-12.1\www\test\inserwarrecrm.php(60): SoapClient->__call('CRM_Warehouse_M...', Array) #1 E:\EasyPHP-12.1\www\test\inserwarrecrm.php(60): SoapClient->CRM_Warehouse_Master_Insert(Object(Crmtet)) #2 {main} thrown in E:\EasyPHP-12.1\www\test\inserwarrecrm.php on line 60

What is the issue.. can anyone help..??

MongoDB check for Collection before creating it

I am creating an install script, but I want to make sure that the collections that I am installing are not already being used by another program.

I am wondering is there a PHP function that returns 0 or 1 if the collection exists in the database?

I know I could do a find search, using the collection, however I would prefer not having to do a find search to get the result.

Any help here would be great

Convert Subquery SQL to Laravel possible?

Is this possible to change this SQL to let it work on Laravel?

SELECT  name, event,m.season_id, tm.played_pugs, active, m.created_at, datediff(now(),m.created_at)
FROM matchs m
LEFT OUTER JOIN seasons ON seasons.id = m.season_id
JOIN ( SELECT season_id, max(matchs.created_at) as MaxDate, count(season_id) as played_pugs
                  FROM matchs
                  GROUP BY season_id) tm on m.season_id = tm.season_id and m.created_at = tm.MaxDate
ORDER BY played_pugs descc>

This is what I have so far:

$seasons = DB::table('matchs')
    ->select('name', 'event', 'season_id', 'played_pugs', 'active', DB::raw('datediff(now(),created_at) as days'))
    ->join('seasons', 'seasons.id', '=', 'matchs.season_id', 'left outer')
    ->join(DB::raw('SELECT season_id, max(matchs.created_at) as MaxDate, count(season_id) as played_pugs FROM matchs GROUP BY season_id)'), '')
    ->orderBy('played_pugs','desc')
    ->get();

Also I can't see the values with 'played_pugs' that have value 0 anymore. How can I fix that.

How to my PHP array value solved

My php array value:

{"search_engine":{"direct":"261","social_media":"3","search":"3"},"browser":{"chrome":"168","firefox":"68","netscape":"26","safari":"4","ie":"1"},"platform":{"windows":"266","mac_os_x":"1"},"entry":{"192.168.1.151":"260","facebook":"1","google":"2","wikipedia":"1","bing":"1","localhost":"1","twitter":"1"},"sceensize":{"1920_x_1080":"228","360_x_640":"1","768_x_1024":"8","800_x_1280":"1","290_x_480":"1","480_x_290":"2","320_x_480":"3","519_x_607":"3","858_x_1143":"7","893_x_1429":"3","357_x_536":"2","402_x_715":"1","715_x_402":"4","2144_x_1206":"3"}}

How to get output this type:-

[{"search_engine":"direct":"261","social_media":"3","search":"3"},{"browser":"chrome":"168","firefox":"68","netscape":"26","safari":"4","ie":"1"},{"platform":"windows":"266","mac_os_x":"1","entry":"192.168.1.151":"260","facebook":"1","google":"2","wikipedia":"1","bing":"1","localhost":"1","twitter":"1"},{"sceensize":"1920_x_1080":"228","360_x_640":"1","768_x_1024":"8","800_x_1280":"1","290_x_480":"1","480_x_290":"2","320_x_480":"3","519_x_607":"3","858_x_1143":"7","893_x_1429":"3","357_x_536":"2","402_x_715":"1","715_x_402":"4","2144_x_1206":"3"}]

Concatenate Integers without calculate PHP

On my database, dates are in the format DD-MM-YYYY. But for a SELECT, I need to be between two dates.
I know I must use BETWEEN syntax but with this, I need the date to be in the format YYYY/MM/DD.
So here's my code to change the syntax :

// my URL is : '.../pdf.php?date1=22-05-2015&date2=29-05-2015'
$date1=explode('-',$_GET["date1"]); // $_GET["date1"] = '22-05-2015'
$date2=explode('-',$_GET["date2"]); // $_GET["date2"] = '29-05-2015'

$date1_good = $date1[2].'/'.$date1[1].'/'.$date1[0];
$date2_good = $date2[2].'/'.$date2[1].'/'.$date2[0];

The problem is, $date1_good and $date2_good are now float values and not a string like '2015/05/29'.
I have tried using strval() and (string) but nothing worked.
Do you have any idea to make it work ? Thank you !

Codeigniter using active record and sql injection

I have using Active Record in my Codeigniter apps. But still got error, I think it cause by sql injection

function get_member_by_hape($hape)
{
    $this->db->select('*');
    $this->db->from('member');
    $this->db->where('hape',$hape);

    $query = $this->db->get();
    if ($query->num_rows() > 0){
        return $query->row_array();
    }else{
        return FALSE;
    }
}

I tried so far, it is no problem. But there is someone who tells me about the error http://ift.tt/1KCisHG on login form. I don't know where is the problem on my source code. This is my website pulsa.aijogja.com

Why while loop is displaying single row?

I am trying to run while loop in a while loop, but only single record is displayed.

<?php    
if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT u.id, u.firstname, u.lastname, u.email, c.fullname, ro.shortname, c.id as courseid
    from mdl_context cx 
    Left join mdl_course c ON cx.instanceid = c.id
    Left join mdl_role_assignments r  on  r.contextid = cx.id
    Left join mdl_user u on u.id = r.userid
    Left join mdl_role ro on ro.id = r.roleid
    WHERE r.roleid IN (11)
    AND cx.contextlevel =50 GROUP BY u.id ORDER BY u.id ASC";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row
        echo "<table>"."<tr>"."<td width='100px;'><h4>Name</h4></td>"."<td width='50px;'>"."</td>"."<td width='230px;'><h4>Email</h4></td>"."<td width='100px;'><h4>Role</h4></td>"."<td width='100px;'>"."</td>"."<td><h4>Course</h4></td>"."</table>"."<br>";
        while($tmg = $result->fetch_assoc()) {
        echo "<table>"."<tr>"."<td width='100px;'><a href='http://localhost/user/profile.php?id=".$tmg["id"]."'>".$tmg["firstname"]." ".$tmg["lastname"]."</a></td>"."<td width='50px;'>"."</td>"."<td width='230px;'>".$tmg["email"]."</td>"."<td width='100px;'>".$tmg["shortname"]."</td>";
        $newarray = implode(",",$tmg["id"]);
        $sqlt = "SELECT u.firstname, u.lastname, c.id, c.fullname FROM mdl_course AS c JOIN mdl_context AS ctx ON c.id = ctx.instanceid JOIN mdl_role_assignments AS ra ON ra.contextid = ctx.id JOIN mdl_user AS u ON u.id = ra.userid WHERE u.id IN ($newarray)";
        while($row = $sqlt->fetch_assoc()) {
        echo    "<td width='100px;'>"."</td>"."<td>".$row["fullname"]."</td>"."</table>"."<br>";
        }
        }
    } else {
        echo "0 results";
    }
    $conn->close();
     ?>

Any guidance or help will be much appreciated.

Php upload to Facebook without Facebook Login

I need to do a form to upload photos with name and description, but I want to upload the photo at the same time to a Facebook fanpage, with the same form. I don't want to login to facebook before uploading the image, I just want to write the credentials in the php and work with this. I have tried it but I can't get the facebook session (and I don't even know that if is possible to do this without login).

Thanks in advance

            //PAGE ID: ********


            define('FACEBOOK_SDK_V4_SRC_DIR', '/complementos/facebook-php-sdk-v4-4.0-dev/src/Facebook/');
            require __DIR__ . '/complementos/facebook-php-sdk-v4-4.0-dev/autoload.php';


            require_once( 'complementos/facebook-php-sdk-v4-4.0-dev/src/Facebook/FacebookSession.php' );

            // Make sure to load the Facebook SDK for PHP via composer or manually
            require_once( 'complementos/facebook-php-sdk-v4-4.0-dev/src/Facebook/FacebookRequest.php' );
            require_once( 'complementos/facebook-php-sdk-v4-4.0-dev/src/Facebook/GraphObject.php' );

            use Facebook\FacebookSession;
            use Facebook\FacebookRequest;
            use Facebook\GraphObject;

            session_start();
            FacebookSession::setDefaultApplication('********', '******');

            if($session) {

              try {
                    // uploading image to user timeline using facebook php sdk v4
                    $response = (new FacebookRequest(
                        $session, 'POST', '/me/photos', array(
                            'source' => new CURLFile('img/h_index.jpg', 'image/jpg'), // photo must be uploaded on your web hosting
                            'message' => 'User provided message'
                            )
                        )
                    )->execute()->getGraphObject();
                    if($response) {
                        echo "Photo is uploaded...";
                    }

                } catch(FacebookRequestException $e) {
                    echo $e->getMessage();
                }

            }

            else
            {
                echo "no entra en session;";
            }

Resize Image Canvas with CodeIgniter Image Library - how to preserve transparency

I am trying to resize image canvas (as in Photoshop) by adding transparency around it. Somehow added part of the image is always black.

if ($this->image_library == 'gd2' AND function_exists('imagecreatetruecolor'))
{
     $create = 'imagecreatetruecolor';
     $copy = 'imagecopyresampled';
}
else
{
     $create = 'imagecreate';
     $copy    = 'imagecopyresized';
}

$dst_img = $create($this->width, $this->height);

if ($this->image_type == 3) // png we can actually preserve transparency
{
    //teorethicaly image should be transparent?
    $trans_colour = imagecolorallocatealpha($dst_img, 0, 0 ,0, 127); 
    imagefill($dst_img, 0, 0, $trans_colour);
    imagealphablending($dst_img, FALSE);
    imagesavealpha($dst_img, TRUE);
}

$copy($dst_img, $src_img, 0, 0, $this->x_axis, $this->y_axis, $this->width, $this->height, $this->orig_width, $this->orig_height);

If I remove $copy and save new image only, it is transparent but if I merge both images the background is always black:

enter image description here

How I can have transparent background in that situation?

Thanks in advance!

search and count by gender and race

I just want to know any ideas for me to find gender and race. The data should display like:

-----------------------------
course  | Race 1 | Race 2 | 
        | M | F  | M | F  |
-----------------------------
science | 2 | 4  | 3 | 7  |

//this is table structure

$sql = "CREATE TABLE student (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
name VARCHAR(30) NOT NULL,
gender VARCHAR(30) NOT NULL,
race VARCHAR(50),
session VARCHAR(50),
course VARCHAR(50),
)";

The code that I already have:

<?php
include "connect_db.php";
if ((isset($_POST['submit'])) AND ($_POST['search'] <> "")) {

    $search = $_POST['search'];

    $sql = "SELECT gender, count(gender) AS cnt FROM student WHERE session LIKE '%$search%' AND gender IN ('Male', 'Female') GROUP BY gender" or die(mysqli_error(
        ''
    ));
    $result = $conn->query($sql);

    while ($row = fetch_assoc($result)) {
        $dataSet->addPoint(new Point($row['gender'], $row['cnt']));

    }

}

sandbox paypal account transferring money to invalid accounts through php code

In my api,I'm using a php code to automatically transfer money amount from one sandbox paypal account to another sandbox paypal account.But through this php code , transactions are occuring for invalid sandbox user accounts which should not happen at all. furthermore , I cannot find any way to check in my code whether the reciever's sandbox account is valid or not.If it's valid ,only then tranfer money to the reciever's account.

Here is the code....

******* Paypal_class.php *******

enter code here

class Paypal {

    public function __construct($username, $password, $signature) {
        $this->username = urlencode($username);
        $this->password = urlencode($password);
        $this->signature = urlencode($signature);
        $this->version = urlencode("122.0");
        $this->api = "http://ift.tt/pI1orb";

        $string = 'cmd=' . urlencode('_notify-validate');
        //The functions can be modified but need to be urlencoded
        $this->type = urlencode("EmailAddress");
        $this->currency = urlencode("USD");
        $this->subject = urlencode("Instant Paypal Payment");
    }

    public function pay($email, $amount, $note="Instant Payment") {
        $string = "&EMAILSUBJECT=".$this->subject."&RECEIVERTYPE=".$this->type."&CURRENCYCODE=".$this->currency;

        $string .= "&L_EMAIL0=".urlencode($email)."&L_Amt0=".urlencode($amount)."&L_NOTE0=".urlencode($note);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->api);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_FAILONERROR, true);

        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        $request = "METHOD=MassPay&VERSION=".$this->version."&PWD=".$this->password."&USER=".$this->username."&SIGNATURE=".$this->signature."$string";

        curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
        $httpResponse = curl_exec($ch);

        if(!$httpResponse) {
            exit("MassPay failed: ".curl_error($ch).'('.curl_errno($ch).')');
        }

        $httpResponseArray = explode("&", $httpResponse);
        $httpParsedResponse = array();
        foreach ($httpResponseArray as $i => $value) {
            $tempArray = explode("=", $value);
            if(sizeof($tempArray) > 1) {
                $httpParsedResponse[$tempArray[0]] = $tempArray[1];
            }
        }

        if((0 == sizeof($httpParsedResponse)) || !array_key_exists('ACK', $httpParsedResponse)) {
            exit("Invalid HTTP Response for POST request($request) to ".$this->api);
        }

        return $httpParsedResponse;
    }

}

?

Metabox connect don't work

Metabox problem how do I connect these php in this code, what am I doing wrong

elseif($infobox_type == 'cspm_type5'){

    $output .= '<div class="cspm_infobox_content">';
    $output .= '<div>';
    $output .= '<div class="cspm_infobox_img">'.$post_thumbnail.'</div>';
    $output .= '<div class="title">'.$the_post_link.'</div>';

    <?php echo get_post_meta( get_the_ID(), 'barcode', true ); ?>

    $output .= '</div><div style="clear:both"></div>';
    $output .= '<div class="description">';
    $post_record = get_post($post_id, ARRAY_A, 'display');
    $post_content = trim(preg_replace('/\s+/', ' ', $post_record['post_content']));
    $output .= apply_filters('cspm_large_infobox_content', $post_content, $post_id);
    $output .= '</div>';
    $output .= '</div>';
    $output .= '<div style="clear:both"></div>';
    $output .= '<div class="cspm_arrow_down"></div>';

PHP create multi dimensional array

I am querying my database with a LEFT JOIN to get the following array:

Array
(
    [invoice_number] => 000010
    [invoice_date] => 1432764000
    [country] => 115
    [fao] => Rick
    [company_name] => Chubbs
    [address_line_1] => kjhk
    [address_line_2] => jh
    [town] => kjh
    [postcode] => kjh
    [filename] => INV-1432820860.pdf
    [id] => 11
    [description] => dfgh
    [rates] => 2
    [quantity] => 3
    [price] => 6
    [created] => 0
    [country_name] => Kazakhstan
)
Array
(
    [invoice_number] => 000010
    [invoice_date] => 1432764000
    [country] => 115
    [fao] => Rick
    [company_name] => Chubbs
    [address_line_1] => kjhk
    [address_line_2] => jh
    [town] => kjh
    [postcode] => kjh
    [filename] => INV-1432820860.pdf
    [id] => 18
    [description] => biscuits
    [rates] => 2
    [quantity] => 3
    [price] => 6
    [created] => 0
    [country_name] => Kazakhstan
)

I want to loop through this and remove duplicates, so something like this:

Array
    (
        ['inv_details'] => array(
            [invoice_number] => 000010
            [invoice_date] => 1432764000
            [country] => 115
            [fao] => Rick
            [company_name] => Chubbs
            [address_line_1] => kjhk
            [address_line_2] => jh
            [town] => kjh
            [postcode] => kjh
            [filename] => INV-1432820860.pdf
        )
        ['items'] => array(
            [0] => array(
                [description] => dfgh
                [rates] => 2
                [quantity] => 3
                [price] => 6
                [created] => 0
            )
            [1] => array(
                [description] => biscuits
                [rates] => 2
                [quantity] => 3
                [price] => 6
                [created] => 0
            )

        )
    )

I have this code at the moment but the items array is not adding two arrays the last item ovewrites the first one and I dont end up with 2 arrays in items, just one:

$i = 0;

foreach($res->fetchAll(PDO::FETCH_ASSOC) as $row){

    $form = array();

    $form['title'] = $row['invoice_number'];
    $form['inv_details']['invoice_date'] = array('value'=>gmdate('d/m/Y', $row['invoice_date']), 'type'=>'date');
    $form['inv_details']['company_name'] = array('value' => $row['company_name'], 'type' => 'text');
    $form['inv_details']['fao'] = array('value' => $row['fao'], 'type' => 'text');
    $form['inv_details']['address_line_1'] = array('value' => $row['address_line_1'], 'type' => 'text');
    $form['inv_details']['address_line_2'] = array('value' => $row['address_line_2'], 'type' => 'text');
    $form['inv_details']['town'] = array('value' => $row['town'], 'type' => 'text');
    $form['inv_details']['postcode'] = array('value' => $row['postcode'], 'type' => 'text');
    //$form['inv_details']['countries'] = $this->crm_account_address->getCountries();
    $form['country'] = $row['country_name'];
    $form['country_id'] = $row['id'];

    $form['items'][$i]['description'] = $row['description'];
    $form['items'][$i]['rates'] = $row['rates'];
    $form['items'][$i]['quantity'] = $row['quantity'];
    $form['items'][$i]['price'] = $row['price'];

    //counter
    $i++;

}

Any help would be great! Thanks

Android- Upload photo to the server

*The UploadProduct.class register a product in my database and upload the photo to my server. I am trying to upload a file to my server. When I execute my app this work perfectly, the product is registered in the database but in my server , the photo had not been loaded.

When I debug , I put a breakpoint in httppost.setEntity(mpEntity); , the value of file atribute is /storage/emulated/0/Needyt/20150529_104715.jpg

The path where I save my files is http://ift.tt/1KCisaP and the path of upload.php is http://aaaa.com/app

Here my code:

atributes:

private List<NameValuePair> params = new ArrayList<NameValuePair>(1);
private File file;
private String imageFileName = "";
private String urlImag ="http://ift.tt/1KCisaP";
private EditText  etNombreProducto,etDescripcion,etPrecioDia,etPrecioSemana;
private Bitmap bitmap=null;

methods:

public void takePhoto() {



        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        imageFileName = timeStamp  + ".jpg";


        //Creamos el Intent para llamar a la Camara
        Intent cameraIntent = new Intent(
                android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        //Creamos una carpeta en la memeria del terminal
        File imagesFolder = new File(
                Environment.getExternalStorageDirectory(), "Needyt");
        imagesFolder.mkdirs();
        //anadimos el nombre de la imagen
        file= new File(imagesFolder, imageFileName);
        Uri uriSavedImage = Uri.fromFile(file);
        //Le decimos al Intent que queremos grabar la imagen
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
        //Lanzamos la aplicacion de la camara con retorno (forResult)
        startActivityForResult(cameraIntent, 1);


    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //Comprovamos que la foto se a realizado
        if (requestCode == 1 && resultCode == RESULT_OK) {
            //Creamos un bitmap con la imagen recientemente
            //almacenada en la memoria
            bitmap= BitmapFactory.decodeFile(
                    Environment.getExternalStorageDirectory() +
                            "/aaaa/" + imageFileName);
//            //Anadimos el bitmap al imageView para
//            //mostrarlo por pantalla
//            img.setImageBitmap(bMap);
        }
    }


    private boolean uploadFoto(String imag){
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpPost httppost = new HttpPost("http://ift.tt/1Ruep13");
        MultipartEntity mpEntity = new MultipartEntity( );

        ContentBody contentBody = new FileBody(file,"image/jpeg");
        mpEntity.addPart("foto", contentBody);
        httppost.setEntity(mpEntity);
        try {
            httpclient.execute(httppost);
            httpclient.getConnectionManager().shutdown();
            return true;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
    private boolean onInsert(){
        String nombreP = etNombreProducto.getText().toString();
        String descripcion = etDescripcion.getText().toString();
        String precioD = etPrecioDia.getText().toString();
        String precioS=etPrecioSemana.getText().toString();
        HttpClient httpclient;

        params.add(new BasicNameValuePair("nombre", nombreP));
        params.add(new BasicNameValuePair("descripcion", descripcion));
        params.add(new BasicNameValuePair("preciodia", precioD));
        params.add(new BasicNameValuePair("preciosemana", precioS));
        params.add(new BasicNameValuePair("imagen", urlImag + imageFileName));
        HttpPost httppost;
        httpclient=new DefaultHttpClient();
        httppost= new HttpPost("http://ift.tt/1KCisaR");
        // Url del Servidor

        try {
            httppost.setEntity(new UrlEncodedFormEntity(params));
            httpclient.execute(httppost);
            return true;
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    private void serverUpdate(){
        if (file.exists())
            new ServerUpdate().execute();
        else
            Toast.makeText(UploadProduct.this, "Debes de hacer una foto",
                    Toast.LENGTH_LONG).show();

    }

    class ServerUpdate extends AsyncTask<String,String,String> {

        ProgressDialog pDialog;
        @Override
        protected String doInBackground(String... arg0) {
            Boolean b=uploadFoto(imageFileName);
            if(onInsert()&& b)
                runOnUiThread(new Runnable(){
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        Toast.makeText(UploadProduct.this, "Exito al subir la imagen",
                                Toast.LENGTH_LONG).show();
                    }
                });
            else
                runOnUiThread(new Runnable(){
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        Toast.makeText(UploadProduct.this, "Sin exito al subir la imagen",
                                Toast.LENGTH_LONG).show();
                    }
                });
            return null;
        }
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(UploadProduct.this);
            pDialog.setMessage("Actualizando Servidor, espere..." );
            pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pDialog.show();
        }
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            pDialog.dismiss();
        }

    }

my upload.php

<?php

    $ruta = "app/imagenes/" .basename($_FILES['foto']['name']);
    if(move_uploaded_file($_FILES['foto']['tmp_name'], $ruta)){
            echo "success";
        } else{
            echo "fail";
        }
    ?>

calculate the sum of each column in sql and php

I want to calculate the sum of each row in mysql and display in php.

for eg

amount1 | amount2 | total 100 | 200 |

300 | 200 |

How to display the total of each column? Here is the code. My code displays the whole table total and displays. What is the wrong with the code.

$query="SELECT *, sum(amount1+amount2) as total FROM contribution";
 $run = mysql_query($query);

while($row=mysql_fetch_assoc($run))
{ ?>
<tr><td><?php echo $row['uid'] ?></td><td><?php echo $row['name'] ?></td><td><?php echo $row['Date'] ?></td>
<td><?php echo $row['month1'] ?></td><td><?php echo $row['amount1'] ?></td>
<td><?php echo $row['month2'] ?></td><td><?php echo $row['amount2'] ?></td><td><?php echo $row['total'] ?></td>
</tr>

<?php } } ?>

Read Nagios Notification using php

How can I read response from a remote server using Nagios Notification. I'm new to this Nagios Notification System. The only data from the server side is , they are pushing data in this format

/usr/bin/curl --url http://ift.tt/1RueqlO? --data-urlencode "eventType=Nagios Notification" --data-urlencode "message=$NOTIFICATIONTYPE$#$LONGDATETIME$#$SERVICEDESC$#$HOSTALIAS$#$SERVICESTATE$#$SERVICEOUTPUT$#$CONTACTEMAIL$#$NOTIFICATIONISESCALATED$"

I've tried searching. But no results find.

What I need is read those tickets from Nagios notification system with my TicKeTREder.php page

mercredi 6 mai 2015

How do I 'watch' list box selection change?

In WPF VB.NET 4.0, I have a list box that is populated with a data binding from XML. How can I set a live watch event to the listbox so that the selected item, based on a certain criteria (field is true or false), a button on the form has it's content changed to read something else?

i.e., user selects an item with XML element 'status' is set to 'current', then button would read, Finished. If user selects an item with XML element 'status' is set to 'finished', then button would read, Unfinished.

Continous Counting of Present Days

I want to count continuously 10 days attendance where attendance_ status is present and shift is III . I have table in sql database named as Attendance_Master having fields Emp_Code,Attendance_Date,Shift,Attendance_Status(for storing Present ,Absent Status). I am using VB.Net 2008 for coding. How could I do this?

Set HTML attribute dynamically

I'm trying to generate HTML dynamically, in a way that looks a bit like MVC. However I'm trying to achieve this in Webforms.

I managed to pass a list to my aspx page, but using the properties in the html attributes doesn't seem to work:

My aspx page:

<% For Each question As WorkOrderQuestionDAO In Session("WorkOrderQuestions") %>
    <tr>
        <td style="width: 620px"><%= question.Question %></td>
        <td style="width: 300px">
        <% Select Case question.WorkOrderAnswerTypeID
            Case 1 %>
                <asp:RadioButtonList ID='<%# question.QuestionID %>' runat="server" RepeatDirection="Horizontal" RepeatLayout="Flow">
                    <asp:ListItem Value="-1">YES</asp:ListItem>
                    <asp:ListItem Value="0">NO</asp:ListItem>
                </asp:RadioButtonList>
            <%Exit Select
            Case 2 %>
                <asp:RadioButtonList ID='<%# question.QuestionID %>' runat="server" RepeatDirection="Horizontal" RepeatLayout="Flow">
                    <asp:ListItem Value="-1">YES</asp:ListItem>
                    <asp:ListItem Value="0">NO</asp:ListItem>
                    <asp:ListItem Value="1">NA</asp:ListItem>
                </asp:RadioButtonList>
            <% Exit Select
        End Select%>
     </td>
  </tr>
<% Next %>

So I try to set the ID of each RadioButtonList automatically, by trying to insert the question.QuestionID property. However the error i'm getting is:

The ID property of a control can only be set using the ID attribute in the tag and a simple value. Example:

I tried:

ID='<%# question.QuestionID %>'
ID='<%= question.QuestionID %>'
ID='<%= Eval("question.QuestionID") %>'

At this point I don't know what syntax to use. I don't think it should be to hard, but I couldn't find an answer using Google and find it hard to come up with the proper search terms.

The <tr>, <td> and <asp:RadioButtonList> generation goes fine by the way.

Consolidate excel data in vb.net

I get an error on consolidate data using vb.net. Please help.

Imports Microsoft.Office.Interop

Public Class Form1 Dim xlsWorkSheet As Excel.Worksheet

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim xlsApp As New Excel.Application
    xlsApp.Visible = True
    Dim xlsWorkbook As Excel.Workbook = xlsApp.Workbooks.Open("C:\Users\hwai\Desktop\Consolidate.xlsx")

    xlsWorkSheet.Range("H1").Select().Consolidate("'C:\Users\hwai\Desktop\[Consolidate.xlsx]Sheet1'!A1:B8", _Function:=-4112, TopRow:=False, LeftColumn:=True, CreateLinks:=False)


End Sub

Thanks

Is it possible to Create trello.com like boards and cards using VB.net?

Hello programmers, Am new to VB.net and i have taken up a task of creating Exactly like TRELLO.com Using VB.net. Is there any possibilities of doing it?

This Should be the first WINFORM i Just Need the BOARDS and BOARDS Creation This Should be the first WINFORM i Just Need the BOARDS and BOARDS Creation

And when the Board has been Clicked Then it should give a new form like this with cards in it. LIKE IN THE RELEASE EVENT THERE ARE SEVERAL CARDS

And when the Board has been Clicked Then it should give a new form like this with cards in it. LIKE IN THE RELEASE EVENT THERE ARE SEVERAL CARDS

Now when you click on the card it should give you options like in the picture. Like Add Members for the Project, Adding Comment,Adding Objectives like in the image

Now when you click on the card it should give you options like in the picture. Like Add Members for the Project, Adding Comment,Adding Objectives like in the image

Now my Question Is whether it is possible to be creating Boards and Cards exectly are closely like trello.com using VB.net

If so then i will start Doing this Project. Please Help Me. Thanks in Advance

Select from sql in vb and display in aspx page

Just wanna select a word from database and display in aspx page

Backend

Using da As New SqlDataAdapter
        con.Open()
        cmd.CommandText = "SELECT value_en as value FROM tbl_language WHERE element_id = 'a1';"
        da.SelectCommand = cmd
        Dim dt As New DataTable
        da.Fill(dt)
        Dim WordValue As String = dt.Rows(0).Item(0)
End Using

in aspx page

<%=WordValue%>

whats wrong here?

Dynamically add code at runtime in VB(.NET)

I want to make a program in VB(.NET) in which per click on a button one or more new buttons are added to the UserForm. This process should work for an infinite number of times. Then the buttons shall call a public sub, handing over an individual variable so that the code knows what button it was called from (thus: knows what to do).

I learned how to create buttons at runtime with the Button = new Button and controls.add(Button) code. I also managed to pass a new code to the button by using WithEvents or an AddHandler. But until now I always need to have the code ready before the program is run. I.e. I need to know the name of the button in advance and have the code prepared.

Is there a way to dynamically create a code snipped at run time that will point to a pre-existing one?

I'll give you a simplyfied example:

WithEvents NewButton01 As New Button
WithEvents NewButton02 As New Button
WithEvents NewButton03 As New Button

Private Sub AddNewButton_Click() Handles AddNewButton.Click

    NewButton01.Location = New Point(10, 10)
    NewButton01.Text = "01"
    Controls.Add(NewButton01)

    NewButton02.Location = New Point(50, 50)
    NewButton02.Text = "02"
    Controls.Add(NewButton02)

    NewButton03.Location = New Point(90, 90)
    NewButton03.Text = "03"
    Controls.Add(NewButton03)

End Sub

Private Sub NewButton01_click() Handles NewButton01.Click
    Call MessageBox(1)
End Sub

Private Sub NewButton02_click() Handles NewButton02.Click
    Call MessageBox(2)
End Sub

Private Sub NewButton03_click() Handles NewButton03.Click
    Call MessageBox(3)
End Sub

Private Sub MessageBox(flag As Integer)
    MsgBox("You activated button number " & flag)
End Sub

As you can see, this is a very unprofessional way of coding. Also, I'd like to keep the amount of buttons created infinite, so I can't use this code. I'd rather have VB make a new button each time I click on "AddNewButton" and write a code that refers to Private Sub MessageBox or whatever code it may be in the end.

I am very new to VB.Net, so please forgive me if the examples contains anything that makes you shiver.

And thank you very much!

Best practises: Execute Javascript code on VBNET

I know that similar questions had been answered before on this forum. But none of them are what i was looking for.

I'm developing a desktop application to show, in the same place, at the same time, information of various web pages using web scraping. I'm having a lot of troubles to show information extracted of one of them.

I need to simulate a login on that page, the problem is that to simulate the POST message i have to cipher the password before do it. For example, when the user opens the page with the browser, he can write the password: "123456". When the user clicks "login", the content of the input is changed (cipher) by javascript before submitting the form.

Thats the behaviour I need to emulate. I know the login and the password of my user. However I need to cipher it before i can do the POST. I have the js file which do the cipher and i know what function i have to call.

I have developed a workaround, but it has not good execution time (Getting an aspx from my server, passing the password as an url parameter. This aspx executes the function on the onload event, and shows the result on the body).

I think there has to be a way to convert the js file to a dll file, to load it as a normal reference, allowing me to call the function directly on my winform application.

Image name rewrites the old one VB.NET - How to rename same image to a different name every time when upload the file?

I know how to rename a file, but, in this case i have a tool to upload one by one, a lot of images, and, when you try to upload two different images with the same name rewrites the old one.

I need to generate dinamically something to identify every upload as unique, but i dont know how to put a count++ in Vb.net,

thank you very much for your time and consideration.

Dim Upload2 As UploadDetail = DirectCast(Me.Session("UploadDetail"), UploadDetail)

Upload2.IsReady = False
        If fileUpload1.PostedFile IsNot Nothing AndAlso fileUpload1.PostedFile.ContentLength > 0 Then

Dim path__1 As String = UPLOADFOLDER & "/"
Dim fileOK As Boolean = False
Dim fileName As String = Path.GetFileName(fileUpload1.PostedFile.FileName)
Dim strPath As String = Path.Combine(path__1, fileName)

If fileUpload1.HasFile Then

Dim fileExtension As String
fileExtension = System.IO.Path. _
                    GetExtension(fileUpload1.FileName).ToLower()

Dim allowedExtensions As String() = _
{".jpg", ".jpeg", ".png", ".gif"}
                For i As Integer = 0 To allowedExtensions.Length - 1
                    If fileExtension = allowedExtensions(i) Then
                        fileOK = True
                    End If
                Next
                If fileOK Then
                    Upload2.ContentLength = fileUpload1.PostedFile.ContentLength
                    Upload2.FileName = fileName
                    Upload2.UploadedLength = 0
                    Upload2.IsReady = True
Dim bufferSize As Integer = 1
Dim buffer As Byte() = New Byte(bufferSize - 1) {}
                    Using fs As New FileStream(Path.Combine(HttpContext.Current.Server.MapPath(path__1), fileName), FileMode.Create
                        While Upload2.UploadedLength < Upload2.ContentLength

Dim bytes As Integer = fileUpload1.PostedFile.InputStream.Read(Buffer, 0, bufferSize)
                            fs.Write(buffer, 0, bytes)
                            Upload2.UploadedLength += bytes
                        End While
                    End Using

Const js As String = "onComplete(1,'File uploaded correctly.','{0}','{1} of {2} Bytes');"
                    scriptManager.RegisterStartupScript(Me, GetType(FileUploadFotosPDF), "progress", String.Format(js, fileName, Upload2.UploadedLength, Upload2.ContentLength), True)
                    Session("Enabled") = fileName
                Else

Const js As String = "onComplete(4, 'There was a problem with the file. Perhaps, this file is not an image or corrupt','','0 of 0 Bytes');"
                    scriptManager.RegisterStartupScript(Me, GetType(FileUploadFotosPDF), "progress", js, True)
                End If

                Upload2.IsReady = False
            Else
Const js As String = "onComplete(4,'No file has been selected.','','0 of 0 Bytes');"
                scriptManager.RegisterStartupScript(Me, GetType(FileUploadFotosPDF), "progress", js, True)

Visual basic button if query

This is probably very simple, but I need a button to appear if another button is clicked. I am using Visual studio.

This is the process:

  1. If this button is clicked: 'cmdUpdateBooking'
  2. This button will appear: 'cmdUpdate'

Sorry to ask a very simple question. A coded example would be helpful.

ASP.NET FileUpload Not working

The issue is very straightforward. Two days ago everything was working just fine but today, my FileUpload asp control doesn't work. I've made several researches but I haven't seen a code or explanation that solves my problem. This is the code I have.

I will summarize, If you need more code just ask it, I will provide it.

HTML:

<td style="text-align: left;"><asp:FileUpload id="FileUpload1" runat="server" /></td>

The FileUpload is inside a table as you can see nothing more to explain. (I am not using AJAX since I saw that the FileUpload doesn't work with AJAX without some code).

Vb.net:

ruta = ConfigurationManager.AppSettings.Get("RutaFotosDirecciones").ToString()



    id_foto = (DateTime.Now - New DateTime(1970, 1, 1)).TotalMilliseconds / 1000
    Dim path As String = Server.MapPath(ruta)
    Dim fileOK As Boolean = False
    If FileUpload1.HasFile Then
        Dim fileExtension As String
        fileExtension = System.IO.Path. _
            GetExtension(FileUpload1.FileName).ToLower()
        Dim allowedExtensions As String() = _
            {".jpg", ".jpeg", ".png", ".gif"}
        For i As Integer = 0 To allowedExtensions.Length - 1
            If fileExtension = allowedExtensions(i) Then
                fileOK = True
            End If
        Next
        If fileOK Then
            Try
                FileUpload1.PostedFile.SaveAs(path & id_foto & fileExtension)
            Catch ex As Exception
            End Try
        End If
    End If

I am using the Web.config file to set up my path.

The FileUpload1.HasFIle returns false and doesn't enter the if.

Thanks in advance.

How to add columns and data to treeviewadv of aga.controls

Private Class ColumnNode
    Inherits Node
    Public nodeControl11 As String = "" ' This sould make the DataPropertyName specified in the Node Collection.
    Public nodeControl21 As String = ""
    Public nodeControl31 As String = ""
    Public Sub New(ByVal nodeControl1 As String, ByVal nodeControl2 As String, ByVal nodeControl3 As String)
        nodeControl11 = nodeControl1
        nodeControl21 = nodeControl2
        nodeControl31 = nodeControl3
    End Sub
End Class


Private Sub Form2_Load1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim col1 As String = "All Parent"

    Dim col2 As String = "Parent"
    Dim col3 As String = "All "
    Dim mmodel As TreeModel = New TreeModel()

    TreeViewAdv1.UseColumns = True

    Dim nodeControl11 As TreeColumn = New TreeColumn("Matcode", 100)
    Dim nodeControl21 As TreeColumn = New TreeColumn("Title", 200)
    Dim nodeControl31 As TreeColumn = New TreeColumn("Ref", 150)

    TreeViewAdv1.Model = mmodel
    TreeViewAdv1.Columns.Add(nodeControl11)
    TreeViewAdv1.Columns.Add(nodeControl21)
    TreeViewAdv1.Columns.Add(nodeControl31)

    Dim ntb As NodeTextBox = New NodeTextBox()
    ntb.DataPropertyName = "Text"
    ntb.ParentColumn = nodeControl11
    Dim ntb1 As NodeTextBox = New NodeTextBox()
    ntb1.DataPropertyName = "Text"
    ntb1.ParentColumn = nodeControl21
    Dim ntb2 As NodeTextBox = New NodeTextBox()
    ntb2.DataPropertyName = "Text"
    ntb2.ParentColumn = nodeControl31

    TreeViewAdv1.NodeControls.Add(ntb)
    TreeViewAdv1.NodeControls.Add(ntb1)
    TreeViewAdv1.NodeControls.Add(ntb2)
    For i = 0 To 20
        'Dim parentnode As Node = New Node("phild" & i.ToString.Trim)

        Dim parentnode As ColumnNode = New ColumnNode(col1, col2, col3)



        mmodel.Nodes.Add(parentnode)

        For j = 0 To 2
            ' Dim childnode As Node = New Node("child" & j.ToString.Trim)
            Dim childnode As ColumnNode = New ColumnNode(col3, col1, col2)


            parentnode.Nodes.Add(childnode)


        Next j

    Next i


    TreeViewAdv1.Visible = True

End Sub

The above code is what I have converted from C# to vb.net, displayed in the link below how to add items to TreeViewAdv in multi-column mode with winforms

However, it is not producing the desired result. What change shall made in the code to add data for each column and display it in the treeviewAdv?

I am getting +/- and lines, which compels me to anticipate that nodes are created but not displayed.

Any suggestion with a working model please?

VB.NET best practice for applications running for a long time?

I have made an application in vb.net that can sometimes take several hours to finish up, and i have noticed that it will quite often crash while waiting for some processes to finish.

For example:

My app uses Form.Show() to open 3 other forms that are needed in the process of the app. These forms can sometimes take several hours to finish, while they are running, my mainform is inactive, and just waiting for form.formclosing() events to happen, at which point it will then execute clean up codes and exit the app. My problem is, that when the forms that my maincode spawns closes, it sometimes crashes the app with a "System.Reflection.TargetInvocationException" error in the windows log files. I know where it crashes, i just dont know how to prevent it from crashing at this point.

So on mainform.load() i have addhandlers for the forms:

AddHandler Form1.FormClosing, AddressOf Form1Closed
AddHandler Form2.FormClosing, AddressOf Form2Closed

And Boolean Dims for later:

Dim F1Closed As Boolean = False
Dim F2Closed As Boolean = False

The app then displays the forms:

Public sub StartForms()
    form1.Show()
    form2.Show()
end sub

and thats the end of that sub, and the mainform then goes on standby until:

Public Sub Form1Closed()

        F1Closed = True

        If F2Closed = True Then
            CloseApp()
        End If

    End Sub
Public Sub Form2Closed()

    F2Closed = True

    If F1Closed = True Then
        CloseApp()
    End If

End Sub

And my close code:

Public Sub CloseApp()
    Try

        For i As Integer = System.Windows.Forms.Application.OpenForms.Count - 1 To 1 Step -1

            Dim form As Form = System.Windows.Forms.Application.OpenForms(i)

            form.Dispose()
        Next i
    Catch ex As Exception
    Finally
        Me.Dispose()

        Environment.Exit(0)
    End Try
End Sub

During the Form1.FormClosing or Form2.FormClosing, the app just crashes with the invocation error as above.

I cant get any more detail on it, even with a try..catch in the events.

Any help would be much appreciated..