1

I´m trying to get uses to the PHP PDO Syntax. Maybe somone can have a look at this peace of code. It seems it´s a bit much lines for little effort.

I catch a User Post-Input (ID). Know I need for calculation reason the values BejagFlach from all Users (the sum of them) and the single value BejagFlach from the User identified by the ID. Do I need two querys for this like here? or is there are shorter/better way?

/* Fetch POST Data */
$User_Num = $_POST['User_Num'];

/* Build query for one User */
$dbSelect =  $objDb->prepare("SELECT BejagFlach,Name FROM Benutzer WHERE lfdNr = :User_Num");
$dbSelect -> setFetchMode(PDO::FETCH_ASSOC);  
$dbSelect->execute(array(':User_Num' => $User_Num));

/* Build query for all Users */
$dbSelect2 =  $objDb->prepare("SELECT BejagFlach FROM Benutzer");
$dbSelect2 -> setFetchMode(PDO::FETCH_ASSOC);  
$dbSelect2->execute();

/* Output + Calculate */    
while($row = $dbSelect->fetch()) {  
    $totalUser +=  $row['BejagFlach'];
    $who = utf8_encode($row['Name']);
}  

/* Output + Calculate */    
while($row = $dbSelect2->fetch()) {  
    $totalAll += $row['BejagFlach'];
}  

Kind regards, toni

4

2 回答 2

0

No, it doesn't seem too much?

The only thing I would change, is if you are only after the number of records matched, use rowCount

<?php
    $sel = $dbh->prepare('select * FROM fruit');
    $sel->execute();

    /* Return number of rows that were deleted */
    print("Return number of rows that were selected:\n");
    $count = $sel->rowCount();
    print("Seleted $count rows.\n");
?>
于 2012-08-08T12:13:59.023 回答
0

Since you need at least your second query, I would do like this so you do only 1request to the database :

$dbSelect =  $objDb->prepare("SELECT BejagFlach,lfdNr FROM Benutzer");
$dbSelect -> setFetchMode(PDO::FETCH_ASSOC);  
$dbSelect ->execute();
while($row = $dbSelect->fetch()) {  
    $totalAll +=  $row['BejagFlach'];
    if( $row['lfdNr'] == $UserNom) {
        $totalUser += $row['BejagFlach'];
        $who = utf8_encode($row['Name']);
    }
}  
于 2012-08-08T12:14:37.130 回答