Log in

View Full Version : Resolved zendframework dB interaction



ggalan
06-04-2011, 08:27 PM
im using ZF's framework to select/update from a dB. the connection works but the result has issues because the views loop indexes through and when you delete an item the index number does not match up with the 'id' key.

controller:


public function listAction()
{
$params = array('host' =>'zc24', 'username' =>'root', 'password' =>'myPassword', 'dbname' =>'demo' );
$DB = new Zend_Db_Adapter_Pdo_Mysql($params);
$DB->setFetchMode(Zend_Db::FETCH_OBJ);

$sql = "SELECT * FROM user WHERE deleted=0 ORDER BY first_name ASC";
$result = $DB->fetchAssoc($sql);

$this->view->assign('title','Member List');
$this->view->assign('description','Below, our members:');
$this->view->assign('datas',$result);
}


view:


<table border="1">
<tr>
<th>ID</th>
<th>User Name</th>
<th>First Name</th>
<th>Last Name</th>
<th>Action</th>
</tr>
<?

$datas = $this->datas;
$i = 1;

$datas = $this->datas;
for($i = 1; $i<= count($datas);$i++){

?>
<tr>
<td><?=$datas[$i]['id']?></td>
<td><?=$datas[$i]['user_name']?></td>
<td><?=$datas[$i]['first_name']?></td>
<td><?=$datas[$i]['last_name']?></td>
<td>
<a href="edit/id/<?=$datas[$i]['id']?>">Edit</a>
|
<a href="del/id/<?=$datas[$i]['id']?>">Delete</a>
</td>
</tr>
<? }?>
</table>


so, i got it working like this, but i dont want to use procedural techniques. my question is: how do i achieve 'mysql_fetch_array' in a more object way? i want to keep all the SQL queries in the controller as well as connection to the dB.


<table border="1">
<tr>
<th>ID</th>
<th>User Name</th>
<th>First Name</th>
<th>Last Name</th>
<th>Action</th>
</tr>
<?
mysql_connect ("localhost", "root", "myPassword") or die('error: ' . mysql_error());
mysql_select_db ("demo");

$queryX = "SELECT * FROM user WHERE deleted=0 ORDER BY id ASC";
$resultX = mysql_query($queryX) or die (mysql_error());

$datas = $this->datas;
$i = 1;
while ($datas = mysql_fetch_array($resultX)){
?>
<tr>
<!-- <td><?//=$datas['id']?></td>-->
<td><? echo $i; ?></td>
<td><?=$datas['user_name']?></td>
<td><?=$datas['first_name']?></td>
<td><?=$datas['last_name']?></td>
<td>
<a href="edit/id/<?=$datas['id']?>">Edit</a>
|
<a href="del/id/<?=$datas['id']?>">Delete</a>
</td>
</tr>
<?
$i+=1;
}?>
</table>


also can anyone tell me how to highlight parts of my code so i can show you the areas thats important?

ggalan
06-05-2011, 05:34 PM
yonman got it. the fix was in the loop from the original view


//replace for loop with foreach
//for($i = 1; $i<= count($datas);$i++){
foreach($datas as $row){
<td><?=$row['id'];?></td>
<td><?=$row['user_name'];?></td>
<td><?=$row['first_name'];?></td>
<td><?=$row['last_name'];?></td>
// the rest of the code