Path: csiph.com!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!news.musoftware.de!wum.musoftware.de!fu-berlin.de!uni-berlin.de!not-for-mail From: "M. Strobel" Newsgroups: comp.lang.php Subject: Re: pgsql and exception Date: Mon, 14 May 2012 10:18:35 +0200 Lines: 81 Message-ID: References: <4fb0a891$0$1739$426a34cc@news.free.fr> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: quoted-printable X-Trace: news.uni-berlin.de TKVoa5FnTui18h9HpC3BwAYWgREyt29uvAJFmHoClSL2iWdgb2FN1DvxQh5z9KPbQ= User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20120421 Thunderbird/12.0 In-Reply-To: Xref: csiph.com comp.lang.php:6017 Am 14.05.2012 09:45, schrieb "=C3=81lvaro G. Vicario": > El 14/05/2012 8:39, Une B=C3=A9vue escribi=C3=B3/wrote: >> I have an INSERT generating an exception : >> ERROR: value too long for type character varying(30) >> >> this error comes from try out usinf command line. >> >> I'd like to print-out this error when using this database from php. >> >> Then, i did : >> >> $ret=3D$db->query($sql); >> try { >> while($row=3D$ret->fetch()){ // line 492 >> $rowid=3D$row['rowid']; >> } >> // do something >> } catch (Exception $e) { >> echo $e->getMessage()."
\n"; >> } >> >> or using : >> } catch (PDOException $e) { >> echo $e->getMessage()."
\n"; >> } >> >> From php i get : >> Fatal error: Call to a member function fetch() on a non-object in >> /Users/yt/Sites/landp_public/landp.php on line 492 >> >> line 492 being "while($row=3D$ret->fetch()){" >> >> obviously the best way is to avoid having a varchar column with a leng= th >> lower than 30. >=20 > This isn't a database error, it's a PHP error. The line where you defin= e $ret's > current value: >=20 > $ret=3D$db->query($sql); >=20 > ... failed. Such function should return a object but it didn't (probabl= y, because it > returned FALSE instead). >=20 > =C2=ABReturn Values: A query result resource on success or FALSE on fai= lure.=C2=BB >=20 > http://es.php.net/pg_query >=20 > Tips: >=20 > - Always do error checking when opening a DB connection and running a S= QL query: it's > way more likely to get an error there than when retrieving rows. >=20 > - You can inspect a variable with var_dump(), e.g.: >=20 > var_dump($ret); >=20 It is true you have to do error checking after every step, the query/exec= ute functions return a PDOStatement or FALSE. But: with PDO::ERRMODE_EXCEPTION PDO does it for you, just take care to h= ave every DB operation in a try block. One extra recommendation for the readers: you should decide on which level you write the try-catch: inside your db = helper functions, or in the top level script. The savings in code using try-catc= h will be more when writing one try block in your top level script. /Str.