Welcome Guest, Not a member yet? Register   Sign In
[solved]Getting a Primary Key after inserting into a table?
#1

[eluser]brucebat[/eluser]
Hello,

Im trying to get a PK so I can use it for my Foreign Key in another table.

Would it be correct to use the get_where() function for this?

Heres my code.

Code:
//Patient segment
            $patient = array
            (
                'patient_age' =>$this->input->post ('patient_age'),
                'patient_height' => $this->input->post ('patient_height'),
                'patient_weight' => $this->input->post ('patient_weight'),
                'patient_gender' => $this->input->post ('patient_gender')
            );
        
            $insertpatient = $this->db->insert ('patient', $patient);
//Get PK for FK in next table
$patientfk = $this->db->get_where ('patient', array('patient_height' == $this->input->post('patient_height') && 'patient_weight' == $this->input->post('patient_weight')));

Im currently getting this error:

Quote:A Database Error Occurred

Error Number: 1054

Unknown column '0' in 'where clause'

SELECT * FROM (`patient`) WHERE `0` = 0

Filename: C:\xampp\htdocs\midas\system\database\DB_driver.php

Line Number: 330

I don't understand how it gets Column '0'?

Would it be because it does not specify correctly the column name?
#2

[eluser]danmontgomery[/eluser]
$id = $this->db->insert_id();
#3

[eluser]brucebat[/eluser]
Thankyou,

So how does it know what value to insert?

What parameters do I give the function. Could you give me an example?
#4

[eluser]defectivereject[/eluser]
not sure where you're trying to get the primary key in your code
BUT AFTER
Code:
$insertpatient = $this->db->insert ('patient', $patient);

putting $this->db->insert_id();
returns the ID of the row it just inserted.
so instead of putting

Code:
$this->db->insert_id();
you could put
Code:
$p_id = $this->db->insert_id();

then $p_id is set as the ID of the last insert ID in the patient table. and can be used as the value for your next table
Code:
$patient2 = array
            (
                'patient' =>$p_id,
                'patient_whatNowr' => $this->input->post ('patient_whatNow')
            );
        
            $insertpatient = $this->db->insert ('patient2', $patient2);
#5

[eluser]Mirge[/eluser]
If you had a table like:

Code:
CREATE TABLE test (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL,
patient_name VARCHAR(50) NOT NULL,
patient_weight INT UNSIGNED NOT NULL,
...rest of your fields here...
);

id would be your primary key.

Code:
$result = $this->db->insert("....");
$id = $this->db->insert_id();

echo "The primary key (id) for the record I just inserted is $id";

See: http://ellislab.com/codeigniter/user-gui...lpers.html
#6

[eluser]brucebat[/eluser]
Wow that is too easy to believe.

Thanks for the help.




Theme © iAndrew 2016 - Forum software by © MyBB