tags:

views:

96

answers:

5

This may be rather noobish but I'm gonna ask anyhow. I have a class that inserts into my database. After the insert is finished, I would like to be able to test whether the insert was successful. Can someone tell me what a good way to do this may be?

I call the class like this:

foo = new Myclass('my params');

print_r($foo) returns an object. Again, all I am interested in is testing whether the insert was successful or not.

Thanks!

A: 

After doing the insert you can usually query the ID of the new row, have a look at the docs of the framework you are using (if any). Also, the insertion itself should return an error code or throw and exception if it failed. Again, this depends on the framework you are using.

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

n3rd
Sure, I could do that but there are A LOT of queries and it wouldn't be optimal I think. This is my framework. In the method, I am testing with mysql_affected_rows but I don't get that value back out of the object. Thanks for the link. :)
Funny but I just read something on unit testing. Never heard of it before until now.
A: 

$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;
}

} }

bumperbox
Thanks for this. Isn't there a way to return a true or false val instead of a string?
Hey bumper.. Thanks. Its a spinoff of adam's code which should work well.
A: 

The mysql_query() function returns true on a succesfull insert.

Did you write the class yourself? If so, you could have the insert(), or save() function (whatever you called it) return a boolean (true/false) so you can check whether the insert succeeded.

If you are using DB_DataObject it goes like this:

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

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 to 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 have MyClass set an error flag in the constructor, as the return value from mysql_db_query() you then check for in your code..

foo = new Myclass('my params');

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

hope this helps!

adam
Thanks Man! (Please enter at least 15 characters.)
A: 

You could just do $foo->affected_rows() Which on insert will be 1.

Jamie