PHP4 alternatives for json_encode and PDO

Hallo Friend,
I want to use the idea of using AJAX to filter MySQL results with multiple checkbox option. Here is the complete code which i already got from this forum. But this code runs on PHP5 version as PDO database connectivity and Json encode input is used in submit.php file. I want to make changes in the submit.php file so that it can runs on PHP4 version. Please help me in that as i am new to use PHP4 version.
Thank You.
regards,
Rahul D.
Here is the code:

CREATE TABLE IF NOT EXISTS `mobile_phone` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `model` varchar(255) DEFAULT NULL,
  `price` int(11) DEFAULT NULL,
  `brand_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

INSERT INTO `mobile_phone` (`id`, `model`, `price`, `brand_id`) VALUES
(1, 'Galaxy S 1', 180, 1),
(2, 'Galaxy S 2', 220, 1),
(3, 'Galaxy S 3', 300, 1),
(4, 'Galaxy S 4', 450, 1),
(5, 'Galaxy S 4 mini', 400, 1),
(6, '3GS', 150, 2),
(7, '4', 200, 2),
(8, '4S', 250, 2),
(9, '5', 300, 2),
(10, '5S', 350, 2),
(11, 'Desire', 150, 3),
(12, 'Desire200', 200, 3),
(13, 'Desire500', 250, 3),
(14, 'One', 400, 3),
(15, 'One mini', 250, 3),
(16, 'Optimus L3', 150, 4),
(17, 'Optimus L5', 250, 4),
(18, 'Optimus L7', 350, 4),
(19, 'Optimus L9', 400, 4),
(20, 'Optimus G2', 450, 4),
(21, '100', 50, 5),
(22, 'E72', 100, 5),
(23, 'E6', 150, 5),
(24, 'Lumia 520', 200, 5),
(25, 'Lumia 620', 250, 5);

Then the brand table :

CREATE TABLE IF NOT EXISTS `brand` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

INSERT INTO `brand` (`id`, `name`) VALUES
(1, 'Samsung'),
(2, 'iPhone'),
(3, 'HTC'),
(4, 'LG'),
(5, 'Nokia');

index.php

<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>AJAX filter demo</title>
    <style>
      body {
        padding: 10px;
      }
 
      h1 {
          margin: 0 0 0.5em 0;
          color: #343434;
          font-weight: normal;
          font-family: 'Ultra', sans-serif;   
          font-size: 36px;
          line-height: 42px;
          text-transform: uppercase;
          text-shadow: 0 2px white, 0 3px #777;
      }
 
      h2 {
          margin: 1em 0 0.3em 0;
          color: #343434;
          font-weight: normal;
          font-size: 30px;
          line-height: 40px;
          font-family: 'Orienta', sans-serif;
      }
 
      #phones {
        font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
        font-size: 12px;
        background: #fff;
        margin: 15px 25px 0 0;
        border-collapse: collapse;
        text-align: center;
        float: left;
        width: 300px;
      }
 
      #phones th {
        font-size: 14px;
        font-weight: normal;
        color: #039;
        padding: 10px 8px;
        border-bottom: 2px solid #6678b1;
      }
 
      #phones td {
        border-bottom: 1px solid #ccc;
        color: #669;
        padding: 8px 10px;
      }
 
      #phones tbody tr:hover td {
        color: #009;
      }
 
      #filter {
        float:left;
      }
    </style>
  </head>
  <body> 
    <h1>Phones database</h1>
 
    <table id="phones">
      <thead>
        <tr>
          <th>ID</th>
          <th>Brand</th>
          <th>Model</th>
          <th>Price</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>
 
    <div id="filter">
      <h2>Filter options</h2>
      <div>
        <input type="checkbox" id="Samsung" checked>
        <label for="Samsung">Samsung</label>
      </div>
      <div>
        <input type="checkbox" id="iPhone" checked>
        <label for="iPhone">iPhone</label>
      </div>
      <div>
        <input type="checkbox" id="HTC" checked>
        <label for="HTC">HTC</label>
      </div>
      <div>
        <input type="checkbox" id="LG" checked>
        <label for="LG">LG</label>
      </div>
      <div>
        <input type="checkbox" id="Nokia" checked>
        <label for="Nokia">Nokia</label>
      </div>
    </div>

    <script src="http://code.jquery.com/jquery-latest.js"></script> 
    <script>
      function makeTable(data){
        console.log(data);
       var tbl_body = "";
          $.each(data, function() {
            var tbl_row = "";
            $.each(this, function(k , v) {
              tbl_row += "<td>"+v+"</td>";
            })
            tbl_body += "<tr>"+tbl_row+"</tr>";
          })
 
        return tbl_body;
      }
 
      function getPhoneFilterOptions(){
        var opts = [];
        $checkboxes.each(function(){
          if(this.checked){
            opts.push(this.id);
          }
        });
 
        return opts;
      }
 
      function updatePhones(opts){
        $.ajax({
          type: "POST",
          url: "submit.php",
          dataType : 'json',
          cache: false,
          data: {filterOpts: opts},
          success: function(records){
            $('#phones tbody').html(makeTable(records));
          }
        });
      }
 
      var $checkboxes = $("input:checkbox");
      $checkboxes.on("change", function(){
        var opts = getPhoneFilterOptions();
        updatePhones(opts);
      });
 
      $checkboxes.trigger("change");
    </script> 
  </body> 
</html>

submit.php


  $pdo = new PDO('mysql:host=localhost;dbname=sitepoint', 'root', '*****');
  $opts = $_POST['filterOpts'];
  $qMarks = str_repeat('?,', count($opts) - 1) . '?';
  $statement = $pdo->prepare("SELECT mobile_phone.id, name, model, price FROM mobile_phone INNER JOIN brand ON brand_id = brand.id WHERE name IN ($qMarks)");
  $statement -> execute($opts);
  $results = $statement -> fetchAll(PDO::FETCH_ASSOC);
  $json = json_encode($results);
  echo($json);
?>

The demo of this code here

Hi,

Your question is of a PHP nature, so I have moved it to the PHP forum.

In a nutshell:

Here is an alternative for json_encode: http://www.dzone.com/snippets/jsonencode-alternative-php-4

If you can’t use PDO, use mysqli: http://www.php.net/manual/en/book.mysqli.php

Hi,
I think mysqli will also not work in PHP4. And regarding Json code can you please help me how to use it as i am not familiar with the Json. I just need to know the small changes in submit.php file.The only problem i am getting in this code is i cant see any output from database.
Thanks.

As I understand it, the json_encode alternative I link to is a drop in replacement for this function.
Is there any reason you are stuck using PHP4?

Hi, Yes i work in a company where they are using PHP4 for development. I know its too odd but i dont have any option to use it :(. And i need this code for some idea which i can use in my project.Please help me if you know it as you have developed this code.
Thanks.

Unfortunately “Please help me” translates as “Please write all the code for me”, which I won’t do.

My suggestion would be to start small and break the problem into solvable pieces.

My original tutorial involved getting a bunch of records from a database, based on options which were set in the client.

So what do you have already?
What kind of records are you trying to filter?

I am trying to run your code. If it will work then only i can change the data which i required for my project.Here is th code i am trying. I have also include Json encode [URL=“http://http://www.abeautifulsite.net/blog/2008/05/using-json-encode-and-json-decode-in-php4/”] in submit.php file. But still i am getting any data from database.Thanks:

<?php
require ‘Database.php’;

TEMP SET NAMES FÜR UTF8

require ‘Json.php’;

$opts = $_POST[‘filterOpts’];
$qMarks = str_repeat(‘?,’, count($opts) - 1) . ‘?’;
$statement = “SELECT mobile_phone.id, name, model, price FROM mobile_phone INNER JOIN brand ON brand_id = brand.id WHERE name IN ($qMarks)”;
$statement1 = mysql_query($statement);
$results = mysql_fetch_assoc($statement1);
$json = json_encode($results);
echo($json);
?>

<?php
require ‘Database.php’;

TEMP SET NAMES FÜR UTF8

require ‘Json.php’;

$opts = $_POST[‘filterOpts’];
foreach ($opts as &$opt) {
$opt = sprintf(“‘%s’”, mysql_real_escape_string($opt));
}
$query = sprintf(
“SELECT mobile_phone.id, name, model, price
FROM mobile_phone
INNER JOIN brand ON brand_id = brand.id
WHERE name IN (%s)”,
join(‘,’, $opts)
);

$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data = $row;
}

echo json_encode($data);
?>

Hi,I am trying this code in submit .php file but still not getting the data from database:

<?php
require ‘Database.php’;

TEMP SET NAMES FÜR UTF8

require_once(‘Json.php’);

$opts = $_POST[‘filterOpts’];
$qMarks = str_repeat(‘?,’, count($opts) - 1) . ‘?’;
$query = sprintf(
“SELECT mobile_phone.id, name, model, price
FROM mobile_phone
INNER JOIN brand ON brand_id = brand.id
WHERE name IN (%s)”,
join(‘,’, $opts)
);

$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data = $row;
}

echo json_encode($data);
?>

And for Json i used this code:http://mike.teczno.com/JSON/JSON.phps Thanks.

So it seems to me that you copy pasted a bunch of my code, then are having trouble making it run (owing to PHP 4 issues).

The code you posted doesn’t help much, so let’s start from the beginning.

The first thing to do is to get a simple script running on a server, which selects all of the records from a database table.

Please do that using whatever means works for you.

Once you have, please post a dump of the database (including data), as well as the PHP code you are using, so that I can run it on my PC, too.

In a second step, we can then implement the json_encode alternative.

Then in a third step we can implement the AJAX functionality.

Hi,I do copy paste ur code but this is only for demo purpose. For my project i have to take only idea from this code.Thts why i try to ran this code in PHP4 because i have to run every code in PHP4 only for official purpose.And thanks for your help but i already find a solution for this problem.

Cool. What did you do?

Here is my code:

<?php
require ‘Database.php’;

TEMP SET NAMES FÜR UTF8

include ‘Json.php’;
$opts = $_POST[‘filterOpts’];
$tmp = array();
foreach ($opts as $opt) {
$tmp = ‘"’.$opt.‘"’;
}
$query =
‘SELECT name
FROM Fahrzeuge
INNER JOIN ohne_fahrzeuge ON Fahrzeuge.dsnr = ohne_fahrzeuge.dsnr
WHERE Fahrzeuge.name IN (’.implode(“,”, $tmp).‘)’;

$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data = $row;
}

echo json_encode($data);
?>

My problem was with the Json and connectivity.Also i make changes bit using for loop to run in PHP4.

Now the good part is anyone can run this code on any version oh PHP!!!

Thanks. Maybe that’ll help someone else with the same problem :slight_smile:

Yes :).

Hi Pullo,
I have query to ask. I have to use button now for example Save button. So when i clicked on checkboxes and then on Save button then only it should show the changes on Phone Database.So in this case what is ur approach ? I am using the same code for index.php and the above code for submit.php.Thanks.

<?php 
require 'Database.php';
#### TEMP SET NAMES FÜR UTF8 ###################################################
include 'Json.php';
  $opts = $_POST['filterOpts'];
  $tmp = array();
  foreach ($opts as $opt) {
     	$tmp[] = '"'.$opt.'"';
  }
  		$query = 
      'SELECT mobile_phone.id, name, model, price FROM mobile_phone INNER JOIN brand ON brand_id = brand.id WHERE name IN ('.implode(",", $tmp).')';


  $result = mysql_query($query);
  $data   = array();
  while ($row = mysql_fetch_assoc($result)) {
  $data[] = $row;
  }

echo json_encode($data);
?>

I’d suggest finding a new job before the entire system you are working on collapses. Support for PHP4 ended several years ago so it is only a matter of time before someone exploits it to take over the entire system. You probably do not want to be there when that happens and they start looking for someone to blame.

So when you click the button, you want your changes saved to the database. Is that correct?

Yes pullo when we click the Save button then onl my Phone database should get updated