0

What I am trying to achieve:

Explanation:

I am constructing a simple process where my class 'Content' will convert an array into objects and print them out on my webpage as they are called.

Expected Outcome:

$stmt PDO will bind parameters using $stmt->bindParam(). The bind variables match the $args in the construct. Then pass the array to a static method which will convert the array into objects.

Outcome

Using print_r(), I can track my PDO results to the stage of converting to $object. I will note the result in comments at the end of the code.

  1. As I move through the results, print_r() returns the database column names rather than the bindPram() variable names.
  2. In the end, I have a blank array displayed on my webpage.

To me it seems my bindParams() isn't working in my PDO.The PDO itself is working because I am able to select and print from the database. I am not sure what I have done incorrectly.

My code

<?php

class Content {

// --- START OF ACTIVE RECORD CODE ---

public $n_id;  // bind with column name 'nid'  in database
public $n_text; //bind with column name 'ntext' in database


// instantiating a STATIC Database Connection for the class to use
static protected $database;

static public function set_database($database) {
  self::$database = $database;
}

// constructing arguments
public function __construct($args=[]) {

  $this->n_id = $args['n_id'] ?? '';
  $this->n_text = $args['n_text'] ?? '';

}

// Multi use method to pass in sql that will execute the PDO only two parameters are bound nid and ntext.

static public function look_all_sql($sql) {

// -------------BEGIN PDO-----------

// checking to ensure PDO extensions are loaded

if (!extension_loaded ('PDO' )) {
    echo 'PDO is NOT loaded!'."\n";
    if (!extension_loaded('pdo_mysql')){
        echo 'PDO mysql driver is NOT loaded.'."\n";
    }
}

// preparing PDO by loading sql from method find_all(), calling db connection, and storing in variable $stmt

  $stmt = self::$database->prepare($sql);

  // Binding Parameters for sql 
  $stmt->bindParam(':nid', $n_id,  PDO::PARAM_INT);
  $stmt->bindParam(':ntext', $n_text,  PDO::PARAM_STR);

  // executing $stmt PDO and storing the result in $stmt
  $stmt->execute();


// ------------END PDO ----------

  // Checking to see if a result exist. If no result is stored in $stmt, then it will echo "Database query failed." If result is stored, then the method will continue 

if(!$stmt) {
    exit("Database query failed.");
  }

// -------- BEGIN TURNING RESULTS INTO OBJECTS --------
$object_array = [];

  // The result $stmt will be stored in the variable $record

  while($record = $stmt->fetch(PDO::FETCH_ASSOC)) {


// passing $record to static method instantiate() to be converted to an object and returned as $object_array

    $object_array[] = self::instantiate($record);

}
  // clearing the PDO after information is stored in $record
    $stmt->closeCursor();

  return $object_array;

// ------------ END TURNING RESULTS INTO OBJECTS --------

}
// method to test passing $sql to method look_all_sql();

static public function find_all(){

  $sql = "SELECT * FROM `ncontent`";
//passing $sql to static method 
    return self::look_all_sql($sql);

}

// --- BEGIN INSTANTIATING METHOD TO CREATE OBJECTS ---

static protected function instantiate($record) {

  $object = new self;

  // Auto assign values
  foreach($record as $property =>  $value) {

    if(property_exists($object, $property)){
      $object->$property = $value;

}



  }


}
// ----- END INSTANTIATING OF RECORD TO CREATE OBJECTS ---

// ---END OF ACTIVE RECORD CODE---



}


?>

What is populated on webpage with no print_r

Nothing page is empty.

Outcomes based on print_r:

On $return

$return = $stmt->fetch(PDO::FETCH_ASSOC);
 return print_r($return);
  • Displayed on page:

Array ( [0] => Array ( [nid] => 2 [ntext] => This is the first Line called the Top Main )

On $record in look_all_sql($sql)

while($record = $stmt->fetch(PDO::FETCH_ASSOC)) {
return print_r($record);
  • Displayed on page:

    Array ( [nid] => 2 [ntext] => This is the first Line called the Top Main ) 1

On $record from static method instantiate():

static protected function instantiate($record) {
return print_r($record);
  • Displayed on page:

Displays the full array of database information. No bound prams. Acts like a fetchAll() command:

Array ( [nid] => 2 [ntext] => This is the first Line called the Top Main ) Array ( [nid] => 3 [ntext] => Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor ) etc

On $object in the static instantiate($record) method. The number of objects match the number of objects from my database. However, it does not correlate with the information from the database.

$object = new self;
return print_r($object); 
  • At the end of the foreach() loop yields the same result. Displayed on webpage.

    Content Object ( [n_id] => [n_text] => ) Content Object ( [n_id] => [n_text] => ) Content Object ( [n_id] => [n_text] => ) Notice: Array to string conversion in H:\Website\xampp\htdocs\hinkleycentersandbox\public\includes\maincontenttopsection.php on line 24 Array

At this point $object is supposed to be returned to $object_array[].

print_r on $object_array:

  • Displayed on page:

    Array ( [0] => [1] => )

Code on webpage:

<h2><?php

    $ncontents = array(Content::find_all());

    foreach($ncontents as $ncontent) {
        echo $ncontent;
         }

    ?></h2> 
danronmoon
  • 3,814
  • 5
  • 34
  • 56
Wes Henderson
  • 117
  • 1
  • 7
  • 2
    you are binding undefined variables `$n_id, $n_text` to the query with no parameters. `$sql = "SELECT * FROM \`nconten\`"; return self::look_all_sql($sql);` Your code makes no sense – Alex Mar 12 '19 at 18:42
  • I think you mean `self::$n_id` and `self::$n_text`, but remember that __construct() does not fire when used in a static context, so they won't have any values. – aynber Mar 12 '19 at 18:46
  • @Alex my database table names are nid and ntext. I am binding nid with $n_id and and ntext with $n_text. I state that in comments when I define the variable. What should I do differently? – Wes Henderson Mar 12 '19 at 18:49
  • 1
    `SELECT * FROM nconten WHERE nid = :nid AND ntext = :ntext` or use `?` etc. This `SELECT * FROM nconten` doesn't have any placehoders to bind params to so you get the error. In this case it doens't matter much but `bindValue` would be a better choice as you don't really need to bind a reference of the $variable. `Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called` Because you have to pass the data into a function that does the binding and executing, there is no point using a reference. – ArtisticPhoenix Mar 12 '19 at 18:51
  • @ArtisticPhoenix I made the adjustments you recommended. $sql = 'SELECT * FROM nconten WHERE nid = :nid AND ntext = :ntext' '$stmt = self::$database->prepare($sql)'; '$stmt->bindValue(':id', $content_id, \PDO::PARAM_INT); '$stmt->bindValue(':nttext', $,_text, \PDO::PARAM_STR);' '$stmt->execute();' – Wes Henderson Mar 14 '19 at 11:05
  • However, I get a error 'Notice: Undefined variable: n_id and Notice: Undefined variable: n_content;' If I use bindParam I do not get an error, but I get an empty result. I am at a loss. Can you help me understand what I am doing incorrectly? I striped out all of the other code. If I do not use binding and just use '$sql = "SELECT ntext FROM nconten WHERE id = 2' I can fetch the result by while($record = $stmt->fetch(PDO::FETCH_ASSOC)) { return $record["ntext"]; not the bound $n_text – Wes Henderson Mar 14 '19 at 11:12
  • $content_id should be $n_id – Wes Henderson Mar 14 '19 at 11:13

0 Answers0