Jump to content

Recommended Posts

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

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.