Jump to content

Recommended Posts

I need assistance with an assignment for school.  I am trying to pull the 18th president's first and last name from a database.  I keep getting the $first_name and $last_name variable undefined.  I have defined them both I think.

 

webpage- http://tomcat.cit.iupui.edu/coxcw/cit21500/exercises/database/classes/person_display.php

person.class.php

person_display.php

Link to comment
https://forums.phpfreaks.com/topic/287873-php-help/
Share on other sites

 

 

I have defined them both I think.

No not at all you have only defined them within the respective methods, for example  $firstname  is defined in the  retrieve_person_first_name()  method and  $lastname  is defined in the  retrieve_person_last_name()  method. Just because you defined them in a method does not mean they are available outside of that method. You need to read up on variable scope.

 

You also do not appear to be executing these methods at all in person.php. You have only initiated the  $class_person  object

$class_person = new Person();

After this you should be claling the firstname and lastname methods from the $class_person object, eg for the firstname

$first_name = $class_person->retrieve_person_first_name();

Problem is upon calling this method you'll now get even more errors.

	public function retrieve_person_first_name()
	{
		db_connect();
		//$user_id = $_GET['user_id'];
		//$first_name = $_GET['first_name'];
		$query = "SELECT first_name FROM presidents WHERE user_id = 18 LIMIT 0,1";
		$result = $conn->query($query);
		$record = $result->fetch(PDO::FETCH_OBJ);
		$first_name = $record->first_name;
		return $first_name;
		exit();
	}

This is because when you call the $class_person->retrieve_person_first_name() method it will try to call a function called db_connect() on line 57. But there is no function called db_connect() defined by your code. However there is a method called db_connect() in the person class ( on line 38).  You cannot call a method from within a class in this way. Instead you'll prefix the method name with $this-> eg:

$this->db_connect();

But this should not even be happening. The database connection should not even be handled by the firstname/lastname methods. The database connection should either be initiated by the class constructor or by passing in the database instance to the constructor upon instantiation . The database instance should then be defined as a property to the class. Personally I take the latter approach.

 

So the database connection code should now be outside of the person class, person.php should now read as

<?php
include('person.class.php');

$host     = 'localhost';
$database = '21500TestDatabase';
$user     = '21500student';
$pwd      = '21500-student-general-access';
    
// try to connect to datatabase
try {
    $conn = new PDO('mysql:host=' . $host . ';dbname=' . $database, $user, $pwd);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $conn->exec('SET NAMES "utf8"');
}
//catch statement
catch(PDOExeception $e) {
    die('Unable to connect to the database server' . $e->getMessage());
}

// pass the database instance ($conn) to the Person class
$class_person = new Person($conn);

$first_name = $class_person->retrieve_person_first_name();
$last_name  = $class_person->retrieve_person_last_name();
?>
<!doctype html>
<html>
<body>
<p>The presidents name is <?=$first_name;?> <?=$last_name;?>.</p>
</body>
</html>

Next the start of the person class definition should read as

	/* Person Class */
	class Person {
		
		/* Attributes */
		private $first_name;
		private $last_name;

        // database property
		private $conn;
		
		
		/* Constructor function */
		public function __construct($conn) {
			//This code will run when the object is created.
			$this->conn = $conn; // defone database instance as a property
		} 

               ....

So now in the retrieve_person_first_name() method delete the call to $this->db_connect(); We no longer need this now. And change  $conn->query  to  $this->conn->query

 

So now hopefully when when we call the $class_person->retreive_person_first_name() it should return the firstname

$first_name = $class_person->retrieve_person_first_name();
echo 'Firstname: ' .$first_name;

You'll now apply the same changes for the lastname method.

 

But our class still has issues. It only returns the firstname and lastname for the 18th person in the database. This is not good what we want to be able to do is make the firstname and lastname methods reusable so we can get other peoples names from the database too.

 

We'll do this by passing the row id as an argument to the method. While we're at this stage I think it is a good idea to combine the firstname and lastname methods into one method as mysql can retrieve more then one piece of data from a query. There is no need to have separate methods.

 

Deletinng the firstname and lastname class methods lets create a new method call get_by_userid

	public function find_by_userid($id)
	{
                // find the user by id retuning the first_name and last_name columns
		$query = 'SELECT first_name, last_name FROM presidents WHERE user_id = '.intval($id).' LIMIT 0,1';
		$result = $this->conn->query($query);

		if($result)
		{
			if($row = $result->fetch(PDO::FETCH_OBJ))
			{
                                // define first_name and last_name as propeties
				$this->first_name = $row->first_name;
				$this->last_name = $row->last_name;

				return true;
			}
		}

		return false;
	}

Now in person.php we can replace

$first_name = $class_person->retrieve_person_first_name();
$last_name  = $class_person->retrieve_person_last_name();

With

$class_peron->find_by_userid(18);

We can also replace <?=$first_name;?> <?=$last_name;?> with a method call to retrieve_full_name() which will return the a string formatted with the persons firstname and lastname 

<p>The presidents name is <?=$class_person->retrieve_full_name(); ?>.</p>

So now hopefully the code should now be running as expected. Hope you learned something along the way. 

Link to comment
https://forums.phpfreaks.com/topic/287873-php-help/#findComment-1476657
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.