php - simple db query function -


I want to be able to call a query function and based on the result they are put into an object that I I can call out the program. I have it:

  & lt ;? Php function query ($ sql) {global $ r; $ Database = "theater"; $ Db_conn = pg_connect ("host = localhost port = 5432 dbname = $ database user = postgrade"); If (! $ Db_conn):? & Gt; & Lt; H1 & gt; Failed to connect to database postgres & lt ;? Php echo $ databases ;? & Gt; & Lt; / H1> & Lt ;? Quit Php; end if; $ Ep = pg_query ($ db_conn, $ sql); While ($ r = pg_fetch_object ($ ep)) {} pg_free_result ($ ep); Pg_close ($ db_conn); } Query (choose 'from test'); Echo $ r- & gt; Fname;  

I do not want to hardcode the name of any column in the function. Then fname is an example but it would be dynamic based on the query. I have a loop for a while but it is not sure what to put in it.

The value returned by the function is already an object, hence no need for loop through the results Not just return it:

Return pg_fetch_object ($ ep);

Then use the returned result without reference to this weird global variable $ r .

  $ r = query (select 'from test *) *; Echo $ r- & gt; Fname;  

In addition, there is no need to free up the resource with pg_free_result . It is automatically free at the end of the scope (in this case the current task is). Calling pg_close can also slow down your script, because the next time you call the function, the connection will be rebuilt. I suggest storage connections in the local static variable and do not close it - it will close automatically.

  function query ($ sql) {$ database = "theater"; Stable $ db_conn; If (! $ Db_conn) {$ db_conn = pg_connect ("host = localhost port = 5432 dbname = $ database user = postgrad"); } ...  

As a long-term solution, I recommend researching object-relational mapping and available ORM-ish tools (i.e., or an existing one implementation). Of the active record pattern).


Comments