On Tue, 30 Apr 2002 08:15:17 -0400 (EDT), Mike Knichel wrote:
>I am a relatively inexperienced programmer(hobbiest).
>I need to do check for the existence of a student in a table. If he is
>there, get is id#, if not, insert him and get his id#. Id# is a primary
>key auto_increment field.
>
>So, say this is my sql select...
> SELECT id from students where name='$name';
>
>and that $name has a correct value in it.
>
>What would be the best way to do the select/insert-select for this?
I'm not sure it's the best way, but it's what I'd do, provided you don't
have to repeat the same action too often. Otherwise, I'd combine
prepare() and execute() calls.
my $student_id = $dbh->selectrow_array(<<"-1-", undef, $name)
SELECT id from students where name=?
-1-
|| do {
$dbh->do(<<'-2-', undef, $name);
INSERT INTO students (name) VALUES (?)
-2-
$dbh->{mysql_insertid};
};
--
Bart.