Php object testing

It might be pretty noobish, but I'll ask anyway. I have a class that is being inserted into my database. After the insert is finished, I would like to check if the insert was successful. Can anyone tell me what a good way to do this might be?

I am calling the class like this:

foo = new Myclass('my params');

      

print_r($foo)

returns an object. Again, all I'm interested in is checking if the insert was successful or not.

+1


a source to share


5 answers


From http://uk3.php.net/manual/en/function.mysql-db-query.php

 mysql_db_query() selects a database, and executes a query on it. 

      

Returns a positive MySQL result resource on the query result, or FALSE on error. The function also returns TRUE / FALSE for INSERT / UPDATE / DELETE queries to indicate success / failure.



So, you can set MyClass to an error flag in the constructor as the return value from mysql_db_query (), which you then check in your code.

foo = new Myclass('my params');

if (foo->error) {
 // error occured
} else {
 // all is good
}

      

hope this helps!

+1


a source


After doing the insert, you can usually ask for a newline id, take a look at the documents of the structure being used (if any). In addition, the insertion itself must return an error code or throw and an exception if it fails. Again, this depends on the structure used.



Depending on how thorough you want your testing to be, you should also take a look at phpunit .

0


a source


$foo = new Myclass('my params');
if ($foo->sqlerror) {
  echo "Error Message: ".$foo->sqlerrmsg;
}


class MyClass {
  var $sqlerror = false;
  var $sqlerrmsg = null;

  // constructor
  function MyClass($parms) {
    $res = mysql_query($sql);

    if (mysql_error()) {
      $this->sqlerrmsg = mysql_error();
      $this->sqlerror = true;
    }
  }
}

      

0


a source


Mysql_query () function returns true in succesfull insert.

Do you write the class yourself? If so, you can use the insert () or save () function (whatever you named) return a boolean (true / false) so you can check if the insert succeeded.

If you are using DB_DataObject it looks like this:

$foo = new ClassX();
$foo->name = 'Name';
if($foo->insert()) {
  //insert succeeded
} else {
  //insert failed
}

      

0


a source


You can just do $ foo-> affected_rows () Which will be 1 in the insert.

0


a source







All Articles