|
Posted by Rik Wasmus on 01/02/08 01:05
On Wed, 02 Jan 2008 01:50:20 +0100, Aaron Gray <ang.usenet@gmail.com> =
wrote:
> I have a MySQL table of pages each with a 'title' and 'page' fields.
>
> How do I do either an UPDATE if the pages 'title' exists or an INSERT =
if =
> it
> does not ?
>
> The code I have written does not seem to do the job correctly.
>
> $result =3D mysql_query( "SELECT page FROM pages WHERE title =3D '=
" . =
> $title
> . "';");
>
> $row =3D mysql_fetch_array( $result, MYSQL_ASSOC);
>
> if ( isset( $row["title"]) && $row[title] =3D=3D $title)
> {
> $result =3D mysql_query( "UPDATE pages SET page =3D '". $page =
.. "' =
> WHERE
> title =3D '" .$title . "';");
> if ($result)
> mysql_query( "COMMIT;");
> }
> else
> {
> $result =3D mysql_query( "INSERT INTO pages SET title =3D'" . =
$title =
> .
> "', page =3D '" . $page . "';");
> if ($result)
> mysql_query( "COMMIT;");
> };
>
> This code is buggy and doing an insert rather than an update. How woul=
d =
> you
> approach this task ?
It could be done with one easy query, look into ON DUPLICATE KEY UPDATE =
=
syntax, ask in comp.databases.mysql
-- =
Rik Wasmus
Navigation:
[Reply to this message]
|