[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

php and mysql counting product on filter

Posted on 2009-02-12
1
Medium Priority
?
388 Views
Last Modified: 2012-05-06
how could i count the result step by step?
 i mean i have the following codes which counts and show the result but it shows when form submit click and it is ok, but i have ajax which shows the result while some one click the first drop down list the result count shows...but the error is
   1) if i choose what i want and click submit...the count result is ok..
   2) but because i have ajax, when i select from drop down list the ajax response is all the data counts and shows.  means if i have 100 product, if i select one criteria to filter ..i get still 100 product...i can see my ajax pass well..my error looks in php count handling script....

some one help please??
   

Ajax Code 
 
var xmlHttp
 
function showCount(str)
{ 
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
  {
  alert ("Your browser does not support AJAX!");
  return;
  } 
var url="phpApplication.php";
url=url+"?action=count2";
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
xmlHttp.send(null);
}
 
function stateChanged() 
{ 
if (xmlHttp.readyState==4)
{ 
document.getElementById("countR").innerHTML=xmlHttp.responseText;
}
}
 
function GetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}
 
 
 
php Code..
 
<?
class Application {
	
	function conn($sql)
{   
      
	  $host      = "localhost";
	  $username  = "root";
      $pwd       = "";
      $dbname    = "example";
 
    //echo "commnecing connection to local db<br>"
    if (!($conn=mysql_connect($host, $username, $pwd)))  {
        printf("error connecting to DB by user = $username and pwd=$pwd");
        exit;
    }
    $db3=mysql_select_db($dbname,$conn) or die("Unable to connect to local database");
	
   
    $result = mysql_query($sql) or die ("Can't connect because ". mysql_error());
   
    return $result;
   
}//end function  
 
 
function dropdown($field, $table)
{ 
  //initialize variables
  $oHTML  = '';
  $result = '';
  
  //check to see if the field is passed correctly
  if (($field == "")||($table == ""))
  {
    die("No column or table specified to create drop down from!");
  }
 
  $sql = "select distinct($field) from $table";
 
  //call the db function and run the query
  $result = $this->conn($sql);
 
  //if no results are found to create a drop down return a textbox
  if ((!$result) ||(mysql_num_rows($result)==0))
  {
    $oHTML .= "<input type='text' name='$field' value='' size='15'>";
  }elseif (($result)&&(mysql_num_rows($result)>0)){
   
    //build the select box out of the results
    $oHTML .= "<select name='$field' onchange='showCount(this.value)'>\n<option value='all'>All</option>\n";
    while ($rows = mysql_fetch_array($result))
    {
      $oHTML .= "<option value='".$rows[$field]."'>".$rows[$field]."</option>\n";
    }
    $oHTML .= "</select>\n";
  }
  //send the value back to the calling code
  return $oHTML;
}//end function
 
 
function countResult(){
	
  $sql2 = "select * from produkt_finder_table where 1 ";
 
 
  if ( $q == (!empty($_POST['Bauform_d']))&&($_POST['Bauform_d'] != 'all'))
  {
    $sql2 .= " and Bauform_d like '". addslashes($_POST['Bauform_d'])."%' ";
  }
  
 
  if ((!empty($_POST['Beschreibung_d']))&&($_POST['Beschreibung_d'] != 'all'))
  {
    $sql2 .= " and Beschreibung_d like '". addslashes($_POST['Beschreibung_d'])."%' ";
  }
  
  
   if ((!empty($_POST['SelectSchutzart_Cust_Bereich_d']))&&($_POST['SelectSchutzart_Cust_Bereich_d'] != 'all'))
  {
    $sql2 .= " and SelectSchutzart_Cust_Bereich_d like '". addslashes($_POST['SelectSchutzart_Cust_Bereich_d'])."%' ";
  }
  
  
   if ((!empty($_POST['SelectErfassungswinkel_Cust_Bereich_d']))&&($_POST['SelectErfassungswinkel_Cust_Bereich_d'] != 'all'))
  {
    $sql2 .= " and SelectErfassungswinkel_Cust_Bereich_d like '". addslashes($_POST['SelectErfassungswinkel_Cust_Bereich_d'])."%' ";
  }
  
  
   if ((!empty($_POST['ArtikelProduktgruppe_d']))&&($_POST['ArtikelProduktgruppe_d'] != 'all'))
  {
    $sql2 .= " and ArtikelProduktgruppe_d like '". addslashes($_POST['ArtikelProduktgruppe_d'])."%' ";
  }
  
  
 
$result2 = $this->conn($sql2);
  //run query
 
  if (!$result2){ die("No results due to database error.<br>".mysql_error());  }
 
  if (mysql_num_rows($result2)==0)
  {
    echo "0";
  }else{
 
    echo mysql_num_rows($result2);
}
}
 
 
function countResultAll(){
 
 $sql = "select * from produkt_finder_table where 1 ";
 
  
 
  if ((!empty($_POST['searchfield']))&&($_POST['searchfield'] != 'all'))
  {
    $sql .= " and ArtikelName like '". addslashes($_POST['searchfield'])."%' ";
  }
 
$result = $this->conn($sql);
  //run query
 
  if (!$result){ die("No results due to database error.<br>".mysql_error());  }
 
  if (mysql_num_rows($result)==0)
  {
    echo "0";
  }else{
 
    echo mysql_num_rows($result);
}
}
 
 
 
function search()
{
 
//base sql
  $sql = "select * from produkt_finder_table where 1 ";
 
//get the values from the form
 
 
  if ((!empty($_POST['Bauform_d']))&&($_POST['Bauform_d'] != 'all'))
  {
    $sql .= " and Bauform_d like '". addslashes($_POST['Bauform_d'])."%' ";
  }
 
  if ((!empty($_POST['Beschreibung_d']))&&($_POST['Beschreibung_d'] != 'all'))
  {
    $sql .= " and Beschreibung_d like '". addslashes($_POST['Beschreibung_d'])."%' ";
  }
  
   if ((!empty($_POST['SelectSchutzart_Cust_Bereich_d']))&&($_POST['SelectSchutzart_Cust_Bereich_d'] != 'all'))
  {
    $sql .= " and SelectSchutzart_Cust_Bereich_d like '". addslashes($_POST['SelectSchutzart_Cust_Bereich_d'])."%' ";
  }
  
   if ((!empty($_POST['SelectErfassungswinkel_Cust_Bereich_d']))&&($_POST['SelectErfassungswinkel_Cust_Bereich_d'] != 'all'))
  {
    $sql .= " and SelectErfassungswinkel_Cust_Bereich_d like '". addslashes($_POST['SelectErfassungswinkel_Cust_Bereich_d'])."%' ";
  }
  
   if ((!empty($_POST['ArtikelProduktgruppe_d']))&&($_POST['ArtikelProduktgruppe_d'] != 'all'))
  {
    $sql .= " and ArtikelProduktgruppe_d like '". addslashes($_POST['ArtikelProduktgruppe_d'])."%' ";
  }
 
 
 //run query
  $result = $this->conn($sql);
 
  if (!$result){ die("No results due to database error.<br>".mysql_error());  }
  
 
  if (mysql_num_rows($result)==0)
  {
    echo "No Results found!";
  }else{
    
	
     echo "<table border='1' class='corner'><th width='332'><a href='product.php'>Back</a></th>";
	 echo "<th>Product Result</th>";
	 echo "<td width='40' align='center' style=' font-size:16px'><div id='countR'>";
	 $this->countResult();
	 echo "</div></td>";
	    echo "</table>";
	 
	// echo '<div style="float:right; font-size:16px">'.$this->countResultAll().'</div>';
	// echo "<div style='float:left; font-size:16px'>Produkt Result</div>";
	
    echo "<table border='1' class='corner'>"; 
  
	 $i = 1;
    if((mysql_num_rows($result) % 2) == 0){
    $complete = false;
     }else{
    $complete = true;
     }
 
    while ($rows= mysql_fetch_array($result))
    {
    
	  echo "<td>";
	  echo "<ul><li class='addResult'><span class='red'>".$rows['Bauform_d']."<br /><span class='black'>".$rows['ArtikelName']."</span></span><img src='{imag}' alt='' /> <a href='#'>More Info</a> </li></ul>";
	  echo "</td>";
   
   if(($i % 2) == 0){
      
       echo "</tr><tr>";
    }   
	
      $i++;
}
if($complete == true){
 
    echo "<td>&nbsp;</td>";
 
}	 
 
	
	echo "</tr></table>";
	  echo "<table border='1' class='corner'><th width='332'><a href='product.php'>Back</a> <div></div></th>";
	 echo "<th>Product Result</th>";
	 echo "<td width='40' align='center' style=' font-size:16px'>";
	 $this->countResult();
	 echo "</td>";
	    echo "</table>";
 
}
}
 
 
function show_form()
{
  
  $Bauform   = $this->dropdown('Bauform_d','produkt_finder_table');
  $Beschreibung  = $this->dropdown('ArtikelGruppe_d','produkt_finder_table');
   $SelectSchutzart  = $this->dropdown('SelectSchutzart_Cust_Bereich_d','produkt_finder_table');
    $SelectErfassungswinkel  = $this->dropdown('SelectErfassungswinkel_Cust_Bereich_d','produkt_finder_table');
	 $ArtikelProduktgruppe  = $this->dropdown('ArtikelProduktgruppe_d','produkt_finder_table');
        
  echo "<form name='search' action='productResult.php?action=search' method='post'>
        <table width='50%' align='center' valign='center' class='corner'>
        <tr>
          <td colspan='2' align='center'> Search Form  <div id='countR' style='float:right; font-size:16px'>Count</div></td>
        </tr>
        <tr>
          <td align='right'>Montageart:</td><td>$Bauform</td>
        </tr>
		 <tr>
          <td align='right'>ProduktGruppe:</td><td>$Beschreibung</td>
        </tr>
		 <tr>
          <td align='right'>Speisung:</td><td>$SelectSchutzart</td>
        </tr>
        <tr>
          <td align='right'>Reichweite:</td><td> $SelectErfassungswinkel </td>
        </tr>
        <tr>
          <td align='right'>Erfwinkel:</td><td>$ArtikelProduktgruppe </td>
        </tr>
		
        <tr>
           <td colspan='2' align='center'><input type='submit' name='submit' value='Go!'></td>
        </tr>
        </table>
        </form>";
 
}//end function
 
 
 
 
function searchAll()
{
 
//base sql
  $sql = "select * from produkt_finder_table where 1 ";
 
//get the values from the form
//NOTE: You should do way more valdation on the values before you attempt to process anything
 
 
  if ((!empty($_POST['searchfield']))&&($_POST['searchfield'] != 'all'))
  {
    $sql .= " and ArtikelName like '". addslashes($_POST['searchfield'])."%' ";
  }
 
  //run query
  $result = $this->conn($sql);
 
  if (!$result){ die("No results due to database error.<br>".mysql_error());  }
  
 
  if (mysql_num_rows($result)==0)
  {
    echo "No Results found!";
  }else{
    
	
     echo "<table border='1' class='corner'><th width='332'><a href='product.php'>Back</a></th>";
	 echo "<th>Product Result</th>";
	 echo "<td width='40' align='center' style=' font-size:16px'><div id='countR'>";
	 $this->countResultAll();
	 echo "</div></td>";
	    echo "</table>";
	 
	// echo '<div style="float:right; font-size:16px">'.$this->countResultAll().'</div>';
	// echo "<div style='float:left; font-size:16px'>Produkt Result</div>";
	
    echo "<table border='1' class='corner'>"; 
  
	 $i = 1;
    if((mysql_num_rows($result) % 2) == 0){
    $complete = false;
     }else{
    $complete = true;
     }
 
    while ($rows= mysql_fetch_array($result))
    {
    
	  echo "<td>";
	  echo "<ul><li class='addResult'><span class='red'>".$rows['Bauform_d']."<br /><span class='black'>".$rows['ArtikelName']."</span></span><img src='{imag}' alt='' /> <a href='#'>More Info</a> </li></ul>";
	  echo "</td>";
   
   if(($i % 2) == 0){
      
       echo "</tr><tr>";
    }   
	
      $i++;
}
if($complete == true){
 
    echo "<td>&nbsp;</td>";
 
}	 
	 echo "</tr></table>";
	 echo "<table border='1' class='corner'><th width='332'><a href='product.php'>Back</a> <div></div></th>";
	 echo "<th>Product Result</th>";
	 echo "<td width='40' align='center' style=' font-size:16px'>";
	 $this->countResultAll();
	 echo "</td>";
	    echo "</table>";
 
}
}
}
 
$action = $_GET['action'];
 
$proFin = new Application();
    
switch($action) {
		
		case 'show':
            $proFin->show_form();
        break;
		
        case 'search':
            $proFin->search();
        break; 
		
	    case 'searchAll':
            $proFin->searchAll();
        break; 
		
		case 'count':
            $proFin->countResult();
        break; 
		
		case 'count2':
            $proFin->countResult();
        break; 
        }
?>

Open in new window

0
Comment
Question by:saad220
1 Comment
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 1050 total points
ID: 23634023
Rather than try to debug 439 lines of code for 350 points, let me suggest a simplification.  At its core, all AJAX does is pass data from the browser to the web server and take server data back into web page by replacing one or more DIV sections.  Any data-related errors are made more difficult to find when you're using AJAX because AJAX, by its very nature, deliberately obscures segments of your information.

Here is the "simplified" version of AJAX.  I think this may have been written by Lerdorf, not sure.  

I would suggest that in order to debug this code, you may want to make ALL the DIVs visible at once, so you can do things like var_dump() and see what is going on inside the backend scripts.

Best of luck with it, ~Ray
I find a lot of this AJAX stuff a bit of a hype.  Lots of people have
been using similar things long before it became "AJAX".  And it really
isn't as complicated as a lot of people make it out to be.  Here is a
simple example from one of my apps.  
 
First the Javascript:
 
function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
}
 
var http = createRequestObject();
 
function sndReq(action) {
    http.open('get', 'rpc.php?action='+action);
    http.onreadystatechange = handleResponse;
    http.send(null);
}
 
function handleResponse() {
    if(http.readyState == 4){
        var response = http.responseText;
        var update = new Array();
 
        if(response.indexOf('|' != -1)) {
            update = response.split('|');
            document.getElementById(update[0]).innerHTML = update[1];
        }
    }
}
 
This creates a request object along with a send request and handle
response function.  So to actually use it, you could include this js in
your page.  Then to make one of these backend requests you would tie it
to something.  Like an onclick event or a straight href like this:
 
  <a href="javascript:sndReq('foo')">[foo]</a>
 
That means that when someone clicks on that link what actually happens
is that a backend request to rpc.php?action=foo will be sent.
 
In rpc.php you might have something like this:
 
  switch($_REQUEST['action']) {
    case 'foo':
      / do something /
      echo "foo|foo done";
      break;
    ...
  }
 
Now, look at handleResponse.  It parses the "foo|foo done" string and
splits it on the '|' and uses whatever is before the '|' as the dom
element id in your page and the part after as the new innerHTML of that
element.  That means if you have a div tag like this in your page:
 
  <div id="foo">
  </div>
 
Once you click on that link, that will dynamically be changed to:
 
  <div id="foo">
  foo done
  </div>
 
That's all there is to it.  Everything else is just building on top of
this.  Replacing my simple response "id|text" syntax with a richer XML
format and makine the request much more complicated as well.  Before you
blindly install large "AJAX" libraries, have a go at rolling your own
functionality so you know exactly how it works and you only make it as
complicated as you need.  Often you don't need much more than what I
have shown here.
 
Expanding this approach a bit to send multiple parameters in the
request, for example, would be really simple.  Something like:
 
  function sndReqArg(action,arg) {
    http.open('get', 'rpc.php?action='+action+'&arg='+arg);
    http.onreadystatechange = handleResponse;
    http.send(null);
  }
 
And your handleResponse can easily be expanded to do much more
interesting things than just replacing the contents of a div.
 
-Rasmus

Open in new window

0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Containers like Docker and Rocket are getting more popular every day. In my conversations with customers, they consistently ask what containers are and how they can use them in their environment. If you’re as curious as most people, read on. . .
It’s a season to be thankful, and we’re thankful for users like you who engage on site, solve technology problems, and network with others in the industry. What tech are we most thankful for? Keep reading.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
Suggested Courses
Course of the Month18 days, 23 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question