Você está na página 1de 8

Barattalo » 10 PHP usefull functions for MySQL stuff

● Skip

Barattalo
● Skip

code snippets, classes and other stuff for developers


search...

Jan ● Categories
25 ❍ Asp
2010

10 PHP usefull functions for MySQL stuff ❍ Css


Category: MySql, Php — admin @ 3:44 pm

❍ Facebook Connect
Here is my personal collection of 10 php function that I always
include in my database function library.
I think they are very usefull and I’d like to share with you. ❍ Google Maps

Here are the mysqli versions of the functions. (NEW)


❍ Html
FUNCTION 1: CONNECT TO A DB
Connect function. I know, everybody already has this function in its library. But I have to add it. The user data
❍ Java Script
are stored in constants, so you don’t have to specify any variable when you call the connect function:

❍ MsSQL
1 function connectDb() {

2 // connect and set the ❍ MySql

3 // working db
Php
4 if (mysql_connect( DBHOST, DBUSER, DBPWD ) && mysql_select_db( DBNAME ))

return true; else return false;


Spiders & webbots
5 }

FUNCTION 2: RUN SCRIPT FOR REPAIR AND OPTIMIZE TABLES


This function will scan all the tables of a db and run repair and optimize for each table. Usefull, for example, ● Blogroll
when you want to run a fix on the db every night calling it through a cron job on the server.
❍ Date Concerti

01 function fixTables($dbname) { ❍ Fabrizio La Scimmia

02 // search for all the tables of


Il Bloggatore
03 // a db and run repair and optimize

04 // note: this can take a lot of time


❍ Ku ku photos
05 // if you have big/many tables.

06 $result = mysql_list_tables($dbname) or die(mysql_error());


❍ Me on Rockit
07 while ($row = mysql_fetch_row($result)) {

08 mysql_query("REPAIR TABLE $row[0]"); ❍ Rockit.it

09 mysql_query("OPTIMIZE TABLE $row[0]");

10 } ❍ Twirl.it

11 }

EXAMPLE: So, make a php file cronfixdb.php with this code and call everynight to fix your tables:
● Print and study
❍ Building website for iphone

http://www.barattalo.it/2010/01/25/10-php-usefull-functions-for-mysql-stuff/ (1 of 8)15/02/2010 07:11:07 p.m.


Barattalo » 10 PHP usefull functions for MySQL stuff

1 <? ❍ Seo staff in Italian


2 include("db.lib.php"); //file with the Connect and fixTables function

3 if connectDb() fixTables(DB);

4 ?> ● Things to test


❍ Building website for iphone

FUNCTION 3: CONVERT A RECORDSET TO HTML TABLE


This code receive a record set coming from a mysql_query output and print it in a simple html table, quick
❍ Counter with Google Analytics
and usefull. This script could be really improved with some css (and, eventually pagination… can you?)

❍ htaccess mp3
01 function getHtmlTable($result){

02 // receive a record set and print ❍ Open inviter

03 // it into an html table

04 $out = '<table>';
● Tags
05 for($i = 0; $i < mysql_num_fields($result); $i++){
❍ Php
06 $aux = mysql_field_name($result, $i);

07 $out .= "<th>".$aux."</th>"; ❍ Java Script


08 }

09 while ($linea = mysql_fetch_array($result, MYSQL_ASSOC)) { ❍ Spiders & webbots

10 $out .= "<tr>";
❍ MySql
11 foreach ($linea as $valor_col) $out .= '<td>'.$valor_col.'</td>';

12 $out .= "</tr>";
❍ Regular expression
13 }

14 $out .= "</table>"; ❍ Asp


15 return $out;

16 } ❍ Web bot

EXAMPLE: Use this code in this way: ❍ Google Maps

❍ Google Maps
1 <?

2 include("db.lib.php");
❍ curl
3 if connectDb() {

4 $rs = mysql_query("select * from users limit 0,100");


❍ Mini Bots Class
5 echo getHtmlTable($rs);

6 } ❍ Google

7 ?>
❍ Php
FUNCTION 4: MAKE A STRING WITH FIELD NAMES
Found the fields-name of a table and return them in a comma-separeted string. This is usefull to automatic
❍ spiders
build queries in some applications. The $excepts parameter can be used to skip some field in the output
string:
❍ Spider

1 function getCommaFields( $table, $excepts = ""){

2 // get a string with the names of the fields of the $table,

http://www.barattalo.it/2010/01/25/10-php-usefull-functions-for-mysql-stuff/ (2 of 8)15/02/2010 07:11:07 p.m.


Barattalo » 10 PHP usefull functions for MySQL stuff

3 // except the onews listed in '$excepts' param

4 $out = "";

5 $result = mysql_query( "SHOW COLUMNS FROM `$table`" );

6 while($row = mysql_fetch_array($result)) if ( !stristr(",".$row['Field']."," ,


$excepts) ) $out.= ($out?",":"").$row['Field'];

7 return $out ;

8 }

FUNCTION 5: MAKE A STRING WITH COMMA SEPARATED VALUES


Run a query and get all the first value of each row into a comma separeted string. Usefull for old mysql
version db that do not support sub select. But also for other things:

1 function getCommaValues($sql) {

2 // execute a $sql query and return

3 // all the first value of the rows in

4 // a comma separated string

5 $out = "";

6 $rs = mysql_query($sql) or die(mysql_error().$sql);

7 while($r=mysql_fetch_row($rs)) $out.=($out?",":"").$r[0];

8 return $out;

9 }

EXAMPLE: find items for a subselect statement:

1 ...

2 $ids = getCommaValues("select id from users where status=-1");

3 $sql = "delete from users where id in (".$ids.")";

4 if ($ids) mysql_query($sql);

5 // note since mysql 5 you can use sub select in delete statements.

6 ...

FUNCTION 6: GET VALUES OF A ENUM/SET FIELD


I’ve also dedicated a post for this function, I think this script, even if isn’t so nice (it could be rewritten with
regular expressions) it’s very usefull if you use ENUM fields in your tables.

01 function getEnumSetValues( $table , $field ){

02 // get an array of the allowed values

03 // of the enum or set $field of $table

04 $query = "SHOW COLUMNS FROM `$table` LIKE '$field'";

05 $result = mysql_query( $query ) or die( 'error getting enum field ' .


mysql_error() );

06 $row = mysql_fetch_array($result);

07 if(stripos(".".$row[1],"enum(") > 0) $row[1]=str_replace("enum('","",$row[1]);

08 else $row[1]=str_replace("set('","",$row[1]);

http://www.barattalo.it/2010/01/25/10-php-usefull-functions-for-mysql-stuff/ (3 of 8)15/02/2010 07:11:07 p.m.


Barattalo » 10 PHP usefull functions for MySQL stuff

09 $row[1]=str_replace("','","\n",$row[1]);

10 $row[1]=str_replace("')","",$row[1]);

11 $ar = split("\n",$row[1]);

12 for ($i=0;$i<count($ar);$i++) $arOut[str_replace("''","'",$ar[$i])]=str_replace


("''","'",$ar[$i]);

13 return $arOut ;

14 }

FUNCTION 7: RUN A QUERY AND GET THE FIRST VALUE


This function and the following one are the most used functions of this collection (after ConnectDb), since we
always need to extract a singular value or (next function) singular row.

01 function getScalar($sql,$def="") {

02 // execute a $sql query and return the first

03 // value, or, if none, the $def value

04 $rs = mysql_query($sql) or die(mysql_error().$sql);

05 if (mysql_num_rows($rs)) {

06 $r = mysql_fetch_row($rs);

07 mysql_free_result($rs);

08 return $r[0];

09 }

10 return $def;

11 }

EXAMPLE:

1 echo getScalar("select count(*) from users"); // 23

FUNCTION 8: RUN A QUERY AND GET FIRST ROW

01 function getRow($sql) {

02 // execute a $sql query and return the first

03 // row, or, if none, return an empty string

04 $rs = mysql_query($sql) or die(mysql_error().$sql);

05 if (mysql_num_rows($rs)) {

06 $r = mysql_fetch_array($rs);

07 mysql_free_result($rs);

08 return $r;

09 }

10 mysql_free_result($rs);

11 return "";

12 }

EXAMPLE:
http://www.barattalo.it/2010/01/25/10-php-usefull-functions-for-mysql-stuff/ (4 of 8)15/02/2010 07:11:07 p.m.
Barattalo » 10 PHP usefull functions for MySQL stuff

1 print_r( getRow("select * from users limit 0,1") ); // Array (...);

FUNCTION 9: DUPLICATE A SPECIFIED ROW


This function use the getCommaFields described above and make an insert in a table duplicating a particular
row defined by the primary id field and value specified in the parameters.
It’s usefull to add “duplicate” functionality in your administrator backend software.

1 function duplicateRow($table,$primaryField,$primaryIDvalue) {

2 // duplicate one record in a table

3 // and return the id

4 $fields = getCommaFields($table,$primaryField);

5 $sql = "insert into $table ($fields) select $fields from $table where
$primaryField='".mysql_real_escape($primaryIDvalue)."' limit 0,1";

6 mysql_query($sql) or die(mysql_error().$sql);

7 return mysql_insert_id();

8 }

EXAMPLE:

1 // duplicate the user with id_user=12 and get the new user id:

2 $newuser = duplicateRow("users","id_user","12");

FUNCTION 10: CONVERT A RECORDSET TO JSON AND CSV


This function converts a record set returned by a mysql_query function to a JSON encoded string or to a CSV
string.
This script could also be improved by adding some configuration for the CSV export.

01 function convertResult($rs, $type, $jsonmain="") {

02 // receive a recordset and convert it to csv

03 // or to json based on "type" parameter.

04 $jsonArray = array();

05 $csvString = "";

06 $csvcolumns = "";

07 $count = 0;

08 while($r = mysql_fetch_row($rs)) {

09 for($k = 0; $k < count($r); $k++) {

10 $jsonArray[$count][mysql_field_name($rs, $k)] = $r[$k];

11 $csvString.=",\"".$r[$k]."\"";

12 }

13 if (!$csvcolumns) for($k = 0; $k < count($r); $k++) $csvcolumns.=


($csvcolumns?",":"").mysql_field_name($rs, $k);

14 $csvString.="\n";

15 $count++;

http://www.barattalo.it/2010/01/25/10-php-usefull-functions-for-mysql-stuff/ (5 of 8)15/02/2010 07:11:07 p.m.


Barattalo » 10 PHP usefull functions for MySQL stuff

16 }

17 $jsondata = "{\"$jsonmain\":".json_encode($jsonArray)."}";

18 $csvdata = str_replace("\n,","\n",$csvcolumns."\n".$csvString);

19 return ($type=="csv"?$csvdata:$jsondata);

20 }

EXAMPLE:

1 //... connect ...

2 $sql = "select * from users limit 0,10";

3 $rs = mysql_query($sql);

4 $jsonString = convertResult($rs,"json","users"); // json encoded string

5 $csvString = convertResult($rs,"csv"); // scv output

Related posts:

1. 10 PHP usefull functions for MySQLi stuff (mysql improved)


2. PHP to get enum/set values from mysql field
3. MYSQL add counter in a query
4. Execute Scalar and Execute Row for Php
5. PHP function to fix collation on database fields of MySQL

Tags: csv, function, json, MySql, mysql_fetch_array, mysql_query, optimize, Php, Recordset, repair, snippets

Comments (6)

6 Responses to “10 PHP usefull functions for MySQL stuff”

1.

Stfr says:
January 26th, 2010 12:27 pm

Using mysql_query() is obsolete.


Use PDO, or mysqli ..but don’t use mysql…

2.

admin says:
January 26th, 2010 12:49 pm

http://www.barattalo.it/2010/01/25/10-php-usefull-functions-for-mysql-stuff/ (6 of 8)15/02/2010 07:11:07 p.m.


Barattalo » 10 PHP usefull functions for MySQL stuff

Mmm ok, in the future I will use mysqli, that’s better and I have to study it.
But why PDO? PDO should be used when you plan to change db, or when you have
different dbs to connect to.

3.

Stfr says:
January 26th, 2010 1:27 pm

Sure, but you can use it in order to create ORM or just in order to use Object syntax for
your Db.
It depends on the use you do and the importance of the project.

4.
Notable Tech Posts – 2010.01.31 | The Life of Lew Ayotte says:
February 1st, 2010 2:32 pm

[...] 10 PHP useful functions for MySQL stuff [...]

5.

The Same says:


February 11th, 2010 5:01 pm

Function 4 in MySql is the same as:

SELECT GROUP_CONCAT(”,COLUMN_NAME) as campos


FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA=’$BBDD’ AND TABLE_NAME=’$TABLE’ AND
COLUMN_NAME NOT IN (’$EXPECTS’)
GROUP BY TABLE_NAME;

6.
10 PHP usefull functions for MySQL stuff | DbRunas says:
February 11th, 2010 9:50 pm

[...] http://www.barattalo.it/2010/01/25/10-php-usefull-functions-for-mysql-stuff/ AKPC_IDS


+= "3371,"; [...]

Leave a Reply

Name (required)

Mail (will not be published) (required)

http://www.barattalo.it/2010/01/25/10-php-usefull-functions-for-mysql-stuff/ (7 of 8)15/02/2010 07:11:07 p.m.


Barattalo » 10 PHP usefull functions for MySQL stuff

Website

Submit Comment

Powered by WordPress and Stardust Created by Tommaso Baldovino top

http://www.barattalo.it/2010/01/25/10-php-usefull-functions-for-mysql-stuff/ (8 of 8)15/02/2010 07:11:07 p.m.

Você também pode gostar