PDO PHP Trying to create a Class

I'm trying to create an OOP file(s) and I;m not sure what I'm doing wrong:

The first file is to grab a total from a DB table:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$pdo = new PDO("mysql:host=...;dbname=...", "l...", "...");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

class moneyMade	{
		function totalAmounts($pdo){
			$total_amounts = 	"SELECT SUM(amount) AS amount
								FROM amounts";
			$pdosb = $pdo->prepare($total_amounts, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
			try {
//  GET RESULTS
				while($row = $pdosb->fetch()):
//  RETURN THE RESULTS FROM THE FUNCTION
				$amount = $row['SUM(amount)'];
				return $amount;
				endwhile;	
			}
			catch(PDOException $e) {
   			echo 'ERROR: ' . $e->getMessage();
			}
			
		}//  END TOTAL AMOUNTS

}  //  END CLASS
?>

Open in new window

Then the other file where I want to run it:
<?php
include('classes/functions.php');
?>
<!--  START AMOUNTS MADE  -->
			<fieldset>
				<b>AMOUNTS::</b><br />
				<?php
					$amount = new moneyMade();
					$amount ->totalAmounts($pdo);
				?>
				
				<form>
					<table>
						<tr>
							<td>TOTAL</td>
						</tr>
						<tr>
							<td><?php $amount->amount; ?></td>
						</tr>
						
					</table>
				</form>
			</fieldset>
<!--  END AMOUNTS MADE  -->

Open in new window

I get the ERROR:
 Undefined property: moneyMade::$amount  in the above file.
LVL 7
rgranlundAsked:
Who is Participating?
 
Slick812Commented:
it looks like your CLASS could be written better as it should contain the OBJECT for the PDO operator, below is my version -
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

class moneyMade	{
  public $cPDO = false; // CLASS property for PDO object 
  
// Make your CLASS produce the PDO object when it starts in __construct()
  public function __construct() {
  $this->cPDO = new PDO("mysql:host=...;dbname=...", "l...", "...");
  $this->cPDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  }
  
  public function totalAmounts(){
  $sql = 	"SELECT SUM(amount) AS amount FROM amounts";

// If you use a simple PDO Query you have less code
  try {
    $statem = $this->cPDO->query($sql);
    $row = $statem->fetch(PDO::FETCH_ASSOC);
    }  //  END TRY
    catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
    }

  return $row['amount']; // RETURN the number of SUM additions
  }//  END TOTAL AMOUNTS

}  //  END CLASS

?>

<!--  START AMOUNTS MADE  -->
  <fieldset><b>AMOUNTS::</b><br />
<?php
// It helps me if I name the variable same as CLASS name
$moneyMade = new moneyMade();

// It helps me if I name the variable the same as what the variable has in it
$total = $moneyMade->totalAmounts();
?>
  <form><table>
    <tr><td>TOTAL</td></tr>
    <tr><td><?php echo $total; ?></td>
    </tr>
  </table></form>
  </fieldset>
<!--  END AMOUNTS MADE  -->

Open in new window

, I tried this on my server and it works there, please ask questions if you need any information about this.
0
 
Chris StanyonCommented:
You are trying to access a property of your class called amount:

<?php $amount->amount; ?>

It doesn't exist. Your class has one method - totalAmount() which returns the amount, so you will need to assign the return value of that method call to a variable and use that (or just output it directly).

One of these 2 blocks will work:

<?php
$amount = new moneyMade();
$myAmount = $amount->totalAmounts($pdo);
?>

<?php echo $myAmount; ?>

Open in new window

or

<?php
$amount = new moneyMade();
echo $amount->totalAmounts($pdo)
?>

Open in new window

Also, if you query only returns 1 record, you don't need a loop. You've also aliased the SUM in your query as 'amount' so that's what the column is called

$row = $pdosb->fetch()
return $row['amount'];

Open in new window

0
 
Ray PaseurCommented:
It looks like the Class MoneyMade script prepares the query but does not actually run the query.

To help with things like this, add error_reporting(E_ALL) to the top of all of your PHP scripts.  Then when you accidentally rely on an undefined variable you have a better chance of catching the issue before it wastes your time. Without the raised level of error reporting, PHP will issue a Notice but will suppress the Notice and you'll never be told what was wrong!

You will also want to make the $amount variable into a class property.  Properties are assigned with the $this-> keyword.  Run this little script to see what is visible in the Thing class.  The $abc contains local data, usable only inside the class constructor.  The $this->abc is a class property, accessible outside the $x object, and therefore visible to var_dump().

<?php

Class Thing
{
    public function __construct()
    {
        $abc = 'ABC';
        $this->abc = '123';
    }
}

$x = new Thing;
var_dump($x);

Open in new window

Forgetting to use $this-> has got to rank as the most frequently made coding error in PHP object oriented programming!
0
Network Scalability - Handle Complex Environments

Monitor your entire network from a single platform. Free 30 Day Trial Now!

 
rinfoCommented:

$total_amounts =       "SELECT SUM(amount) AS amount       FROM amounts";

In the above context is this correct.

$amount = $row['SUM(amount)'];


i think this should be $amount = $row['amount'];
I would have preferred
$total_amount_qry =       "SELECT SUM(amount) AS totamts       FROM amounts";
$sum_amount = $row['totamts'];

I suggest following codes
<?php
	
	error_reporting(E_ALL);
	ini_set('display_errors', '1');

					
	$pdo = new PDO("mysql:host=...;dbname=...", "l...", "...");
	$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


	class moneyMade	{

		function totalAmounts($pdo)
		{
			$sum_amounts_qry = 	"SELECT SUM(amount) AS totamts FROM amounts";
			$sum_amounts = 0;
			$pdosb = $pdo->prepare($total_amounts, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
			try {
					//  GET RESULTS
				    $pdosb->execute();
					while($row = $pdosb->fetch()):
					//  RETURN THE RESULTS FROM THE FUNCTION
					$sum_amount = $row['totamts'];
					return $sum_amount;
					endwhile;	
			}
			catch(PDOException $e) {
   			echo 'ERROR: ' . $e->getMessage();
			}
			
		}//  END TOTAL AMOUNTS

}  //  END CLASS
?>

<?php	
	include('classes/functions.php');
?>
<!--  START AMOUNTS MADE  -->
			<fieldset>
				<b>AMOUNTS::</b><br />
				<?php
					$amount = new moneyMade();
					$amount ->totalAmounts($pdo);
				?>
				
				<form>
					<table>
						<tr>
							<td>TOTAL</td>
						</tr>
						<tr>
							<td><?php $amount->sum_amounts; ?></td>
						</tr>
						
					</table>
				</form>
			</fieldset>
<!--  END AMOUNTS MADE  -->

Open in new window

0
 
Chris StanyonCommented:
@Ray - can't believe I missed the non-execution!!

@rinfo - I've already covered that

@rgranlund - as Ray said, you also need to make sure you execute your query:

function totalAmounts($pdo){
   $total_amounts = "SELECT SUM(amount) AS amount FROM amounts";
   $pdosb = $pdo->prepare($total_amounts, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
   try {
      $pdosb->execute();
      $row = $pdosb->fetch();
      return $row['amount'];
   } catch(PDOException $e) {
      echo 'ERROR: ' . $e->getMessage();
   }
}

Open in new window

0
 
rinfoCommented:
@Chris Stanyon my emphasis was on wrong use of column name .
And what i submitted was a more appropriate way to achieve what author is trying to achieve.
0
 
Chris StanyonCommented:
@rinfo - read the last part of my opening comment!
0
 
rinfoCommented:
@Chris Stanyon i stand corrected and  perhaps deleted.
0
 
Chris StanyonCommented:
No worries - at least we're all on the same page :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.