2015-03-19 7 views
0

Этот код исправить ошибку: Фатальная ошибка: вызвать функцию-член prepare() для не-объекта в C: \ xampp \ htdocs \ kohana \ application \ контроллеры \ phactory2_test.php на линии 16
это пример из руководства Phactory: http://phactory.org/guide/#phpunit-exampleВызов функции-члена prepare() для не-объекта

<?php 
include_once('/simpletest/autorun.php'); 
require_once ('/Phactory/lib/Phactory.php'); 

/** 
    * This is the function we will test. 
    * It should retrieve a user from the db by id, 
    * and return that user's age. 
    * 
    * @param PDO $pdo 
    * @param int $user_id 
    * @return mixed The age of the user, or false if no user 
    */ 
function getUserAge($pdo, $user_id) 
{ 
    $stmt = $pdo->prepare("SELECT * FROM `users` WHERE `id` = ?"); 
    $stmt->execute(array($user_id)); 
    $user = $stmt->fetch(); 

    if(false === $user) { 
     return false; 
    } 

    return $user['age']; 
} 

class UserTest extends UnitTestCase 
{ 
    public static function setUpBeforeClass() 
    { 
     // create a db connection and tell Phactory to use it 
     $pdo = new PDO('mysql:host=127.0.0.1; dbname=testdb', 'root', ''); 
     Phactory::setConnection($pdo); 

     /** 
      * Normally you would not need to create a table here, and would use 
      * an existing table in your test database instead. 
      * For the sake of creating a self-contained example, we create 
      * the 'users' table here. 
      */ 
     $pdo->exec("CREATE TABLE `users` (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)"); 

     // reset any existing blueprints and empty any tables Phactory has used 
     Phactory::reset(); 

     // define default values for each user we will create 
     Phactory::define('user', array('name' => 'Test User $n', 'age' => 18)); 
    } 

    public static function tearDownAfterClass() 
    { 
     Phactory::reset(); 

     // since we created a table in this test, we must drop it as well 
     Phactory::getConnection()->exec("DROP TABLE `users`"); 
    } 

    public function testGetUserAge() 
    { 
     // test that getUserAge() returns false for a nonexistent user 
     $age = getUserAge(Phactory::getConnection(), 0); 
     $this->assertFalse($age); 

     // create 20 users, with ages from 1-20 
     $users = array(); 
     for($i = 1; $i <= 20; $i++) 
     { 
      // create a row in the db with age = $i, and store a Phactory_Row object 
      $users[] = Phactory::create('user', array('age' => $i)); 
     } 

     // test that getUserAge() returns the correct age for each user 
     foreach($users as $user) 
     { 
      // Phactory_Row provides getId() which returns the value of the PK column 
      $user_id = $user->getId(); 

      $age = getUserAge(Phactory::getConnection(), $user_id); 

      $this->assertEqual($user->age, $age); 
     } 
    } 
} 
?> 

Каковы возможные причины?
Спасибо

Edit: я узнал проблему, Phactory :: GetConnection() возвращает NULL по какой-то причине

+1

Включите все ваши взаимодействия с базой данных с помощью блоков try catch. Выполнение этого гарантирует, что вы сможете выйти из скрипта внутри улова, если это необходимо, но также даст вам возможность поймать ошибки и либо восстановить их, либо распечатать. попытка { // Подключение к базе данных или запросов здесь } поймать (PDOException $ е) { эхо $ e-> GetMessage(); } – Chris

ответ

1

Вы должны добавить bind_param, прежде чем выполнить подготовленное заявление.

$stmt = $pdo->prepare("SELECT * FROM `users` WHERE `id` = ?"); 
    $stmt->bind_param('i', $user_id); 
    $stmt->execute(); 

Это соединение MySQL. Для pdo вы можете добавить

print_r($stmt->errorInfo()); 

Чтобы узнать, в чем ваша проблема.

+1

'$ stmt-> execute (array ($ user_id));' <- Я думаю, вы упускаете эту строку – Rizier123