PHP-Zend
PHP-Zend

Reputation: 311

dynamic drop down list is not working properly

I'm working on a small project and I needed to create a drop down list dynamically. I have found a way for that and developed the code according to it. I'm using php with Zend Framework and my database is mysql.

here is my codes:

below is the PVHandler.php class which I used to connect to the db and retrieve values.

class PVHandler {

public function generateSelect(){

    try {
        $con = mysql_connect("localhost","root","");
        mysql_select_db("accounts_db",$con);

    $data = mysql_query('SELECT `desc` FROM `expense` LIMIT 0 , 30');
    } catch (Exception $e) {
        die('Error!!!'.$e);
    }
    $desc = mysql_fetch_array($data);
    $html = '<select name="expenses">';
    foreach ($desc as $des){
        $html.='<option value='.$des.'>'.$des.'</option>';
    }
    $html.='</select>';
    return $html;
}

}

?>

The generateSelect() method in above class is called inside the newPV.phtml file.

Here is it.

<html xmlns="http://www.w3.org/1999/xhtml" lang = "en">
<style>
</style>
<head></head>
<body>
 <div><?php include APPLICATION_PATH.'/views/scripts/layouts/header.php';?></div>
  <div id="title"><h3>TSDC Lanka (Private) Ltd.</h3>
  <h2>Payment Voucher</h2></div>
   <div id="content"><form action="#" method="post">
    Date : <input type="text" name="date" id="dt" value=<?php echo date("j/M/Y");?>></td>
<span style="align:right;">Document No: <input type="text" name="docNo"><br><br></span>
Cheque No: <input type="text" name="cheqNo" ><br><br>
Payment in favour of : <input type="text" name="payin" style="width:700px"><br><br>
Description :  <?php include APPLICATION_PATH.'/models/db/PVHandler.php';
 $pv = new PVHandler();             /*Here I have called the method*/
 $html= $pv->generateSelect();
  echo $html; ?>
</form></div>
</body>
</html>

I want to retrieve the expenses in the expense table, in accounts_db database.

I have entered these values to the database for testing.

exid      desc
 1         Water
 2         Electricity
 3         Salaries
 4         Printing and Stationary

The output only displays a drop down list with "Water". The "Water" is displayed twice.

Why does this happen? Please help me.

Thanks in advance

Charu

Upvotes: 0

Views: 194

Answers (1)

WolvDev
WolvDev

Reputation: 3226

The mysql_fetch_array only selects one (1) row of the database. To select ALL results you need to use a while loop:

$html = '<select name="expenses">'; 
while($desc = mysql_fetch_array($data)) {
    $html.='<option value='.$desc['desc'].'>'.$desc['desc'].'</option>'; 
}

You surly can create an array with the data and than use a foreach to write the data.

Upvotes: 1

Related Questions