Affichage des articles dont le libellé est Active questions tagged php - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged php - Stack Overflow. Afficher tous les articles

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.