July 27, 2011

How can I filter POST numeric values in php?

Question by user841823

Numeric values..

$price = $_POST['price'];
$zipcode = $_POST['zipcode'];

How can I filter two fields passing through a single select tag field called category_id that uses the explode() to recieve the values from this category_id field.

Form

    <?php echo '<label for="Category">Category:</label>
<select name="category_id" size="1" ><br />';


$sql = "SELECT id, name FROM category ORDER BY name";

$rs = mysql_query($sql);

while($row = mysql_fetch_array($rs))
{
echo "<option value="".$row['name']."$".$row['id']."">".$row['name']."</option>n  ";
}


echo '</select>';

the way I receive the category_id field with explode but don’t know how to filter it since it is a numeric and data field at the same time.

$option = explode("$", $_POST['category_id']); 

enter code here

Answer by Phil

Are you just trying to retrieve the category name and ID from the posted, $ delimited category_id field?

If so, then this should do it

$option = explode("$", $_POST['category_id']);
$name = $option[0];
$id   = $option[1];

I would be more inclined to just set the ID in the <option> value attribute and fetch the name from the database or a pre-fetched associative array.

Update

If you’re wanting to validate that field, you could try something like

if (!preg_match('/^[a-zA-Z0-9]+$d+$/', $_POST['category_id'])) {
    // not valid
}

I wouldn’t attempt to filter out invalid characters on that field. Validation and error conditions are more concise.

Answer by Starx

Not sure, If i got you correctly. If you are trying to receive the name and id of the product from the same select box, using your technique

echo "<option value="".$row['name']."$".$row['id']."">".$row['name']."</option>n  ";

Change this line to this. Just replace $ with “_” for simplicty

echo "<option value="".$row['name']."_".$row['id']."">".$row['name']."</option>n  ";

Then while processing it

$category_id = $_POST['category_id'];
$carr = explode("_",$category_id);
$category = $carr[0];
$id = $carr[1];

//now verify them
if((int)$id>0) { //id is valid number
// and so on
July 20, 2011

How to get data from jQuery.post()?

Question by Alwayz Change

My problem is that i wanna use post data outside it’s function, example:

$(function() {
  var s = 'something ';
  $.post('ajax.php', {option: 'test'}, function(data) {
    s += data; // data: 'hello world';
  });
  alert(s); // output: 'something ';
});

my expected result is ‘something hello world’.
how can i deal with this?
Thanks

Answer by Nishant

Use $.ajax with async:false, I assume the data is coming as content-type:json/application e.g.

var s = 'something ';
$.ajax({
      url: "ajax.php",
      type: "POST",
      data: ({option: 'test'}),
      dataType: "json",
      async:false,
      success: function(msg){
         s += msg.data;//msg={data: "hello world"}
      }
   }
);
alert(s);

Answer by Starx

You code should be working. Unless the ajax.php is not echoing “Hello World” at the end. Please make sure of it and try to post the results. Errors or output, whatever you can feed us.

Mysql fetch array, table results

Question by Crays

i’m pretty new to this and not sure how should i do it,

I’ve got a database with a column called “names”

how can i make it display in so?

  <tr>
  <td width="270px">Henry</td>
  <td width="270px">Jeffrey</td>
  <td width="270px">Hansel</td>
  </tr>

  <tr>
  <td width="270px">Michelle</td>
  <td width="270px">Jackson</td>
  <td width="270px">Ivan</td>
  </tr>

I only know how i should do it if the records goes one after another vertically.

  $result = mysql_query('SELECT * FROM member');

  while($row = mysql_fetch_array($result))
  {
  echo'
  <tr>
  <td width="270px">'.$row['names'].'</td>
  <td width="270px">Jeffrey</td>
  <td width="270px">Hansel</td>
  </tr>';

Kinda stucked here…

Sorry i forgot to put this.

what i want is that it should loop the tags along. So i can have a 3 column table with infinite rows.

what bout this one? What if i want this to loop instead?

<tr>
<td><img src="images/ava/A.png" /></td>
<td>A</td>
<td width="2px" rowspan="3"></td>
<td><img src="images/ava/B.png" /></td>
<td>B</td>
</tr>


<tr>
<td>A</td>
<td>B</td>
</tr>

Answer by ascii-lime

$row will update on each iteration of the loop:

$result = mysql_query('SELECT * FROM member');

echo '<tr>';

for($i = 0; $row = mysql_fetch_array($result); $i = ($i+1)%3){
    echo '<td width="270px">'.$row['names'].'</td>';
    if($i == 2)
        echo '</tr><tr>';
}

echo '</tr>';

Answer by Starx

You know accomplish this by assigning the row count before you start the variable and few flags to know initialized loop or started/ended loop.

$i = 1;
$initFlag = false;
$flag = "closed";
while($row = mysql_fetch_array($result)) {
    if($i%3 == 0) $initFlag = false;
    if($flag == "closed" && ($i == 1 || $i % 3 == 1)) { 
        echo "<tr>"; $flag = "started"; $initFlag = true; 
    }

    echo '<td width="270px">'.$row['names'].'</td>';

    if(!initFlag && $flag == "started" && $i % 3 ==0) { 
        echo "</tr>"; $flag = "closed"; 
    }


    $i++;
}

Line break with css

Question by winchendonsprings

I have 7 divs in a row with all very little content. I want to have the first 3 one a line then the next 3, and so on.

<div class="parent">
 <div class="child-a">abc</div>
 <div class="child-b">def</div>
 <div class="child-c">ghi</div>
 <div class="child-d">jkl</div>
 <div class="child-e">mno</div>
 <div class="child-f">pqr</div>
 <div class="child-g">stu</div>
</div>

So how can I make this work?

For the first line I have

.child-a, .child-b, .child-c {
  padding: 0 2% 0 0;
  width:100%
  display: inline;
  float: left;
 }

What would the css be for child-c, child-d, child-e so that they would be displayed below child-a, child-b, child-c rather than on the same line?

My complete code: http://jsfiddle.net/winchendonsprings/UfswL/11/

Answer by Starx

A better way to go would be something like this.

.parent div { float: left; }
.parent div:nth-child(3n + 1) { clear: left; }

Every element after the third will go to next line. Demo

This is do what you asked the first 3 one a line then the next 3, and so on. efficiently despites some browsers compatiblity issues.

July 19, 2011

Shared database desktop/web app

Question by tonycanyouhearme

We have 2 applications: web-based (PHP) and Desktop (VB) sharing the same database (Hostgator). Our web app has a fast access to the database (it’s localhost). Our desktop application suffers with slow access and frequent timeouts.
What’s the best approach to this kind of issue? Should we share a database? Are there any other solution.
Thanks

Answer by Starx

AFAIK, I dont suppose, this could be a problem. Because, web or desktop, both access the database with MySQL server, so it mustn’t be giving mixed performance results.

how to submit a form from a php script

Question by elduderino

Possible Duplicate:
Auto Submitting a form (cURL)

I have a form which submits to a php script. In this form I need to collect all the $_POST data and then post this on to another form (the reason for this isn’t really relevant but there is a good reason).

My question is once I’ve collected all the data from the initial form submit, sanitised it and assigned it all to variables how do i then package it all up to send to the next form? The second form is expecting a $_POST with hidden fields with particular name attributes….so how do i do this? do I build the actual html and submit that somehow to the second form or do I buld some sort of array and send that?

hope this makes sense. Kind of hard to put in to words.

Answer by RiaD

  1. You can generate form and submit onLoad by Javascript
  2. You can use curl to send POST query (from your server but not from client)

Answer by Starx

The better way woudl be to store the sanitized variables in the session.

Collect all the information you need from all the forms you need.

Then after you have all the data needed, then finally update the DB (or Somethign else)

July 13, 2011

Zend Framework: Zend_Form is not including 'name' attribute in form tag

Question by Simpanoz

I have following class for a form:

class Application_Form_ContactForm extends Zend_Form
{
    public function init()
    {
      $this->setName('contact_us');
     /* 
       I have also used follwing statements (one by one) to set name attribute 
       // $this->setAttrib('name', 'myForm-name');
       // $this->setAttribs(array('name' => 'frm', 'id' => 'frmlogin')); 
     */
    }
}

When I run this form, I get follwoing html code:

<form id="contact_us" enctype="application/x-www-form-urlencoded" action="" method="post"><dl class="zend_form">

The above mentioned html code doesn’t show ‘name’ attribute of the form html tag.

Can some one guide me in this regards, how to rectify it.

Answer by Starx

The “name” attribute is allowed in HTML4 but has been deprecated in XHTML1.0. The HTML specification does not allow for a “name” attribute for forms. Check Here and here.

Zend Framework is just following the rules.

But why do you need a name is form anyway? Almost everything can be done using class and id.

But, if you really need it that bad try setting a ID first and then the name, it might work.

Search functionality with pagination on a website

Question by acidpaul

I’m developing a search functionality with pagination in my site to search for the product name and the brand name. I’m using this query to get the user’s search request:

SELECT *
from products
WHERE name = 'optimum nutrition'
    OR brand = 'optimum nutrition' 
    OR name LIKE '%optimum%' 
    OR brand LIKE '%optimum%' 
    OR name LIKE '%nutrition%' 
    OR brand LIKE '%nutrition%'

I would like to display first the products that has the full ‘optimum nutrition’ in either the brand name and in the product name. How will I accomplish this?

Any suggestion would be greatly appreciated.

Answer by Shef

Try:

SELECT *, 
CASE WHEN (name = 'optimum nutrition' OR brand = 'optimum nutrition') THEN 1 ELSE 0 END AS full_match,
CASE WHEN (name LIKE '%optimum%' OR brand LIKE '%optimum%' OR name LIKE '%nutrition%' OR brand LIKE '%nutrition%') THEN 1 ELSE 0 END AS half_match
FROM products 
WHERE (name = 'optimum nutrition' OR brand = 'optimum nutrition')
OR (name LIKE '%optimum%' OR brand LIKE '%optimum%' OR name LIKE '%nutrition%' OR brand LIKE '%nutrition%')
ORDER BY full_match, half_match

Answer by Starx

I will suggest you look into
Zend Search Lucene, to put search functionality on your page.

...

Please fill the form - I will response as fast as I can!