mercredi 6 mai 2015

How to auto fill in text boxes with data from database?

I want to fill all the text boxes with data that corresponds to the name that is chosed on the dropdown box. I have searched for codes for it to work and unluckily none of it works.

PHP

<?php
    include("webconfig.php");
    session_start();    
?>

HTML

<!doctype html>
<html>
<head>
<meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link rel="shortcut icon" href="img/logo_trans.png">
    <link rel="stylesheet" href="css/iconFont.css">
    <link rel="stylesheet" href="css/metro-bootstrap.css">
    <link rel="stylesheet" href="css/metro-bootstrap-responsive.css">

    <script src="js/jquery/jquery.min.js"></script>
    <script src="js/jquery/jquery.widget.min.js"></script>            
    <script src="js/load-metro.js"></script>

    <!-- Local JavaScript -->
    <script src="js/docs.js"></script>
    <script src="js/github.info.js"></script>
    <script src="js/Chart.js"></script>
    <script src="js/metro-dropdown.js"></script>
<title>AS_SIGNS</title>
</head>

<body class="metro">
        <nav class="horizontal-menu" style="background:#037E04;">
            <ul>
             <center><li><a href="index.php"><h1><font color="#FFFFFF">AS Signs</font></h1></a></li></center>
            </ul>
       </nav>

    <div style="width:70%; height:60%; position:absolute; left:0;">
        <div  style="width:100%; height:100%;overflow:scroll; overflow-x:hidden; overflow-y:auto;">
        <div style="width:50%; float:left;">
            <h2>New Service Call</h2>
            <form method="post" name="form">
                    <table  class="table bordered" width="100%">
                    <tr>    
                        <td>Customer ID</td>
                        <td><input type="text" name="custid" /></td>
                    </tr>

                    <tr>    
                        <td>Customer Name</td>
                        <td>
                        <select name="CUSTOMER_NAME" style="width:205px" required>
                                <option value="default"></option>
                                 <?php
                                    $sql1 = "SELECT * FROM CUSTOMER_MASTER";
                                    $sth = ibase_query($conn, $sql1) or die(ibase_errmsg());

                                    $num = '';

                                    while($row = ibase_fetch_assoc($sth))
                                    {


                                    $name = $row["ACCOUNT_NAME"];

                                    echo "<option value=\"$name\">$name</option>";

                                    }
                                ?>


                        </select>
                        </td>   
                        </tr>
                    <tr>
                        <td>Address</td>
                        <td><input type="text" name="ADDRESS" value="<?php echo "$add"?>"></td>
                    </tr>
                    </table>

        </div>
        <div style="width:50%; float:right;">
             <h2 style="visibility:hidden;">cqcqcqcqc</h2>
                    <table  class="table bordered" width="100%">

                    <tr>
                        <td>Contact Person</td>
                        <td><input type="text" name="CONTACT_PERSON" value="<?php echo "$contperson"?>"></td>
                    </tr>
                    <tr>
                        <td>Contact Number</td>
                        <td><input type="text" name="CONTACT_NUMBER" value= "<?php echo "$contnum"?>"> </td>
                    </tr>
                    </table>    
                     <input type="submit" name="btnSave" value="SAVE" />
                     <input type="button" name="load" value="LOAD" />

                    <?php
                    if(isset($_POST['load']))
        {
                    $sql = "SELECT * FROM CUSTOMER_MASTER WHERE CUSTOMER_NAME = '$name'";
                    $result = ibase_query($query, $conn);
                    $details = ibase_fetch_assoc($result);                                  

                    $sth = ibase_query($conn, $sql) or die(ibase_errmsg());

                    $add = $details["ADDRESS"];
                    $name = $_POST["ACCOUNT_NAME"];
                    $servicenum = $details["SERVICE_CALL_NUMBER"];
                    $contperson = $details["CONTACT_PERSON"];
                    $contnum = $details["CONTACT_NUMBER"];


                    }

                    ?>

                    <?php
                    $sql = "SELECT * FROM SERVICE_REPORTS";


                    $sth = ibase_query($conn, $sql) or die(ibase_errmsg());
                    $add = $_POST["ADDRESS"];
                    $name = $_POST["CUSTOMER_NAME"];
                    $servicenum = $_POST["SERVICE_CALL_NUMBER"];
                    $contperson = $_POST["CONTACT_PERSON"];
                    $contnum = $_POST["CONTACT_NUMBER"];



        if(isset($_POST['btnSave']))
        {

            ibase_query($conn, "INSERT INTO SERVICE_REPORTS (CUSTOMER_NAME, ADDRESS, CONTACT_PERSON, CONTACT_NUMBER) VALUES('$name', '$add', '$contperson', '$contnum')") or die (ibase_errmsg());

            echo "Record Saved";
        }


    ?>
          </form>   
        </div>
        </div>
    </div>

  <div class="span5" style="position: absolute;right:0; top:100px;">
        <nav class="sidebar dark">
            <ul>
                <li class="active"><a href="#"><i class="icon-home"></i>Home</a></li>
                <li class="stick bg-red">
                    <a class="dropdown-toggle" href="#"><i class=""></i>Service Call</a>
                        <ul class="dropdown-menu" data-role="dropdown" data-effect="slide">
                            <li><a href="servicecallnew.php">New Service</a></li>
                            <li><a href="#">Service Call List</a></li>
                        </ul>
                </li>                            
                <li class="stick bg-red">
                    <a class="dropdown-toggle" href="#"><i class="icon-sale"></i>File Maintenance</a>
                    <ul class="dropdown-menu" data-role="dropdown" data-effect="slide">
                        <li><a href="items.php?itd=&action">Items</a></li>
                        <li><a href="categories.php">Categories</a></li>
                        <li><a href="contractors.php">Contractors</a></li>
                        <li><a href="suppliers.php">Suppliers</a></li>
                    </ul>
                </li>

                  <li class="stick bg-red">
                    <a class="dropdown-toggle" href="#"><i class="icon-box-add"></i>Production</a>
                    <ul class="dropdown-menu" data-role="dropdown">




                                <li><a href="estimatelist.php">Estimate / Quotation</a></li>
                                <li><a href="bomlist.php">Bill of Materials</a></li>
                                <li><a href="bomposting.php">BOM Posting</a></li>
                                <li><a href="issuancelist.php">Issuance</a></li>
                                <li><a href="adjplist.php">Adjustment</a></li>


                      </ul>
                  </li>


                  <li class="stick bg-red">
                    <a class="dropdown-toggle" href="#"><i class="icon-box-add"></i>Inventory</a>
                    <ul class="dropdown-menu" data-role="dropdown"> 
                                <li><a href="receiving.php">Receiving</a></li>

                      </ul>
                  </li>

                  <li class="stick bg-red">
                    <a class="dropdown-toggle" href="#"><i class="icon-printer"></i>Reports</a>
                    <ul class="dropdown-menu" data-role="dropdown">

                             <!--   <li><a onClick="<?php echo "window.open('report_prod.php?type=estimate','mywindow3')"; ?>">Estimate / Quotation</a></li>
                                <li><a onClick="<?php echo "window.open('report_prod.php?type=bom','mywindow3')"; ?>">Bill of Materials</a></li>
                                <li><a onClick="<?php echo "window.open('report_prod.php?type=issuance','mywindow3')"; ?>">Issuance</a></li>
                                <li><a onClick="<?php echo "window.open('report_prod.php?type=adj','mywindow3')"; ?>">Adjustment</a></li>

                                <li><a onClick="<?php echo "window.open('rptinventory.php?','mywindow8','menubar=0,location=1,status=1,scrollbars=1,width=1000,height=500,left=0,top=0,screenX=50,screenY=100')"; ?>">Inventory</a></li>-->

                                    <li><a href="signspec.php">Sign Spec</a></li>
                                    <li><a href="warehouse.php">Warehouse</a></li>


                      </ul>
                  </li>
                                 <li class="stick bg-red"><a href="#"><i class="icon-cog"></i>Settings</a></li>
                <li class="stick bg-red"><a href="logout.php"><i class="icon-switch"></i>Logout</a></li>
            </ul>
        </nav>
    </div>
</body>
</html>

Configuration of EasyPhp wamp

I am using EasyPhp (easyphp.org)

When I list a directory I can only see the filename with a limited number of characters.

  • ThisIsAnExample.php

  • AndThisIsALongerExampl..>

I managed to expand the with of the table containing the FileName column but the long names are stil croped.

Is there a configuration to allow more characters in the FileName?

Invalid shipping method error message edit in wordpress

Currently I'm using Maya shop WordPress theme. I have done a validation for pincode. If we gave the wrong password means it showing the error message like "Invalid shipping Method" instead of this error message I want my own error message.

How can I achieve this?

Warning (2): session_regenerate_id(): Session object destruction failed

I have setup user login in cakephp with Auth. In core.php I have set sessions to be handled like below so that on every page load the session is renewed

Configure::write('Session', array(
    'defaults' => 'cake',
    'timeout' => 180,
    'cookieTimeout' => 1440,
    'checkAgent' => false,
    'autoRegenerate' => true,
    'requestCountdown' => 1
));

Still sometimes I get this warning:

Warning (2): session_regenerate_id(): Session object destruction failed

And after the next click the user is logged out. Any ideas as to why?

Multi-Color Gradient Fade for Text without CSS?

I'd like help getting this PHP function to work with a third color option.

Note: No CSS. No Javascript. Just PHP and HTML.

<?php

function Gradient($HexFrom, $HexTo, $ColorSteps)
{
        $FromRGB['r'] = hexdec(substr($HexFrom, 0, 2));
        $FromRGB['g'] = hexdec(substr($HexFrom, 2, 2));
        $FromRGB['b'] = hexdec(substr($HexFrom, 4, 2));

        $ToRGB['r'] = hexdec(substr($HexTo, 0, 2));
        $ToRGB['g'] = hexdec(substr($HexTo, 2, 2));
        $ToRGB['b'] = hexdec(substr($HexTo, 4, 2));

        $StepRGB['r'] = ($FromRGB['r'] - $ToRGB['r']) / ($ColorSteps - 1);
        $StepRGB['g'] = ($FromRGB['g'] - $ToRGB['g']) / ($ColorSteps - 1);
        $StepRGB['b'] = ($FromRGB['b'] - $ToRGB['b']) / ($ColorSteps - 1);

        $GradientColors = array();

        for($i = 0; $i <= $ColorSteps; $i++)
        {
                $RGB['r'] = floor($FromRGB['r'] - ($StepRGB['r'] * $i));
                $RGB['g'] = floor($FromRGB['g'] - ($StepRGB['g'] * $i));
                $RGB['b'] = floor($FromRGB['b'] - ($StepRGB['b'] * $i));

                $HexRGB['r'] = sprintf('%02x', ($RGB['r']));
                $HexRGB['g'] = sprintf('%02x', ($RGB['g']));
                $HexRGB['b'] = sprintf('%02x', ($RGB['b']));

                $GradientColors[] = implode(NULL, $HexRGB);
        }
        return $GradientColors;
}

$text = "blah testing blah testing blah";
$length = strlen($text);
$Gradients = Gradient("00FF00", "0000FF", $length);

for ($i=0; $i<$length; $i++) {
    echo '<span style="color: #' . $Gradients[$i] . ';">' . $text[$i] . '</span>';
}


?>

What must I do to get a 3rd option? Such as:

Gradient($HexOne, $HexTwo, $HexThree, $ColorSteps)
                         //^^^^^^^^^

Creating MS File in php using data of MYSQL

<?php
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=document_name.doc");

echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo "<b>My first document</b>";
echo "</body>";
echo "</html>";
?>

This is a code to create MS file with PHP

What I want to is some thing like this:

<?php
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=document_name.doc");

echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo "<b>".$Variable(data from the table)."</b>";
echo "</body>";
echo "</html>";
?>

Is it possible to create an ms file, with the records from the table?

Bootstrap MODAL REGISTRATION not working

I have this code

  <form id="form" role="form" method="post" action="" autocomplete="off" enctype="multipart/form-data">

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">




                <?php
                // Verificar erros
                if(isset($error)){
                    foreach($error as $error){
                        echo '<p class="register-errors">'.$error.'</p>';
                    }
                }

                // Mensagem de sucesso
                if(isset($_GET['action']) && $_GET['action'] == 'joined'){
                    echo "<h2 class='register-sucess'>Registration successful, please check your email to activate your account.</h2> ";
                }
                ?>


    <input type="text" name="username" id="username" class="register-username" placeholder="Username" value="<?php if(isset($error)){ echo $_POST['username']; } ?>" tabindex="1" maxlength="12">


    <br>
    <img id="uploadPreview1" src="../cdn/css/images/no_image.jpg" width="130" height="130"/>

    <input id="uploadImage1" type="file" name="img[]" onchange="PreviewImage(1);" />
           <label for="uploadImage1" >Add profile picture</label>


    <br>



    <input type="email" name="email" id="email" class="register-email" placeholder="Email Address" value="<?php if(isset($error)){ echo $_POST['email']; } ?>" tabindex="2">

    <br>

    <input type="password" name="password" id="password" class="register-password" placeholder="Password" tabindex="3">
    <input type="password" name="passwordConfirm" id="passwordConfirm" class="register-confirmpassword" placeholder="Confirm Password" tabindex="4">

    <br>


    <br>







<?  



if(isset($_POST['submit'])){


        if(strlen($_POST['username']) < 3){
            $error[] = 'Username is too short.';
        } else {
            $stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
            $stmt->execute(array(':username' => $_POST['username']));
            $row = $stmt->fetch(PDO::FETCH_ASSOC);

            if(!empty($row['username'])){
                $error[] = 'Username provided is already in use.';
            }
        }

        if(strlen($_POST['password']) < 3){
            $error[] = 'Password is too short.';
        }

        if(strlen($_POST['passwordConfirm']) < 3){
            $error[] = 'Confirm password is too short.';
        }

        if($_POST['password'] != $_POST['passwordConfirm']){
            $error[] = 'Passwords do not match.';
        }

        if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
            $error[] = 'Please enter a valid email address';
        } else {
            $stmt = $db->prepare('SELECT email FROM members WHERE email = :email');
            $stmt->execute(array(':email' => $_POST['email']));
            $row = $stmt->fetch(PDO::FETCH_ASSOC);

            if(!empty($row['email'])){
                $error[] = 'Email provided is already in use.';
            }

        }


        if(!isset($error)){

            // Proteger a password
            $hashedpassword = $user->password_hash($_POST['password'], PASSWORD_BCRYPT);

            // Criar código de activação
            $activasion = md5(uniqid(rand(),true));

            try {

        $file       = $_FILES['img'];
        $numFile    = count(array_filter($file['name']));

        //PASTA
        $folder     = '../cdn/uploads/avatars/';

        //REQUISITOS
        $permite    = array('image/jpeg', 'image/png');
        $maxSize    = 1024 * 1024 * 1;

        //MENSAGENS
        $msg        = array();
        $errorMsg   = array(
        1 => 'O arquivo no upload é maior do que o limite definido em upload_max_filesize no php.ini.',
        2 => 'O arquivo ultrapassa o limite de tamanho em MAX_FILE_SIZE que foi especificado no formulário HTML',
        3 => 'o upload do arquivo foi feito parcialmente',
        4 => 'Não foi feito o upload do arquivo'
            );

    if($numFile <= 0){
        echo '<script>alert(asd);</script>';
    }
    else{
        for($i = 0; $i < $numFile; $i++){
        $name   = $file['name'][$i];
        $type   = $file['type'][$i];
        $size   = $file['size'][$i];
        $error  = $file['error'][$i];
        $tmp    = $file['tmp_name'][$i];

        $extensao = @end(explode('.', $name));
        $avatar = rand().".$extensao";

        if($error != 0)
            $msg[] = "<b>$name :</b> ".$errorMsg[$error];
        else if(!in_array($type, $permite))
            $msg[] = "<b>$name :</b> Erro imagem não suportada!";
        else if($size > $maxSize)
            $msg[] = "<b>$name :</b> Erro imagem ultrapassa o limite de 1MB";
        else{

        if(move_uploaded_file($tmp, $folder.'/'.$avatar)){


                $stmt = $db->prepare('INSERT INTO members (username,password,email,active,avatar) VALUES (:username, :password, :email, :active, :avatar)');
                $stmt->execute(array(
                    ':username' => $_POST['username'],
                    ':password' => $hashedpassword,
                    ':email' => $_POST['email'],
                    ':active' => $activasion,
                    ':avatar' => $avatar
                ));


     }else{
     $msg[] = "<b>$name :</b> Desculpe! Ocorreu um erro...";

       }
      }
     }
     }

                // Inserir dados na base de dados

                $id = $db->lastInsertId('memberID');

                // Estrutura do email
                $to = $_POST['email'];
                $subject = " Registration Confirmation";
                $body = "Thank you for registering at site.\n\n To activate your account, please click on this link:\n\n ".DIR."activate.php?x=$id&y=$activasion\n\n\n Regards,\n Administration \n\n";
                $additionalheaders = "From: <".SITEEMAIL.">\r\n";
                $additionalheaders .= "Reply-To: ".SITEEMAIL."";
                mail($to, $subject, $body, $additionalheaders);

                header('Location: register.php?action=joined');
                exit;

            } catch(PDOException $e) {
                $error[] = $e->getMessage();
            }

        }

    }


?>

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <input type="submit" name="submit" value="Register" class="btn btn-primary" tabindex="5">
        </form>
      </div>
    </div>
  </div>
</div>

What happens is this, when I give Submit it does not add anything in the database, only makes a refresh on the page. And also like that mistakes appear in Ajax / jQuery without having to refresh the page after submit. Both email errors, user etc .. As the avatar so there mistakes but do not appear: ss

In short, I wanted help to FIX the part of not going anything to the database and show all errors including Avatar. And all of them in ajax without having to refresh the page ..

Please, anyone help me, it's really urgent :ss

Why is my HTML so poorly formatted when rendered with Smarty?

Why is my HTML so poorly formatted when viewing the source code?

Working with:

  1. WAMPSERVER (64 BITS & PHP 5.5) 2.5

  2. Slim Framework v2

  3. RedBeanPHP 4.2

  4. Smarty 3.1.21


index.php:

<?php

// load required files
require 'class/Slim/Slim.php';
require 'class/RedBean/rb.php';

// register slim auto-loader
\Slim\Slim::registerAutoloader();

// set up database connection
R::setup('mysql:host=localhost;dbname=slimcms','root','');
R::freeze(true);


// initialize app
$app = new \Slim\Slim(array(
    'mode' => 'development'
    ,'debug' => true
    ,'view' => new \Slim\Views\Smarty()
    ,'templates.path' => './templates'
));


$view = $app->view();

$view->parserDirectory = dirname(__FILE__) . '/class/Smarty/';
$view->parserCompileDirectory = dirname(__FILE__) . '/compiled';
$view->parserCacheDirectory = dirname(__FILE__) . '/cache';



// handle GET request for index
$app->get('/', function() use ($app){
    $books = R::findAll('book');
//print_r($books);
    $app->render('home.tpl',array('books'=>$books));

});


$app->run();


templates/home.tpl:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Home</title>
</head>
<body>    
    <div id="content">
        {foreach name=aussen item=book from=$books}
            {foreach key=key item=value from=$book}
                {if $key == 'id' }
                    <a href="{$key}/{$value}">{$key}</a>
                {else}{$key}{/if}
            {/foreach}
            <hr />
        {/foreach}
    </div>    
</body>
</html>


when i view the sourcecode via chrome:

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Home</title>
</head>
<body>
    <div id="content">
                                                        <a href="id/1">id</a>
                                            rating                            price                            title                        <hr />
                                                        <a href="id/2">id</a>
                                            rating                            price                            title                        <hr />
            </div>
</body>
</html>

I would have expected:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <title>Home</title>
</head>
<body>
    <div id="content">
        <a href="id/1">id</a> rating price title
        <hr>
        <a href="id/2">id</a> rating price title
        <hr>
    </div>
</body>
</html>

Symfony2 updating the values and displaying them without refresh with ajax

first of all I want to say that im not an expert in front-end, and this is my first time digging in to ajax. So this is what I want to do:

I want to change and show the updated value without the full pages refresh.. The only thing I want to update is the input field with its values and thats it. How can I update only that portion of the code?

This is my twig(when i press the + button i increase the quantity of the product and i want the twig to update it without refreshing the whole page. Like in any standard shopping cart):

{% for key, item in cart %}

                {% if key == info.id %}

                    <div class="input-append">

                    <input class="span1" style="max-width:34px" placeholder="{{ key }}" value="{{ item }}" id="appendedInputButtons" size="16" type="text" data-id="{{ key }}"/>
                    <a href="javascript:void(0)" class="remove btn"><i class="icon-minus"></i></a>
                    <a href="javascript:void(0)" class="add btn"><i class="icon-plus"></i></a>

                    {% endif %}

                    {% endfor %}

And this is the script:

$(document).ready(function () {
    $(document).on('click', '.add', function (e) {
    $this = $(this);   
    $.ajax({
        type: 'POST',
        url: 'add/quantity',
        dataType: 'JSON',
        data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
        success: function (data) {      
          if(data.success == false){
           alert('error')
          }else{
            document.location.reload(true);
           }
        }
    });
});   
});

currently I only have the document.location.reload(true); which reloads the full page, how can I change that code?

Laravel echo strange characters

Hey i wan't to echo something with belongsTo but the output gives me some strange characters back.

class Leviews extends Entity
{
public $table = 'reviews';


public function ravatar()
{
  return $this->belongsTo('User', 'author', 'username')->select('avatar');

}

now when i echo the data with {{ $item->ravatar }} im getting this

{"avatar":"avatars\/1.jpg"} 

and it should be

avatars/1.jpg    

what im doing wrong?

edit here is the Controller

<?php

use Carbon\Carbon;
use Lib\Reviews\LeviewsRepository;
use Lib\Services\Scraping\Scraper;
use Lib\Services\Validation\LeviewsValidator;

class LeviewsController extends \BaseController {

/**
 * Leviews repository instance.
 * 
 * @var Lib\Leviews\LeviewsRepository
 */
protected $repo;

/**
 * validator instance.
 * 
 * @var Lib\Services\Validation\LeviewsCreateValidator
 */
private $validator;

/**
 * Leviews scraper isntance.
 * 
 * @var Lib\Services\Scraping\NewScraper;
 */
private $scraper;

public function __construct(LeviewsRepository $lreviews, LeviewsValidator $validator, Scraper $scraper)
{
    $this->beforeFilter('csrf', array('on' => 'post'));
    $this->beforeFilter('logged', array('except' => array('index', 'show', 'paginate')));
    $this->beforeFilter('news:create', array('only' => array('create', 'store')));
    $this->beforeFilter('news:edit', array('only' => array('edit', 'update')));
    $this->beforeFilter('news:delete', array('only' => 'destroy'));
    $this->beforeFilter('news:update', array('only' => 'updateFromExternal'));

    $this->repo = $lreviews;
    $this->scraper = $scraper;
    $this->validator = $validator;
}

/**
 * Display list of paginated news.
 *
 * @return View
 */
public function index()
{
    return View::make('Leviews.Index');
}

/**
 * Display form for creating new news items.
 *
 * @return View
 */
public function create()
{
    return View::make('Leviews.Create');
}

/**
 * Store a newly created news item.
 *
 * @return Redirect
 */
public function store()
{
    $input = Input::except('_token');

    if ( ! $this->validator->with($input)->passes())
    {
        return Redirect::back()->withErrors($this->validator->errors())->withInput($input);
    }

    //escape double qoutes
    $input['title'] = htmlspecialchars($input['title']);

    $this->repo->store($input);

    return Redirect::back()->withSuccess( trans('main.news create success') );
}

/**
 * Display single news items.
 *
 * @param  int  $id
 * @return View
 */
public function show($id)
{
    $lreviews = $this->repo->byId($id);

    if ($lreviews->full_url && ! $lreviews->fully_scraped)
    {
        $lreviews = $this->repo->getFullLeviewsItem($lreviews);
    }

    return View::make('Leviews.Show')->with(compact('news'))->withRecent($this->repo->latest());
}

/**
 * Displays form for editing news item.
 *
 * @param  int  $id
 * @return View
 */
public function edit($id)
{
    $lreviews = $this->repo->byId($id);

    return View::make('Leviews.Edit')->withLeviews($lreviews);
}

/**
 * Updates the news item.
 *
 * @param  int  $id
 * @return Redirect
 */
public function update($id)
{
    $input = Input::except('_token', '_method');

    $lreviews = $this->repo->byId($id);

    if ($lreviews->title === $input['title'])
    {
        //dont check for title uniqueness when updating if
        //title was not updated.
        $this->validator->rules['title'] = 'required|min:2|max:255';
    }

    if ( ! $this->validator->with($input)->passes())
    {
        return Redirect::back()->withErrors($this->validator->errors())->withInput($input);
    }

    //escape double qoutes
    $input['title'] = htmlspecialchars($input['title']);

    $this->repo->update($lreviews, $input); 

    return Redirect::back()->withSuccess( trans('main.news update success') );
}

/**
 * Delete specified news item.
 *
 * @param  int  $id
 * @return Response
 */
public function destroy($id)
{
    $this->repo->delete($id);       

    return Response::json(trans('main.news delete success'), 200);
}

/**
 * Updates news from external sources.
 * 
 * @return void
 */
public function updateFromExternal()
{
    $this->scraper->updateLeviews();

    Event::fire('Leviews.Updated', Carbon::now());

    return Redirect::back()->withSuccess( trans('dash.updated news successfully') );
}

}

and here the view

    @if ($options->enableNews())

                @foreach($lreviews as $k => $item)

                    {{ $item->body }}
                    {{ $item->ravatar }}

                @endforeach

    @endif

{{ $item->body }} is without strange characters

decode json object sent form android app to php server

I am sending json object from android as such:

//Create JSONObject here
                    JSONObject json = new JSONObject();
                    json.put("key", String.valueOf(args[0]));

                    String postData=json.toString();

                    // Send POST output.
                    printout = new DataOutputStream(urlConn.getOutputStream ());
                    printout.writeUTF(URLEncoder.encode(postData,"UTF-8"));
                    Log.i("NOTIFICATION", "Data Sent");
                    printout.flush ();
                    printout.close ();

When it is sent to the server it looks like the following code snippet. ???%7B%22key%22%3A%22value%22%7D I should add the first ??? are in a diamond each. When I decode the whole json object I get null. In the php server I have

$somevar=json_decode(json, true);

which returns null. Can someone point me on how to retrieve the json value? Thanks so much:)

Paypal IPN INVALID & No POST

I'm trying to use paypal ipn but I don't receive any posts from paypal and the result is always invalid.

I need you kind help.

I'm using the code below :

<?php

// STEP 1: read POST data

// Reading POSTed data directly from $_POST causes serialization issues with array data in the POST.
// Instead, read raw POST data from the input stream. 
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
  $keyval = explode ('=', $keyval);
  if (count($keyval) == 2)
     $myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the IPN message sent from PayPal and prepend 'cmd=_notify-validate'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
   $get_magic_quotes_exists = true;
} 
foreach ($myPost as $key => $value) {        
   if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) { 
        $value = urlencode(stripslashes($value)); 
   } else {
        $value = urlencode($value);
   }
   $req .= "&$key=$value";
}


// STEP 2: POST IPN data back to PayPal to validate

$ch = curl_init('http://ift.tt/xpRUtH');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));

// In wamp-like environments that do not come bundled with root authority certificates,
// please download 'cacert.pem' from "http://ift.tt/piTBkz" and set 
// the directory path of the certificate as shown below:
// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
if( !($res = curl_exec($ch)) ) {
    // error_log("Got " . curl_error($ch) . " when processing IPN data");
    curl_close($ch);
    exit;
}
curl_close($ch);


// STEP 3: Inspect IPN validation result and act accordingly

if (strcmp ($res, "VERIFIED") == 0) {
    // The IPN is verified, process it:
    // check whether the payment_status is Completed
    // check that txn_id has not been previously processed
    // check that receiver_email is your Primary PayPal email
    // check that payment_amount/payment_currency are correct
    // process the notification

    // assign posted variables to local variables
    $item_name = $_POST['item_name'];
    $item_number = $_POST['item_number'];
    $payment_status = $_POST['payment_status'];
    $payment_amount = $_POST['mc_gross'];
    $payment_currency = $_POST['mc_currency'];
    $txn_id = $_POST['txn_id'];
    $receiver_email = $_POST['receiver_email'];
    $payer_email = $_POST['payer_email'];

    // IPN message values depend upon the type of notification sent.
    // To loop through the &_POST array and print the NV pairs to the screen:
    foreach($_POST as $key => $value) {
      echo $key." = ". $value."<br>";
    }
} else if (strcmp ($res, "INVALID") == 0) {
    // IPN invalid, log for manual investigation
    echo "The response from IPN was: <b>" .$res ."</b>";

        // assign posted variables to local variables
    $item_name = $_POST['item_name'];
    $item_number = $_POST['item_number'];
    $payment_status = $_POST['payment_status'];
    $payment_amount = $_POST['mc_gross'];
    $payment_currency = $_POST['mc_currency'];
    $txn_id = $_POST['txn_id'];
    $receiver_email = $_POST['receiver_email'];
    $payer_email = $_POST['payer_email'];

    // IPN message values depend upon the type of notification sent.
    // To loop through the &_POST array and print the NV pairs to the screen:
    foreach($_POST as $key => $value) {
      echo $key." = ". $value."<br>";
    }

}


?>

Thank you for your help in advance.

Kindly ignore the text below:

It looks like your post is mostly code; please add some more details.

It looks like your post is mostly code; please add some more details.

It looks like your post is mostly code; please add some more details.

It looks like your post is mostly code; please add some more details.

script error in javascript

I have an script prices table in javascript and jquery.. and is not working the paypal button and the error functions.. I tryed in my phone and is working property only from pc is not working..

This is my script:

<?
include("../../config.php"); 

   session_start();
    if(!isset($_SESSION['login'])) die;
    $dbres  = mysql_query("SELECT *,UNIX_TIMESTAMP(`online`) AS `online` FROM `users` WHERE `login`='{$_SESSION['login']}'");
$data   = mysql_fetch_object($dbres);
    ?>
<div id="sett-title"> Simple. Easy. Affordable. </div>
We have made the process of buying social media services ultra simple and user friendly. Just simply follow these steps.
</br>
<a class="glyphicons circle_arrow_right"><i></i></a>Choose a service from below</br>
<a class="glyphicons circle_arrow_right"><i></i></a>Select your package</br>
<a class="glyphicons circle_arrow_right"><i></i></a>Enter your details (URL, username etc.)</br>
<a class="glyphicons circle_arrow_right"><i></i></a>Pay for your order</br>
<a class="glyphicons circle_arrow_right"><i></i></a>We deliver your order within 72 hours.</br>

</br>
<div class="infobox"><center>
<a href="javascript:void(0)" onclick="$('#content').load('fb.php'); window.location.hash = 'Shop';" class="button" style="width:120px;text-align:center">Facebook</a></center></div>
<hr style="margin: 20px 20px 20px 20px">
<div align="center">

<table width="100%"><tr><td>
<?php
  $queryRes = mysql_query("SELECT * FROM `shop` ORDER BY `id` ASC");
for($j=1; $shop = mysql_fetch_object($queryRes); $j++) {

?>
<div class="buy_boxs">
        <table width="100%">
            <tr style="height:40px">


                        <div id="title-premium-boxs"><span style="margin: 30px"><span class="glyphicons face"><i></i><?=$shop->name?> </span></span></div>

                    <div class="gray-area">24-72 hour delivery</div>
                    <ul class="special" style="margin: 10px 22px 10px 40px">



<li>
<strong><?=$shop->nr1?></strong>
<?=$shop->media?>
<span class="away">$<?=$shop->price1?></span>
</li>
<li>
<strong><?=$shop->nr2?></strong>
<?=$shop->media?>
<span class="away">$<?=$shop->price2?></span>
</li>
<li>
<strong><?=$shop->nr3?></strong>
<?=$shop->media?>
<span class="away">$<?=$shop->price3?></span>
</li>
<li>
<strong><?=$shop->nr4?></strong>
<?=$shop->media?>
<span class="away">$<?=$shop->price4?></span>
</li>
<li>
<strong><?=$shop->nr5?></strong>
<?=$shop->media?>
<span class="away">$<?=$shop->price5?></span>
</li>
</ul></a>




               <script language="javascript">
                   function setPrice<?=$j?>()
                   {

                       value              = $("#item_number<?=$j?> :selected").val();
                       option_text<?=$j?> = $("#item_number<?=$j?> :selected").text();
                       arr_data<?=$j?>    = option_text<?=$j?>.split("—");
                       price<?=$j?>       = arr_data<?=$j?>[1].replace('$','');
                       custom<?=$j?>      = $("#custom<?=$j?>").val();

                      $("#item_name<?=$j?>").val(option_text<?=$j?>+' '+custom<?=$j?>);
                      $("#item_number<?=$j?>").val(value);
                      $("#amount<?=$j?>").val(price<?=$j?>);

                   }
                </script>       

                <select class="selection" name="item_number<?=$j?>" id="item_number<?=$j?>" style="margin: 10px 22px 10px 25px; width: 201px" onchange="setPrice<?=$j?>();">
                        <option value="">Select</option>
                        <option data-price="15" value="TF1000"> <?=$shop->nr1?> <?=$shop->media?> — $0.02 </option>
                        <option data-price="20" value="TF5000"> <?=$shop->nr3?> <?=$shop->media?> — $<?=$shop->price2?> </option>
                        <option data-price="30" value="TF10000"> <?=$shop->nr3?> <?=$shop->media?> — $<?=$shop->price3?> </option>
                        <option data-price="75" value="TF50000"> <?=$shop->nr4?> <?=$shop->media?> — $<?=$shop->price4?> </option>
                        <option data-price="150" value="TF100000"> <?=$shop->nr5?> <?=$shop->media?> — $<?=$shop->price5?> </option>
                </select>
                    <div class="gray-area extrapadding">
<input style="margin: -14px 23px 10px 25px; width: 188px;" type="text" placeholder="<?=$shop->placeholder?>" name="custom<?=$j?>" id="custom<?=$j?>">
</div>


                <script language="javascript">
                 function checkerror<?=$j?>()
                 {

                    value              = $("#item_number<?=$j?> :selected").val();
                    option_text<?=$j?> = $("#item_number<?=$j?> :selected").text();
                    custom<?=$j?>      = $("#custom<?=$j?>").val();
                    $("#item_name<?=$j?>").val(option_text<?=$j?>+' '+custom<?=$j?>);


                    custom<?=$j?>      = $("#custom<?=$j?>").val();

                    if(custom<?=$j?>=="")
                    {
                      alert("Fanpage URL / Facebook Username is a required filed");
                      return false;
                    }

                 }
                </script>

                    <div style="text-align:right">
<form action="http://ift.tt/rDmnwQ" method="post" onsubmit="return checkerror<?=$j?>();">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" id="business" value="mail@yahoo.com">
<input type="hidden" name="item_name" id="item_name<?=$j?>"  value="<? echo $site->site_brand;?> <? echo $pack->name;?>">
<input type="hidden" name="item_number" id="item_number<?=$j?>" value="<? echo $pack->coins;?>+ Credits">
<input type="hidden" name="custom" value="<? echo $data->id; ?>">
<input type="hidden" name="amount" id="amount<?=$j?>" value="<? echo $pack->price;?>">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="button_subtype" value="services">
<input type="hidden" name="no_note" value="1">
<input type="hidden" name="no_shipping" value="2">
<input type="hidden" name="rm" value="1">
<input type="hidden" name="return" value="<?echo $site->site_url;?>/return.php">
<input type="hidden" name="cancel_return" value="<?echo $site->site_url;?>">
<input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynow_LG.gif:NonHosted">
<input type="hidden" name="notify_url" value="<?echo $site->site_url;?>/ipn.php">
<!--<input style="width:80px;border:none;background:none;" type="image" src="http://ift.tt/18UOXym" name="submit" alt="PayPal - The safer, easier way to pay online!" /><img alt="" src="http://ift.tt/qzX37J" width="1" height="1" />-->
<input style="width: 151px;border: 1px solid #b6b6b6; margin: 10px 22px 10px 25px; width: 201px" type="submit" name="submit"  value="Buy Now" class="button" />

</form>




                            </div>

                </td>

            </tr>

        </table>

</div>      
<?php } ?>

</td></tr></table>

<br clear="all">
<br>
<b><?=$lang['sp85']?></b><br>
<br>
<span style="font-size: 10pt;font-family: Arial;"><?=$lang['sp86']?></span>
<?

If I use this script without javascript is working..

For see live:

http://goo.gl/5kYwtQ (working version)

usr: xdesign pass: carina

For see here is not working.. click in the menu "Shop" buton.

Thank you very much for your help

Magento: if statement not functioning correctly

I am having an issue getting my if statement to function the way I want it. I have an Appointment Maker that shows up on the bottom of every page. Say they submit the form on the homepage/contact/about page, I want that to direct them to the /success/ page. Now say they are on a product detail page, which they more than likely will, I just want it to revert the success indicator back onto that specific product page they were on to begin with.

This is the coding I have at the moment:

$product = Mage::getModel('catalog/product')->load($data['product_id']);
   Mage::getSingleton('catalog/session')->addSuccess(Mage::helper('appointmentmaker')->getSuccessMessage());
    if($product) {
        $this->_redirectUrl($product->getProductUrl());
    } else {
        $this->_redirectUrl('/success/');
    }
    return; 

I can get the product redirect to work. But if they submit from the homepage, it will try to find the product detail page which of course there isn't one. It doesn't try to use the /success/ page instead.

HTML/PHP Form doesn't sent data to MySQL Database

Hi this is my first question, so tell me if i do something wrong. I'm new to PHP so this is kinda new to me. Anyway im creating a site so i can access my recepies online.

This is the form:

<form action="Form.php" method="post" class="basic-grey">
<h1><a href="index.html">Receita</a>
    <span>Aqui podes adicionar uma nova receita</span>
</h1>
<label>
    <span>Titulo :</span>
    <input id="titulo" type="text" size="20" maxlength="100" name="titulo" placeholder="Introduza o Titulo" />
</label>

<label>
    <span>Categoria :</span><select  maxlength="10" name="categoria">
    <option value="categoria">--- Seleccione aqui a Categoria ---</option>
    <option name=" " value="sopa">Sopa</option>
    <option name="entrada" value="entrada">Entrada</option>
    <option name="carne" value="carne">Carne</option>
    <option name="peixe" value="peixe">Peixe</option>
    <option name="salada" value="salada">Salada</option>
    <option name="sobremesa" value="sobremesa">Sobremesa</option>
    </select>

</label>

<label>
    <span>Ingredientes :</span>
    <textarea id="ingredientes" size="20" maxlength="1000" name="ingredientes" placeholder="Introduza os ingredientes"></textarea>
</label> 
<label>
    <span>Preparação :</span>
    <textarea id="preparacao" size="20" maxlength="1000" name="preparacao" placeholder="Introduza o modo de preparação"></textarea>
</label> 
<label>
    <span>Notas :</span>
    <textarea id="notas" size="20" maxlength="1000" name="notas" placeholder="Aqui pode adicionar uma nota"></textarea>
</label> 
<label>
    <span>&nbsp;</span> 
    <input type="submit" class="button" value="Enviar" /> 
</label>   

</form>

This is the code to handle the form:

<?php
// processing form values


if ($_SERVER['REQUEST_METHOD'] == 'POST'){

$titulo = $_POST['titulo'];
$categoria = $_POST['categoria'];
$ingredientes = $_POST['ingredientes'];
$preparacao = $_POST['preparacao'];
$notas = $_POST['notas'];


if(!empty($titulo) && !empty($categoria) && !empty($ingredientes) && !empty($preparacao) && !empty($notas)){

    include('connection.php');

    mysqli_query($dbc, "INSERT INTO receita(Titulo,Categoria,Ingredientes,Preparacao,Notas) VALUES ('$titulo','$categoria','$ingredientes','$preparacao','$notas')");
    $registered = mysqli_affected_rows($dbc);
    echo $registered." row is affected, everything worked fine!";
}else{
    echo "Please fill all values on the form";
}

}else{

echo "No form has been submitted";

}

?>

And what happens its that if i input something like this it doesn't work:

Titulo:Açorda de camarao

Categoria: Peixe

Ingredientes: 800 g de camarao; 4 dentes de alho; 1 ramo de salsa ou coentros; 3 ovos inteiros; 1.5 dl de Azeite; 1.5 pão por pessoa; sal; piri-piri

Preparação: Coze-se o camarão com sal e piri-piri e reserva-se a agua. De seguida demolha-se o pão na agua do camarão. Aquece-se o azeite com os alhos e os coentros e de seguida junta-se o camarão e por ultimo o pão. Mexe-se tudo para cozer o pão e ganhar consistencia. Por ultimo junta-se os ovos e envolve-se tudo.

Nota: Receita para 4 pessoas

But if i input like this it works:

Titulo:gfdsfdsa

Categoria: Peixe

Ingredientes: hudsbfbdsf fdsfidsfidsfsd, fdsjifjdsifdis 0palpdsandnsaud jkdosakodsakodmnsa jidsjaidsa

Preparação: nfjdbshfbhdbjfdjs dsajijdisandiabuu fjndoisjfojidsanfds

Nota: fbhdubsufbndsnfs

My database table:

Nome    Tipo    Agrupamento (Collation) Atributos   Nulo    Omissao Extra   

1 ID bigint(50) Não None AUTO_INCREMENT Muda Muda Elimina
2 Titulo varchar(100) utf8_general_ci Não None Muda Muda Elimina 3 Categoria varchar(10) utf8_general_ci Não None Muda Muda
4 Ingredientes varchar(1000) utf8_general_ci Não None Muda 5 Preparacao varchar(1000) utf8_general_ci Não None Muda Muda 6 Notas varchar(1000) utf8_general_ci Não None Muda Muda

Sorry if this post its to long. Any ideas how to fix it?

Space and special characters problems on post

I got a problem with blank space and special characters during a POST action using this AJAX function:

function comments(id,postId,user_id) {
        var user_comments = encodeURIComponent($("#commentsId_"+id).val());
        if(user_comments!=''){
            var img = $("#img_"+id).val();
            var username = "<?php echo $this->session->userdata('username'); ?>"
            $.ajax({
                    type: "POST",
                    url: "<?php echo base_url() ?>social/userscomment/" +user_id+"/"+postId+"/"+user_comments,
                    data:{ user_comments : user_comments},
                    success: function(data) { 
                        $("#commentsId_"+id).val('');
                        var $sparkLines = $('.comments_body_'+id);
                        $("#comments_add_"+id).append('<div id="id' + ($sparkLines.length + 1) + '" class="comments_body_"'+id+'><div class="feed-element comments_body_"'+id+'><a class="pull-left"><strong>'+username+' <i class="fa fa-comment-o"></i></strong></a><div class="media-body">'+user_comments+'<br></div><div class="col-lg-12"><a id="span_'+postId+'" onclick="callajaxcommcool('+postId+')" class="btn btn-xs btn-white"><i class="fa fa-star"></i><span id="span1_'+postId+'" style="display:none;">1</span> Cool </a></div></div></div></div>');
                    }
            });
        }
    }

The PHP controller:

public function userscomment($comment_id,$post_id,$user_comments){

    $this->load->model('comments');

    $user_comments = utf8_decode(trim(mysql_real_escape_string($user_comments)));

    if(!empty($user_comments)){

        $data = array("user_id"         => $this->session->userdata('user_id'),
                      "comment_user_id" => $comment_id,
                      "comments"        => $user_comments,
                      "post_id"         => $post_id,
                      "username"        => $this->session->userdata('username')
                );
        $this->comments->insertComments($data);

        //logged user
       $userRow = $this->register->get_login($this->session->userdata('user_id'));
       redirect('social/userprofile/'.$userRow[0]['username']);
    }
}    

When an user post a comment like: "a b c d" the results showed in the view is: a%20b%20c%20d, if an user try to wrote a special characters like € i got this results %E2%82%AC

How can i prevent this problem?

Presenting an integer in a non standard money format with PHP

I am working on a PHP script that will be used as part of an RPG. The value of money is stored as an integer but needs to be presented slightly differently.

For example if the value is 125050 then it should be shown as 12 gold, 50 silver and 50 copper. However to complicate matters further sometimes the code will be used for a different system where 10 of each is equal to the next so 125050 would be 1250 gold, 5 silver (and no copper). Also some sessions will call for the use of a fourth currency unit (platinum, probably) which will follow the same pattern.

Given that I know that unit divisor is going to be 10 or 100 I need a method of presenting the integer value in the correct format. How can do this?

I did toy with the idea of casting the int to string and picking of the characters but I would rather use a purely mathematical approach so that I can also separate the int into an array of int like this:

// 125050
//  =
$money(
    'copper'=>50,
    'silver'=>50,
    'gold'=>12,
    'platinum'=>0
); 

How to display array of json data properly in html?

My Ajax

$("form").on("submit", function () {
    var data = {
        "action": "test"
    };

    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "ajax2.php", //Relative or absolute path to response.php file
        data: data,
        success: function (data) {

            $("#main_content").slideUp("normal",function(){

            $(".the-return").html("<br />JSON: " + data);
//how to alter this part to display data for each record in one div?

            });
        }
    });
    return false;

});

My query

$statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
    $statement->execute(array(':key2' => $key2,':postcode2'=>$postcode));
 // $row = $statement->fetchAll(PDO::FETCH_ASSOC);
  $json = array();
 while( $row = $statement->fetch()) {
     array_push($json, array($row['Name'], $row['PostUUID']));
 }

    header('Content-Type: application/json');
    echo json_encode($json);

The result displayed currently in this form:

JSON: jack,55421894ab602,test,55439324cc43d

But I want to display like:

 Name:jack,
 Id:55421894ab602
.....and some other info-

 Name:test
 Id:55439324cc43d
.....and some other info-

This part:

$(".the-return").html("<br />JSON: " + data);

I tried: data[0]; But when I do this, only the first record displayed obviously.

What I'm trying is :

data[0] itself is an array. How to display that array together with other records fetched in nice html?

edited: WIth these edited code, i can only retrieve the last result, it's not looping through the array.

ajax success: function (data) {

            $("#main_content").slideUp("normal",function(){

            //$(".the-return").html("<br />JSON: " + j_data);
            for (i = 0; i < data.length; i++) {
            $(".the-return").html("<div>Name:" + data[i].name + "<br/>Id:" + data[i].id);
        }
            console.log(data); // this shows nothing in console,I wonder why?
            //alert(j_data);
            });
        }

php

$json = array();
 while( $row = $statement->fetch()) {
     //array_push($json, array($row['Name'], $row['PostUUID']));
     array_push($json, array("name" => $row['Name'], "id" => $row['PostUUID']));
 }

    header('Content-Type: application/json');
    echo json_encode($json);

Looping name attribute[] in PHP to INSERT into database from JSON

Think im finally at the last bit of this invoice creation tool im creating, so everything is passed from JSON aJAX which is all passing to the PHP function fine however im note sure ive got the loop working for the invoice items, can someone help me?

You will see the multiple products i need to loop to add to invoice_items table.

invoice_product[] etc.. in results below - its actually not adding anything and return the json error (bottom of PHP code) so not sure if its because of that but if anyone can spot in the PHP that might be causing that would be great as well :)

Thanks in advance for help on this!

Example of data being passed:

action  create_invoice
customer_address_1  5 Some Road
customer_address_1_ship 5 Some Road
customer_address_2  Epping
customer_address_2_ship Epping
customer_county Essex
customer_county_ship    Essex
customer_email  james@ambientlounge.com
customer_name   James Brandon
customer_name_ship  James Brandon
customer_phone  0748646013845
customer_postcode   CM16 8DD
customer_postcode_ship  CM16 8DD
customer_town   Epping
customer_town_ship  Epping
invoice_date    14/05/2015
invoice_discount    130.50
invoice_due_date    20/05/2015
invoice_id  AMBMN0001
invoice_product[]   Versa Table - Wildberry
invoice_product[]   Versa Table - Aubergine
invoice_product[]   Versa Table - Tundra Spring
invoice_product_discount[]  10%
invoice_product_discount[]  
invoice_product_discount[]  70.50
invoice_product_price[] 200
invoice_product_price[] 200
invoice_product_price[] 200
invoice_product_qty[]   3
invoice_product_qty[]   2
invoice_product_qty[]   1
invoice_product_sub[]   540.00
invoice_product_sub[]   400.00
invoice_product_sub[]   129.50
invoice_shipping    23
invoice_subtotal    1069.50
invoice_total   1092.50
invoice_vat 213.90

PHP

// Create invoice
if ($action == 'create_invoice'){

    // invoice customer information
    // billing
    $customer_name = $_POST['customer_name']; // customer name
    $customer_email = $_POST['customer_email']; // customer email
    $customer_address_1 = $_POST['customer_address_1']; // customer address
    $customer_address_2 = $_POST['customer_address_2']; // customer address
    $customer_town = $_POST['customer_town']; // customer town
    $customer_county = $_POST['customer_county']; // customer county
    $customer_postcode = $_POST['customer_postcode']; // customer postcode
    $customer_phone = $_POST['customer_phone']; // customer phone number

    //shipping
    $customer_name_ship = $_POST['customer_name_ship']; // customer name (shipping)
    $customer_address_1_ship = $_POST['customer_address_1_ship']; // customer address (shipping)
    $customer_address_2_ship = $_POST['customer_address_2_ship']; // customer address (shipping)
    $customer_town_ship = $_POST['customer_town_ship']; // customer town (shipping)
    $customer_county_ship = $_POST['customer_county_ship']; // customer county (shipping)
    $customer_postcode_ship = $_POST['customer_postcode_ship']; // customer postcode (shipping)

    // invoice product items
    foreach($_POST['invoice_product'] as $key => $value) {
        $item_product = $value;
        // $item_description = $_POST['invoice_product_desc'][$key];
        $item_qty = $_POST['invoice_product_qty'][$key];
        $item_price = $_POST['invoice_product_price'][$key];
        $item_discount = $_POST['invoice_product_discount'][$key];
        $item_subtotal = $_POST['invoice_product_sub'][$key];
    }

    // invoice details
    $invoice = $_POST['invoice_id']; // invoice number
    $invoice_date = $_POST['invoice_date']; // invoice date
    $invoice_due_date = $_POST['invoice_due_date']; // invoice due date
    $invoice_subtotal = $_POST['invoice_subtotal']; // invoice sub-total
    $invoice_shipping = $_POST['invoice_shipping']; // invoice shipping amount
    $invoice_discount = $_POST['invoice_discount']; // invoice discount
    $invoice_vat = $_POST['invoice_vat']; // invoice vat
    $invoice_total = $_POST['invoice_total']; // invoice total

    // insert invoice into database
    $query = "INSERT INTO invoices SET
                invoice = '".$invoice."',
                date = '".$invoice_date."',
                due_date = '".$invoice_due_date."',
                subtotal = '".$invoice_subtotal."',
                shipping = '".$invoice_shipping."',
                discount = '".$invoice_discount."',
                vat = '".$invoice_vat."',
                total = '".$invoice_total."';
            ";

    // insert invoice items into database
    $query .= "INSERT INTO invoice_items SET
        invoice = '".$invoice."',
        product = '".$item_product."',
        qty = '".$item_qty."',
        price = '".$item_price."',
        discount = '".$item_discount."',
        subtotal = '".$item_subtotal."';
    ";

    // insert customer details into database
    $query .= "INSERT INTO customers SET
                name = '".$customer_name."',
                email = '".$customer_email."',
                address_1 = '".$customer_address_1."',
                address_2 = '".$customer_address_2."',
                town = '".$customer_town."',
                county = '".$customer_county."',
                postcode = '".$customer_postcode."',
                phone = '".$customer_phone."',

                name_ship = '".$customer_name_ship."',
                address_1_ship = '".$customer_address_1_ship."',
                address_2_ship = '".$customer_address_2_ship."',
                town_ship = '".$customer_town_ship."',
                county_ship = '".$customer_county_ship."',
                postcode_ship = '".$customer_postcode_ship."';
            ";

    header('Content-Type: application/json');

    // execute the query
    if($mysqli -> query($query)){
        //if saving success
        echo json_encode(array(
            'status' => 'Success',
            'message' => 'Invoice has been create successfully!'
        ));
    } else {
        // if unable to create invoice
        echo json_encode(array(
            'status' => 'Error',
            'message' => 'There has been an error, please try again.<pre>'.$query.'</pre>'
        ));
    }

    //close database connection
    $mysqli->close();

}

Traversing HTML DOM Elements in foreach loop

I have this segment of code here

<table>
    <thead>
        <th>Title One</th>
        <th>Title Two</th>
        <th>Title Three</th>
    </thead>
    <tbody>
        <?php foreach ($foos as $foo): ?>
            <tr>
                <td id="x"><?php echo $foo->bar1; ?></td>
                <td id="y"><?php echo $foo->bar2; ?></td>
                <td id="z"><?php echo $foo->bar3; ?></td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<script type="text/javascript">
    $('#x').on('click', function(){
        console.log($(this).html());
    });
</script>

Suppose I have 10 rows of data there, how will I be able to reference the exact element I have clicked? For example row number 5, how will jQuery know that I have clicked row 5? I can't go writing <td id="x1">,<td id="x2">,<td id="x3">,<td id="x4"> because I can be having a thousand records.

Any help will be appreciated.

magento: insert content in to predefined block using Custom Layout Update

I have the Ultimo theme on my magento store. There is a predefined static block called 'block_product_secondary_bottom' that when enabled will show up on all products. I am trying to show content in this block's space for select products, and from another defined static block named 'suggested_addons'.

I used the following code in Custom Layout Update and it doesn't work. Any suggestions?

<reference name="block_product_secondary_bottom">
    <block type="cms/block" name="suggested_addons">
        <action method="setBlockId"><block_id>suggested_addons</block_id></action>
    </block>    
</reference>

PHP how to consume a remote https WCF webservice

Im trying to consume a WCF webservice using get or post with php , it is a great example, it works locally but I need to make it work remotelly.

The code is a great test example because it allows you to see both the get and post requests.

This is a model of the url (not the real one).

http://ift.tt/1dNt0pO

This is the error from the server

The exception message is 'Invalid value for 'encryptedTicket' parameter.'

What should I do to solve it? It seems there is not to much written about this.

The code below

<?php
echo 'Call the service using GET <br>';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://ift.tt/1dNt0pO".
                    "");
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Accept: application/json'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

print_r($result);
echo '<br>';

echo '<br>Call the service using POST <br>';


$transmitObject = array("fname" => "MASTER", "lname" => "POGI");




$jsonObject = json_encode($transmitObject);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://ift.tt/1dNt0pO");
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Accept: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonObject);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);
print_r($result);
?>

SELECT, UPDATE records using php and mysql

I have a php file that displays records from a mysql db into a html table. For each row I have a check-box added. I would like to select a check box for a given row and UPDATE a field for that row only. I know that an UPDATE statement has to be created then on SUBMIT the UPDATE will process. I have researched but have no idea what to do next.

Here is what I have

$sql = "SELECT * , date_format(created_at, '%m/%d/%y'), time_format(created_at, '%h:%i:%s') FROM `report_facility_maintenance` LEFT JOIN facilities ON  report_facility_maintenance.facility_id = facilities.id ORDER BY created_at DESC";
$result = $conn->query($sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row

       // while($row = $result->fetch_assoc()) {
       echo "<table border=1, width=900px; >
            <tr>
            <th width=300px>Request Information</th>
            <th>Details</th>
            <th>Complete</th>
            </tr>";
       while ($row = mysqli_fetch_assoc($result)) {

        echo "<tr>";
            echo "<td align=Left> <br> <strong>Location: </strong>" . $row["name"]. 
            " <br> <strong>Type: </strong>" . $row["maint_type"]. 
            " <br> <strong>Date: </strong>" . $row["date_format(created_at, '%m/%d/%y')"].
            " <br> <strong>Time: </strong>" . $row["time_format(created_at, '%h:%i:%s')"].
            "<br><strong>Submitted By: </strong>". $row["submitted_by"]. 
            "<br><br></td><td>".$row["details"]. "</td><td><input type=checkbox name=completed[] value=complete /></td>";
            echo "</tr>";
             //print_r($row);
            // echo $result;
        }
        echo "</table><br />";
    } else {
    //echo "0 results";
    }
echo "<input type=submit name=completedSubmit value= Clear&nbsp;Selected />";

$conn->close();
?>

How to parse the header returned by cURL?

I am trying to communicate to an API using cURL. One of the methods require that I pass the value of the ININ-ICWS-CSRF-Token header (ie. WAhtYWxoYXlla1dBY2NvUkRJWCQxZmUxZWFhZS0xZTE0LTQyNGYtYjdhZS0zNmZjN2MxYWJmODBYCjEwLjAuNC4xNjA=) and the Set-Cookie (ie. icws_904586002=bf7c7783-6766-4c4f-862b-48f25a9a3741) so I need to extract them so I can pass them later in my code.

Here is what I did to extract the header and the body from the cURL/API respond

$respond = curl_exec($ch);

//throw cURL exception
if($respond === false){
    $errorNo = curl_errno($ch);
    $errorMessage = curl_error($ch);

    throw new ApiException($errorMessage, $errorNo);
}   

list($header, $body) = explode("\r\n\r\n", $respond, 2);
echo '<pre>';
print_r($header);
echo '</pre>';

This is the content of the $header value

HTTP/1.1 201 Created
ININ-ICWS-CSRF-Token: WAhtYWxoYXlla1dBY2NvUkRJWCQxZmUxZWFhZS0xZTE0LTQyNGYtYjdhZS0zNmZjN2MxYWJmODBYCjEwLjAuNC4xNjA=
ININ-ICWS-Session-ID: 904586002
Set-Cookie: icws_904586002=bf7c7783-6766-4c4f-862b-48f25a9a3741; Path=/icws/904586002
Location: /icws/904586002/connection
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Content-Type: application/vnd.inin.icws+JSON; charset=utf-8
Date: Wed, 06 May 2015 17:13:44 GMT
Server: HttpPluginHost
Content-Length: 237

I would like to get in return results like this

the value of "ININ-ICWS-CSRF-Token" is "WAhtYWxoYXlla1dBY2NvUkRJWCQxZmUxZWFhZS0xZTE0LTQyNGYtYjdhZS0zNmZjN2MxYWJmODBYCjEwLjAuNC4xNjA="
the value of the "cookie" is "ININ-ICWS-CSRF-Token: WAhtYWxoYXlla1dBY2NvUkRJWCQxZmUxZWFhZS0xZTE0LTQyNGYtYjdhZS0zNmZjN2MxYWJmODBYCjEwLjAuNC4xNjA="

How to load controller / create router for php mvc framework

I am writing a light weight php mvc framework for my portfolio and as a barebone setup for my future developments. I am stuck now because I am trying to use PSR-4 autoloader through composer. I understand the concept of PSR-4 etc but I am wondering how should I handle the routing.

My folder structure is:

--|-Root---
  index.php
  composer.json
-----|-application------
--------|-controller----
--------|-model---------
--------|-core----------
-----------|-baseController.php
-----------|-Application.php
-----------|-baseView.php
-----------|-baseModel.php
--------|-view----------
--------|-config
-----------|-config.php
-----|-vendor------
--------|-autoload.php
-----|-assets------

I am fairly good with php but writing an own mvc framework is a hard challange, even bigger because I never used PSR standards before.

Now my questions are:

  1. Should I use router at all?
  2. If yes then what pattern should I use to acomplish that.

So, in my index.php I define all constants to store directories like ROOT, APP, VENDOR. I then load vendor/autoload.php generated from my composer.json. After autoload.php I load and initiate my config by calling this code:

if(is_readable(APP . 'config/config.php')) 
{
    require APP . 'config/config.php';

    //Initiate config
    new AppWorld\Confyy\config();
} 
else 
{
    throw new Exception('config.php file was not found in' . APP . 'config');
}

After config I setup application environment and then I initiate my app by calling:

// Start the application
new AppWorld\FrostHeart\Application();

Then my baseController is very very thin:

<?php
namespace AppWorld\FrostHeart;
use AppWorld\FrostHeart\baseView as View;

abstract class baseController {

    public $currentView;

    public function __construct() {

        //Initiate new View object and set currentView to this object.
        $this->currentView = new View();

    }

}

And this is my baseView.php:

<?php
namespace AppWorld\FrostHeart;

class baseView {

    public function show($file, $data = null, $showTemplate = 1) {

        if($data != null) {
            foreach($data as $key => $value) {
                $this->{$key} = $value;
            }
        }

        if($showTemplate === 1) {
            require VIEW_DIR . header . ".php";
            require VIEW_DIR . $file . ".php";
            require VIEW_DIR . footer . ".php";
        } 
        elseif($showTemplate === 0) 
        {
            require VIEW_DIR . $file . ".php";
        }

    }

}

my config.php:

<?php
namespace AppWorld\Confyy;

class config {

    public function __construct() {
        $this->application();
        $this->database();
    }

    public function application() {

        /**
        * Define application environment, defaults are:
        * 
        * development
        * live
        * 
        */

        define("ENVIRONMENT", "development");

        //Define base url
        define("BASE_URL", "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);       
        //Define default controller
        define("DEFAULT_CONTROLLER", "landing");
        //Define default method
        define("DEFAULT_METHOD", "index");    
        //Define controllers directory
        define("CONTROLLER_DIR", APP . "controller/");
        //Define views directory
        define("VIEW_DIR", APP . "view/");

    }

    public function database() {
        //Define DB Server
        define("DB_SERVER", "localhost");
        //Define DB User 
        define("DB_USER", "root");
        //Define DB Password
        define("DB_PASSWORD", "");
        //Define DB Name
        define("DB_NAME", "test");
    }

}

and at last my composer.json autoload section:

"autoload": {
        "psr-4":{
            "AppWorld\\": "application",
            "AppWorld\\Conffy\\": "application/config",
            "AppWorld\\FrostHeart\\": "application/core",
            "AppWorld\\Controls\\": "application/controller"
        }
    }

So how should I implement a router that routes the URL requests and load correct files?

Thanks!

Is there a tool to view emails (PHP application)

The scamdex.com website has an archive of 100,000+ scammy emails. I have written my own email display routines but I've never been happy with the output. Does anyone know of a tool or component that can do this better - perhaps a JQuery library or a snippet I can use from a PHP framework? Here's an example:

http://ift.tt/1c6fCw5

I'm in the middle of changing the website to use a Twitter Bootstrap/JQuery template, so this is a good time to rethink stuff. Thanks!

Laravel Querybuilder how to skip and take rows from newest to oldest?

Is there a way to skip and take rows from newest to oldest using Laravel Querybuilder?

This is what I currently have:

DB::table('decks')->skip(10)->take(5)->get();

It skips from the oldest to the newest. Is there a way to make skip start from the newest rows?

Repair accents on php with htmlentities

i want repair the problem of accents , but I have this

error Warning: htmlentities() expects parameter 2 to be long, string given in

my code :

function check_and_secure($T, $field)
{
    if (!isSet($T[$field]))
        return "";
        $in_utf8encoded="é à ù è ò";
       $in_iso8859encoded=iconv("UTF-8", "ISO-8859-1",$in_utf8encoded);
 return   $out_iso8859= htmlentities($T[$field],$in_iso8859encoded, ENT_COMPAT, "ISO-8859-1");

}

Include blank values in array from foreach statement

EDIT: I tried to simplify it before but I think I'll just lay it all out there as it may clear up some confusion as to what I am trying to achieve.

I am using two mySQL tables to create a javascript chart showing a bar graph and a line graph on the same chart. The line graph showing attendance and the bar graph showing what brewing processes was done for that date. Table A:

id |   date   | attended
1  |2015-01-14| 3
2  |2015-01-20| 4
3  |2015-01-31| 2
4  |2015-02-21| 3
5  |2015-02-25| 4
6  |2015-03-16| 4

Table B:

id |    name    |    brewdate   | bottledate
1  | Honey Ale  |   2015-01-14  | 2015-02-21
2  |     IPA    |   2015-01-14  | 2015-01-31
3  |   Porter   |   2015-01-20  | 2015-02-25
4  | Brown Ale  |   2015-02-21  | 2015-03-16

Using the code below I am able to get arrays to use with zingchart:

<?php
    $sql = "SELECT * DATE_FORMAT(DATE(date), '%m/%d') AS bpdate
    FROM TableA ORDER BY date";
    $data = $conn->query($sql);
?>
<script
    //GET array of attendance for line chart
    var present=[<?php
    mysqli_data_seek($data, 0);
    while($info=mysqli_fetch_array($data)) {
        echo $info['present'].",";
    }
    ?>];
    //Get dates for x-axis of chart
    var dates=[<?php
    mysqli_data_seek($data, 0);
    while($info=mysqli_fetch_array($data))
        echo '"'.$info['bpdate'].'",';
    ?>];
    <?php
        $sql = "SELECT COUNT(TableB.brewdate) AS brewed
        FROM TableB
        RIGHT JOIN TableA
        ON TableB.brewdate=TableA.date
        GROUP BY TableA.date ORDER BY TableA.date";
        $events = $conn->query($sql);
    ?>
    //Get number of beers brewed per date
    var brewed=[<?php
    while($info=mysqli_fetch_array($events)) {
        echo $info['brewed'];
    }
    ?>];
    <?php
        $sql = "SELECT TableB.*
        FROM TableB
        RIGHT JOIN TableA
        ON TableB.date=TableA.date
        ORDER BY TableA.date";
        $names = $conn->query($sql);
    ?>
    //Get the name of each beer that was brewed.
    var brewednames=[<?php
    while($info=mysqli_fetch_array($names))  {
        echo '"' . $info['name'] . ',"';
    }
    ?>];
</script>

Which gives me this:

var present=[3,4,2,3,4,4];
var dates=["01/14","01/20","01/31","2/21","02/25","03/16"];
var brewednames=["Honey Ale","IPA","Porter","","Brown Ale","",""];

The problem I am having is with variable brewednames. It is correctly giving me the list of the beers with blanks filling in the dates where no beers were brewed, but it lists beers that have the same date in different array elements and I want them to show in the same one. Like so:

var brewednames=["Honey Ale IPA","Porter","","Brown Ale","",""];

The reasoning behind this is that this array is shown when a user hovers over the corresponding bar on chart. So rather than showing the number of beers brewed for that date I want it to give the names of all the beers brewed on that date.

I found this article which was able to help me group each beer that was brewed on the same date in the same array element but now they are not ordered according to date as all the blanks have been moved to the beginning of the array:

var brewednames=[<?php
$info = array();
while($row=$names->fetch_assoc())  {
    $date = $row['date'];
    $name = $row['name'];
    $info[$date][] = $name;
}
foreach ($info as $date => $values) {
    echo '"';
    foreach($values as $value) {
        echo $value . ' ';
    }
    echo '",';
}
?>];

Which gives me this:

var namegroup=["   ","Honey Ale IPA","Porter","Brown Ale"]

Any help would be much appreciated. Also I am sure that my code is not perfect as I am somewhat teaching myself mySQL and PHP so if there are any suggestions for cleaner/better code feel free to weigh in. Thanks.

How to get this day last year in PHP?

So I'm currently using Carbon for getting dates, times and comparisons. I can do subYear() easily enough to get this date last year. Now I need something to get the exact same day at the same time last year, e.g Wednesday of the second week of April.

I'd expect to have to do something that works out the current day of the week, e.g 3, and the current week of the year, then get the same value last year.

Just thought I'd check if there's anything available that already does this in Carbon or other PHP tools? Thanks

Why can't I assign any variable to a function return value in pChart?

I'm trying to assign a return value from a method to an array and in a second step to place this array into the addPoints() method of pChart.

Right now I'm using the following code:

$dataUsage = array();
for ($i = 1; $i < 31; $i++) {
        $dataUsage[$i - 1] = getDailyUsage($i);
}
$dataUsage[30] = getDailyUsage(31);

The getDailyUsage method looks like this:

function getPeriod() {
    return date("Y-m");
}

function getDailyUsage($day) {
        $var = getPeriod() . "-" . $day;
        global $pdo;
        $sql = "SELECT COUNT(  `id` ) FROM  `logs` WHERE timestamp = '$var'";
        $q = $pdo->prepare($sql);
        $q->execute();
        $q->setFetchMode(PDO::FETCH_ASSOC);
        $number = $q->fetchColumn(0);
        return $number;
}

To display the data into the pChart I'm running this:

$myData->addPoints($dataUsage, "Serie2");

As output I'm getting the default html icon as if I'm not finding the picture I'm looking for.

What really makes me curious is that I don't get any errors if I run this code:

$array = array();
for ($i = 1; $i < 31; $i++) {
    $array[$i - 1] = $i;
}
$array[30] = 31;

$myData->addPoints($array, "Absissa");

Since this is my first post I'm looking for tips to improve my questions, so feel free to leave a comment.

CakePhp Generating a XML file from a string

Im trying to generate a XML file to be send through a invoice I´m generating. The XML I have in a string is the next:

<?xml version="1.0" encoding="UTF-8"?>
<cfdi:Comprobante xmlns:cfdi="http://ift.tt/UMOQdM" xmlns:xsi="http://ift.tt/ra1lAU" xmlns:implocal="http://ift.tt/1H1oBfr" xsi:schemaLocation="http://ift.tt/UMOQdM http://ift.tt/U86xac http://ift.tt/1H1oBfr http://ift.tt/1H1oBft" version="3.2" serie="Z" folio="155" fecha="2015-04-06T15:26:14" subTotal="1.00" total="1.32" certificado="" noCertificado="" TipoCambio="1" Moneda="MXN" metodoDePago="no aplica" sello="" tipoDeComprobante="ingreso" formaDePago="no aplica" LugarExpedicion="no aplica">
    <cfdi:Emisor rfc="ZFL080519LG0" nombre="ZURITA FLORERIAS S.A. DE C.V.">
        <cfdi:DomicilioFiscal calle="Avenida 14 Sur" noExterior="5347" noInterior="B" colonia="Jardines San Manuel" localidad="Puebla" municipio="Puebla" estado="Puebla" pais="México Teléfono 2224974551" codigoPostal="72570" />
        <cfdi:ExpedidoEn pais="México" />
        <cfdi:RegimenFiscal Regimen="Persona Moral del Regimen General" />
    </cfdi:Emisor>
    <cfdi:Receptor rfc="GOMA890623M50" nombre="ARANTXA GONZALEZ MENDOZA">
        <cfdi:Domicilio calle="NORTE" noExterior="1" noInterior="O" colonia="LA PAZ" localidad="PUEBLA" municipio="PUEBLA" estado="PUEBLA" pais="MEXICO" codigoPostal="00000" />
    </cfdi:Receptor>
    <cfdi:Conceptos>
        <cfdi:Concepto cantidad="1" unidad="NO APLICA" descripcion="NO APLICA" valorUnitario="1.00" importe="1.00" />
    </cfdi:Conceptos>
    <cfdi:Impuestos totalImpuestosTrasladados="0.16">
        <cfdi:Traslados>
            <cfdi:Traslado impuesto="IVA" tasa="16.00" importe="0.16" />
        </cfdi:Traslados>
    </cfdi:Impuestos>
    <cfdi:Complemento>
        <implocal:ImpuestosLocales version="1.0" TotaldeRetenciones="0.00" TotaldeTraslados="0.16">
            <implocal:TrasladosLocales ImpLocTrasladado="TRASLADADO" Importe="0.16" TasadeTraslado="16.00" />
        </implocal:ImpuestosLocales>
    </cfdi:Complemento>
</cfdi:Comprobante>

Im using CakePhp Xml::Build($string); to generate a XML, but for some reason not all the variables are going through. Im guessing the Xml is not being build or something. This is the code to generate the XML.

$XMLString = '<?xml version="1.0" encoding="UTF-8"?><cfdi:Comprobante xmlns:cfdi="http://ift.tt/UMOQdM" xmlns:xsi="http://ift.tt/ra1lAU" xmlns:implocal="http://ift.tt/1H1oBfr" xsi:schemaLocation="http://ift.tt/UMOQdM http://ift.tt/U86xac http://ift.tt/1H1oBfr http://ift.tt/1H1oBft" version="3.2" serie="Z" folio="155" fecha="2015-04-06T15:26:14" subTotal="1.00" total="1.32" certificado="" noCertificado="" TipoCambio="1" Moneda="MXN" metodoDePago="no aplica" sello="" tipoDeComprobante="ingreso" formaDePago="no aplica" LugarExpedicion="no aplica"><cfdi:Emisor rfc="ZFL080519LG0" nombre="ZURITA FLORERIAS S.A. DE C.V."><cfdi:DomicilioFiscal calle="Avenida 14 Sur" noExterior="5347" noInterior="B" colonia="Jardines San Manuel" localidad="Puebla" municipio="Puebla" estado="Puebla" pais="México Teléfono 2224974551" codigoPostal="72570" /><cfdi:ExpedidoEn pais="México" /><cfdi:RegimenFiscal Regimen="Persona Moral del Regimen General" /></cfdi:Emisor><cfdi:Receptor rfc="GOMA890623M50" nombre="ARANTXA GONZALEZ MENDOZA"><cfdi:Domicilio calle="NORTE" noExterior="1" noInterior="O" colonia="LA PAZ" localidad="PUEBLA" municipio="PUEBLA" estado="PUEBLA" pais="MEXICO" codigoPostal="00000" /></cfdi:Receptor><cfdi:Conceptos><cfdi:Concepto cantidad="1" unidad="NO APLICA" descripcion="NO APLICA" valorUnitario="1.00" importe="1.00" /></cfdi:Conceptos><cfdi:Impuestos totalImpuestosTrasladados="0.16"><cfdi:Traslados><cfdi:Traslado impuesto="IVA" tasa="16.00" importe="0.16" /></cfdi:Traslados></cfdi:Impuestos><cfdi:Complemento><implocal:ImpuestosLocales version="1.0" TotaldeRetenciones="0.00" TotaldeTraslados="0.16"><implocal:TrasladosLocales ImpLocTrasladado="TRASLADADO" Importe="0.16" TasadeTraslado="16.00" /></implocal:ImpuestosLocales></cfdi:Complemento></cfdi:Comprobante>';
$document=Xml::build($XMLString, array('encoding' => 'UTF-8', 'return' => 'simplexml'));

What Im getting back when I check the variable that is being received with the element inspector on google chrome is the next.

documnet: Object
@attributes: Object
LugarExpedicion: "no aplica"
Moneda: "MXN"
TipoCambio: "1"
certificado: ""
fecha: "2015-04-06T15:26:14"
folio: "155"
formaDePago: "no aplica"
metodoDePago: "no aplica"
noCertificado: ""
sello: ""
serie: "Z"
subTotal: "1.00"
tipoDeComprobante: "ingreso"
total: "1.32"
version: "3.2"

Not all the data is going through. Only the header. I want to send the string as a file.xml that is all I have to do. any ideas of an easier way of doing this? or what am I doing wrong?

Thanks in advance.

PHP, Codebird and Twitter why am receiving error 401 Invalid Request Token

I am trying to get access token from twitter using codebird, first getting user to authorize use of my application works perfectly using this code

    require_once('lib/codebird.php');

\Codebird\Codebird::setConsumerKey("xxx", "xxxx");
$cb = \Codebird\Codebird::getInstance();
session_start();
    // get the request token
    $reply = $cb->oauth_requestToken(array(
        'oauth_callback' => 'http://ift.tt/1H1oC39'));
    // store the token
    $cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
    $_SESSION['oauth_token'] = $reply->oauth_token;
    $_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
    $_SESSION['oauth_verify'] = true;

    // redirect to auth website
    $auth_url = $cb->oauth_authorize();
?>
    <script type="text/javascript">
        window.location = "<?php echo  $auth_url; ?>";
    </script>

<?php
    //header('Location: ' . $auth_url);
?>

This is where I am redirected here:

twitter authorization

When then I get redirected to the window in where I am supposed to get the access token and access token secret and that also works.

Here is where using $_GET[] I get the following codes http://ift.tt/1H1oAZ9

Now in that page when I run the following code, it does not work, but produces the following error:

require_once('lib/codebird.php');
session_start();
\Codebird\Codebird::setConsumerKey("xxxx", "xxxx");
$cb = \Codebird\Codebird::getInstance();
// get the access token
$reply = $cb->oauth_accessToken(array(
        'oauth_verifier' => $_GET['oauth_verifier']
));

var_dump($reply);

When I dump the reply, it has the following error in it:

object(stdClass)#1 (3) { ["message"]=> string(21) "Invalid request token" ["httpstatus"]=> int(401) ["rate"]=> NULL }

So how am I supposed to get the aouth_accessToken, with this oauth_token=zzzzz&oauth_verifier=zzzz url parameters provide and a user has authorised use of my application?

pass specific element of array to ajax in joomla 3 module

I'm sure this is really simple but I have been trying to get this for ages. I have a foreach loop which iterates over an array of objects and displays them in an html table with a submit button which when clicked makes an ajax call to display some data in the same page.

This all works fine except it only passes the value of the last object from the array in the foreach loop instead of the value as displayed in that table row. I have tried to use a counter or to set and id for the but unsure how to get that specific value and pass it through.

Here is what is in my code:

<?php 
// No direct access
defined('_JEXEC') or die; ?>

<div class="status shelterbuddydog" >
<table class="profile_table">
   <?php foreach ($animalDetails as $profile):?>
    <tr>
        <td><?php echo $profile->photo;?></td>
        <td><span class="profile">Name:<?php echo $profile->name;?></span><br/>
            <span class="profile">Sex: <?php echo $profile->sex;?></span></<br/>
            <span class="profile">Age: <?php echo $profile->age;?></span><br/>
            <span class="profile">Breed: <?php echo $profile->breed;?></span><br/>
            <span class="profile">Animal Id: <?php echo$profile->animalId;?></span><br/>
            <span class="profile">Location: <?php echo $profile->shelter;?></span><br/>
            <?php $profile->summary;?>
            <input type="submit" id="summary" name="summary" value="VIEW MY PROFILE">
            </input></td>
    </tr>
    <?php endforeach;

</table>
<?php 
// Instantiate global document object

$doc = JFactory::getDocument();

$js = <<<JS

(function ($) {
 $(document).on('click', '#summary', function () {

    var profileSummary = {};
        profileSummary['photo'] = '$profile->photo';
        profileSummary['name'] =  "$profile->name";
        profileSummary['sex']  = "$profile->sex";
        profileSummary['age']  =  "$profile->age";
        profileSummary['breed']  = "$profile->breed";
        profileSummary['shelter']  = "$profile->shelter";
        profileSummary['animalId']  =  "$profile->animalId";
        profileSummary['summary'] =  "$profile->summary";

        request = {
                'option' : 'com_ajax',
                'module' : 'shelterbuddydog',
                'data'   : profileSummary,
                'format' : 'raw'
            };
    $.ajax({
        type   : 'GET',
        data   : request,
        success: function (response) {
            $('.status').html(response);
        }
    });
    return false;
});
})(jQuery)
JS;
$doc->addScriptDeclaration($js);    
?>
</div>

Thanks for any help with this.

Redis sentinel implementation

We have a setup with :
2 php server
2 redis servers running as master/slave
1 Log server, which stores all kind of logs in elastcisearch

We want to implement automatic failover for redis servers, right now in php servers redis master address ir hardcoded.

And in log server, which has a logstash instance with redis input from master is also harcoded in logstash config.

We have installed redis sentinel on both redis servers and it's working fine.

But the problem is how to get master in php and logstash or that is not the right way.

For php I found this client wrapper http://ift.tt/1c6fBZ3

But haven't found anything for logstash, I quess that I'm just searching in wrong direction

So the question is if this is the right direction if not someone could point me to it.

how to overwrite current theme in yii2.0 with your own theme

I have been trying to use my own downloaded themes in yii2.0. I created a folder called 'themes' in web and copied my theme folder there, then I changed the view in web.php but I still get the default theme. What can I do to make my theme work?

getting values from php dynamically created checkboxes with jquery

H Im trying to get the value of a check box to send in a ajax request to a php page, the checkboxes are dynamically created using php. So far my code allows me to show an instruction to the user telling the user to choose an admin to delete from the list dynamically created. Then when a checkbox is checked the instrcution hides and the delete admin button is shown. Next on clicking the delete button I'm trying to confirm the user wants to delete the admin chosen and click to confirm or cancel. The real problem I'having is getting the value of the chosen checked checkbox to pass to the php processing page, so far I have managed to get the value of the first checkbox to pass no matter which checkbox is checked

Jquery

<script type="text/javascript">

$(document).ready(function() {

    var checkboxes = $("input[type='checkbox']");

checkboxes.click(function() {
    $('.delete_admin_but').show();
    $('#adminDeleteNotice').hide();
    var deleteAdminName=$(this).attr('id');
});

    $(".delete_admin_but").click(function() {



//  if(confirm("Are you sure you want to delete the Admin")) {

    $("#deleteAdminError").html('<img src="image/ajax-loader.gif" width="16" height="16" alt=""/>');




$.post("includes/delete_admin.inc.php",{deleteAdminname:deleteAdminName},function(json)   {
    if(json.result === "success") {
        $("#deleteAdminError").html(json.message);
//  $('.add_intern').get(0).reset();
    }else{
        $("#deleteAdminError").html(json.message);
    }
});



});//submit click
});//doc ready
</script>

html form

<div id="deleteAdmin" style="display:none">

<form id="adminDelete">

          <div class="delete_admin_list">

            <?php while($row = mysqli_fetch_array($result1)) { ?>

              <input type="checkbox" id="<?php echo $row['name']; ?>" value="<?php echo $row['id']; ?>" name="delete[]" class="checkboxAdmin" />

              <div id="admin_db_detail"><?php echo $row['name']; ?> - <?php echo $row['email']; ?></div>

              <?php } ?>

      </div>        


<div id="adminDeleteNotice" style="display:block">Please Choose an Admin to Delete</div>

<input name="delete_admin_but" id="delete_admin_but" type="button" class="delete_admin_but" value="Delete Admin" style="display:none"/>

</form>

<div id="deleteAdminError"></div>

</div>

If anyone could help me figure this out I would be greatful

Fancybox - trying to change the zoom effect

I am trying to edit this the below code to change the hover function. I'm a super novice but learning Javascript and php. As this is using fancybox, is there a way to change the zoom in effect to zoom out? Do i need to change it from the css? I can post if necessary. Thanks in advance.

 <?php
    $service_args = array(
        'post_type' => 'snap',
        'nopaging' => true,
        'orderby' => 'date',
        'order' => 'DESC'
    );

    $loop = new WP_Query($service_args);

    if ( $loop->have_posts() ) :
        while ($loop->have_posts()) :
            $loop->the_post();
            $image = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full', true);
            $thumb = wp_get_attachment_image_src(get_post_thumbnail_id(), 'size-360-225', true);

            echo '<a href="'.$image[0].'" class="snap-item fancybox"><img src="'.$thumb[0].'" alt="" /></a>';
        endwhile;
    endif;
    wp_reset_postdata();
?>