colombian Posted May 28, 2008 Share Posted May 28, 2008 I have this class, and with 2 columns and no implicit id, it works fine. However if the MySQL table has column that will by set to auto_increment. In procedural code, that ID is implied and you don't need to specify it in the SQL statement. However, I am getting an error with the class. Maybe the code will make it more clear: <?php class Name { public $Ages; public $Names; public function __construct ($name, $age) { $this->Ages = $age; $this->Names = $name; } public function add_name() { $query = "INSERT INTO name_age VALUES ('$this->Names', $this->Ages)"; $result = mysql_query($query); if (mysql_affected_rows() > 0) { echo "Success!"; } else { echo "<p> Failed</p>" . mysql_error() . "</p> <a href=\"staff.php\"> Return to main page </a>"; } } } $name1 = new Name('John', 28); $name1->add_name(); ?> The code works fine for a two column table with those values - but I am having trouble passing the auto_increment id column... Any help would be greatly appreciated. Thanks Quote Link to comment https://forums.phpfreaks.com/topic/107658-solved-passing-an-id-auto_increment-through-a-class-function/ Share on other sites More sharing options...
craygo Posted May 28, 2008 Share Posted May 28, 2008 If you don't list the fields you want to insert data to, mysql will start from the first and work its way forward. so if your id field is the first field and you have 2 other fields for a total of 3, and you try to insert just 2 fields, mysql will try to insert the first value into the first field. So in your case it is trying to insert the name into the id field. just try and list the fields and values rather than just the values. $query = "INSERT INTO name_age (`namefield`, `agesfield`) VALUES ('$this->Names', $this->Ages)"; Either that or include a null value for the id field $query = "INSERT INTO name_age VALUES ('', '$this->Names', $this->Ages)"; Ray Quote Link to comment https://forums.phpfreaks.com/topic/107658-solved-passing-an-id-auto_increment-through-a-class-function/#findComment-551876 Share on other sites More sharing options...
colombian Posted May 28, 2008 Author Share Posted May 28, 2008 Many thanks... I feel very silly - I knew better than that, I started thinking too much, thinking it had something to do with the class. Anyhow - thanks a lot. Quote Link to comment https://forums.phpfreaks.com/topic/107658-solved-passing-an-id-auto_increment-through-a-class-function/#findComment-551986 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.