Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Populate PostgreSQL tables (See related posts)

This script in PHP populate with demo data tables Postgresql.
It insert serious registers automatically in a table.
Remove the primary key before run.

   1  
   2  <?php
   3  /** Rotina para popular tabela do PostgreSQL com massa de testes
   4    * Colaboração de Ribamar FS - http://ribafs.net - 14/03/2007
   5    * Requer remoção da chave primáia antes da execução.
   6    */ 
   7  ?>
   8  
   9  <html><head><title>Inserir Registros de Teste</title></head>
  10  <body bgcolor=''>
  11  <h2 align=center>Cadastrar Tabela do PostgreSQL com Massa de Testes</h2>
  12  <h3 align=center><font color=red>Remova chave primáia da tabela, antes de executar</font></h3>
  13  <h4 align=center>Observe que nem todos os tipos de dados foram contemplados, alguns ficarão como string</h4>
  14  
  15  <table align=center>
  16  <form method='POST' name=frmIns action='popula_table_pg.php'>
  17  
  18  <tr><td>Host</td><td><input type=text name='host' value='127.0.0.1'></td></tr>
  19  <tr><td>Banco</td><td><input type=text name='banco' value='cliente'></td></tr>
  20  <tr><td>Usuário</td><td><input type=text name='usuario' value='postgres'></td></tr>
  21  <tr><td>Senha</td><td><input type=text name='senha' value='postgres'></td></tr>
  22  <tr><td>Tabela</td><td><input type=text name='tabela' value='clientes'></td></tr>
  23  <tr><td>Registros</td><td><input type=text name='registros' value=5></td></tr>
  24  <tr><td></td><td><input type=submit name='popular' value='Popular'></td></tr>
  25  </form>
  26  </table>
  27  </body>
  28  </html>
  29  
  30  <?php
  31  if(isset($_POST['popular'])){
  32  	$host=$_POST['host'];
  33  	$banco=$_POST['banco'];
  34  	$usuario=$_POST['usuario'];
  35  	$senha=$_POST['senha'];
  36  	$tabela=$_POST['tabela'];
  37  	$registros=$_POST['registros'];
  38  
  39  	$conexao=pg_connect("host=$host user=$usuario password=$senha dbname=$banco port=5432");
  40  	if (!$conexao){
  41  		die('Erro ao conectar ao banco<br>'.pg_last_error($conexao));
  42  	}
  43  	$str="SELECT * FROM $tabela";
  44  	$consulta= pg_query($conexao,$str);
  45  	$nc=pg_num_fields($consulta);
  46  	$nr=pg_num_rows($consulta);
  47  
  48     $n='';//numericos (int, tinyint, smallint, bigint, etc)
  49     $r=''; //reais (float e double)
  50     $s="'";//strings
  51     $d=date('Y-m-d'); //datas
  52     $dt=date('Y-m-d H:i:s');//datatimes
  53     $o=''; //outros
  54  
  55     	$inscod .="INSERT INTO $tabela (";
  56     	for ($j = 0; $j < $nc; $j++) {
  57        $campo = pg_field_name($consulta, $j);
  58  		if ($j < $nc-1)	$inscod .= "$campo,";
  59       	else $inscod .= "$campo";
  60  	}
  61  	$inscod .= ")";	 
  62      $inscod .= " VALUES (";
  63  
  64     for ($j = 0; $j < $nc; $j++) {   
  65     $tam   = pg_field_size($consulta, $j);
  66     if($tam == -1) $tam=20; //Caso queira limitar os campos ao máximo de 20 posiçes
  67  		if ($j < $nc-1){ 
  68  			switch (pg_field_type($consulta, $j)){
  69  				case 'int4':
  70  					$n=str_pad($n,$tam,'12345679890');
  71  					$inscod .= "$n,";
  72  					break;
  73       			case 'float4':
  74  					$r=str_pad($r,$tam,'1234567890');
  75  					$inscod .= "$r,";
  76  					break;
  77  				case 'bpchar':
  78  				case 'varchar':
  79  					$s=str_pad($s,$tam,"abcdefghijklmnopqrstuvxyz");
  80  					$inscod .= "$s',";
  81  					break;
  82  				case 'date':
  83  		 		    $inscod .= "'$d',";
  84  					break;
  85  				case 'timestamp':
  86  					$inscod .= "'$dt',";
  87  					break;
  88  				case 'text':
  89  					$inscod .= "'$t'";
  90  					break;
  91  				default:
  92  					$o=str_pad($o,$tam,"abcdefghijklmnopqrstuvxyz");
  93  					$inscod .= "'$o',";
  94  					break;
  95  			}
  96       	}else{
  97       		switch (pg_field_type($consulta, $j)){
  98  				case 'int4':
  99  					$n=str_pad($n,$tam,'1234567890');
 100  					$inscod .= "$n";
 101  					break;
 102       			case 'float4':
 103  					$r=str_pad($r,$tam,'1234567890');
 104  					$inscod .= "$r";
 105  					break;
 106  				case 'bpchar':
 107  				case 'varchar':
 108  					$s=str_pad($s,$tam,"abcdefghijklmnopqrstuvxyz");
 109  					$inscod .= "$s'";
 110  					break;
 111  				case 'date':
 112  					$inscod .= "'$d'";
 113  					break;
 114  				case 'timestamp':
 115  					$inscod .= "'$dt'";
 116  					break;
 117  				case 'text':
 118  					$inscod .= "'$t'";
 119  					break;
 120  				default:
 121  					$o=str_pad($o,$tam,"abcdefghijklmnopqrstuvxyz");
 122  					$inscod .= "'$o'";
 123  					break;
 124       		}
 125       	}
 126       	
 127  	}
 128      $inscod .=");";	
 129  	
 130      for($r=1;$r<=$registros;$r++){	   
 131  		//echo  $inscod;
 132  	   	if(!pg_query($conexao,$inscod)) die ("Erro na inclusã<br>".pg_last_error($conexao));
 133      }	   
 134  }
 135  ?>
 136  

Comments on this post

EagleDog posts on Apr 22, 2007 at 19:24
Eu acho que otros poderiam usar seu code melhor se tudo fosse escrito em ingles. Ainda bem que leio portugues, mas creio que a maioria aqui apenas leiam ingles.

(I think that other's could use your code better if it was all written in English. It's good that I read Portuguese, but I think that the majority here only read English.)

Porem, gostei do que ta' fazendo!

You need to create an account or log in to post comments to this site.


Click here to browse all 5556 code snippets

Related Posts