Aplicativos em PHP/Integração do PHP com SGBDs/MySQL

Origem: Wikilivros, livros abertos por um mundo aberto.

Conectar ao MySQL


Usaremos:

banco - cliente

create table clientes(id int primary key auto_increment, nome char(45), data date);
INSERT INTO `clientes` VALUES (1, 'Jorge da Cunha', '2007-01-12');
INSERT INTO `clientes` VALUES (2, 'Jorge da Cunha', '2007-01-12');
INSERT INTO `clientes` VALUES (3, 'Jorge da Cunha', '2007-01-12');
INSERT INTO `clientes` VALUES (4, 'Jorge da Cunha', '2007-01-12');
INSERT INTO `clientes` VALUES (5, 'Jorge da Cunha', '2007-01-12');
INSERT INTO `clientes` VALUES (6, 'Jorge da Cunha', '2007-01-12');
INSERT INTO `clientes` VALUES (7, 'Jorge da Cunha', '2007-01-12');
INSERT INTO `clientes` VALUES (8, 'Jorge da Cunha', '2007-01-12');
INSERT INTO `clientes` VALUES (9, 'Jorge da Cunha', '2007-01-12');
INSERT INTO `clientes` VALUES (10, 'João Brito10', '2007-01-12');
INSERT INTO `clientes` VALUES (11, 'João Brito11', '2007-01-13');
INSERT INTO `clientes` VALUES (12, 'Jorge da Cunha', '2007-01-12');
INSERT INTO `clientes` VALUES (13, 'Jorge da Cunha', '2007-01-12');
INSERT INTO `clientes` VALUES (14, 'Jorge da Cunha', '2007-01-12');

Recomendações:

- Usar sempre os mesmos nomes de variáveis para mesmas funções. Exemplo: $link para receber a conexão.
- Usar sempre as mesmas mensagens de erro para certos erros. Exemplo: 
  mysql_query... 'Erro na consulta: ' . mysql_error() não esquecer de passar a funãoo do MySQL que retorna o erro



$link = mysql_connect('localhost', 'root', '');
if (!$link) {
    die('Erro ao conectar conectar: ' . mysql_error());
}


Fechar a Conexão

print "<h2>FECHAR A CONEXÃO COM O MYSQL</h2>";
mysql_close($link);


Selecionar um Banco após a Conexão

print "<h2>SELECIONAR BANCO APÓS CONEXÃO</h2>";
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
    die('Erro ao conectar conectar : ' . mysql_error());
}else{
	if(!$db_selected = mysql_select_db('cliente', $link))  die ('Erro ao selecionar o banco cliente : ' . mysql_error());
}


Executar Consulta SQL

print "<h2>EXECUTAR CONSULTA(Qualquer consulta SQL)</h2>";
$result = mysql_query('SELECT * FROM clientes',$link); //se $link não for especificado, será usado o ltimo aberto
if (!$result) {
    die('Erro na consulta: ' . mysql_error());
}


Mover Ponteiro para um Registro Específico

print "<h2>MOVER PARA UM REGISTRO ESPECÍFICO</h2>";
$query = 'SELECT nome, data FROM clientes';
$result = mysql_query($query,$link);
if (!$result) {
    die('Erro na consulta: ' . mysql_error());
}
/* obter as linhas (registros) em ordem reversa */
for ($i = mysql_num_rows($result) - 1; $i <= 0; $i--) {
    if (!mysql_data_seek($result, $i)) {
        echo "Não foi possí­vel mover para a linha $i: " . mysql_error() . "\n";
        continue;
    }

    if (!($row = mysql_fetch_assoc($result))) {
        continue;
    }

    echo $row['nome'] . ' ' . $row['data'] . "<br />\n";
}
//mysql_free_result($result);


Retornar Todos os Registos em Forma de Array

print "<h2>RETORNAR TODOS OS REGISTROS COMO ARRAY</h2>";
mysql_fetch_array($result, MYSQL_BOTH); // Retorna todos os registros como array numérico e nomes

$result = mysql_query("SELECT id, nome FROM clientes");

while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
    printf ("ID: %s  Nome: %s", $row[0], $row["nome"].'<br>');
}


Total de Registros

print "<h2>TOTAL DE REGISTROS</h2>";
$result = mysql_query("SELECT * FROM clientes", $link);
$num_rows = mysql_num_rows($result);

echo "$num_rows registros<br>";
	

<h2>Receber Registros Afetados por Consulta</h2>

<pre>
print "<h2>REGISTROS AFETADOS (INSERT, DELETE E UPDATE)</h2>";
mysql_query('DELETE FROM clientes WHERE id < 10');
printf("Registros excluídos: %d\n", mysql_affected_rows());

/* Com uma cláusula WHERE que nunca é verdadeira isso deve retornar 0 */
mysql_query('DELETE FROM mytable WHERE 0');
printf("Registros excluí­dos: %d\n", mysql_affected_rows());


Criar Banco de Dados

print "<h2>CRIAR BANCO DE DADOS</h2>";
$sql = 'CREATE DATABASE cliente2';
if (mysql_query($sql, $link)) {
    echo "O banco de dados cliente2 foi criado<br>";
} else {
    echo 'Erro criando o banco de dados: ' . mysql_error() . "<br>";
}


Nomes dos Bancos de Dados

print "<h2>NOMES DOS BD</h2>";
$db_list = mysql_list_dbs($link);

$i = 0;
$cnt = mysql_num_rows($db_list);
while ($i < $cnt) {
    echo mysql_db_name($db_list, $i) . "<br>";
    $i++;
}


Excluir Banco

print "<h2>EXCLUIR BANCO</h2>";
$sql = 'DROP DATABASE cliente2';
if (mysql_query($sql, $link)) {
    echo "O banco de dados foi excluído com sucesso<br>";
} else {
    echo 'Erro ao excluir o banco de dados: ' . mysql_error() . "<br>";
}
<pre>


<h2>Retornar Número do Erro</h2>

<pre>
print "<h2>MYSQL_ERRNO</h2>";
if (!mysql_select_db("naoexistentebd", $link)) {
    echo mysql_errno($link) . ": " . mysql_error($link). "<br>";
}

Informações sobre os Campos

print "<h2>INFORMAÃÇÕES SOBRE CAMPOS</h2>";
$i = 0;
while ($i < mysql_num_fields($result)) {
    echo "Informação para a coluna $i:<br><br>";
    $meta = mysql_fetch_field($result, $i);
    if (!$meta) {
        echo "Sem informação disponível<br>";
    }
    echo "<pre>
blob:         $meta->blob
max_length:   $meta->max_length
multiple_key: $meta->multiple_key
name:         $meta->name
not_null:     $meta->not_null
numeric:      $meta->numeric
primary_key:  $meta->primary_key
table:        $meta->table
type:         $meta->type
default:      $meta->def
unique_key:   $meta->unique_key
unsigned:     $meta->unsigned
zerofill:     $meta->zerofill

";

   $i++;

}


Retornar um Registro em Forma de Array de Campos

print "<h2>RETORNAR UM REGISTRO COM ARRAY DE CAMPOS</h2>";
$result = mysql_query("SELECT id,nome FROM clientes WHERE id = '12'");
if (!$result) {
    echo 'Erro na consulta: ' . mysql_error();
    exit;
}
$row = mysql_fetch_row($result);

echo $row[0]; // 42
echo $row[1]; // o valor do email


Tamanho de Campos

print "<h2>TAMANHO DE CAMPOS</h2>";
$result = mysql_query("SELECT id,nome FROM clientes WHERE id = '42'");
if (!$result) {
    echo 'Erro na consulta: ' . mysql_error();
    exit;
}

// Receberão tamanho do campo id como especificado no banco
// schema. 
$length = mysql_field_len($result, 0);
echo $length;


Nomes de Campos

print "<h2>NOMES DE CAMPOS</h2>";
$res = mysql_query('select * from clientes', $link);

echo mysql_field_name($res, 0) . "<br>";
echo mysql_field_name($res, 2);


Nome de Tabela

print "<h2>NOME DE TABELA</h2>";
$table = mysql_field_table($result, $nomedeumcampodatabela);
echo $table; // people


Tipos de Dados dos Campos

print "<h2>TIPO DE DADOS DE CAMPO</h2>";
$result = mysql_query("SELECT * FROM clientes");
$fields = mysql_num_fields($result);
$rows   = mysql_num_rows($result);
$table  = mysql_field_table($result, 0);
echo "Sua tabela '" . $table . "' tem " . $fields . " campos e " . $rows . " registros<br>";
echo "A tabela tem os seguintes campos:<br>";
for ($i=0; $i < $fields; $i++) {
    $name  = mysql_field_name($result, $i);    
    $type  = mysql_field_type($result, $i);
    $len   = mysql_field_len($result, $i);
    $flags = mysql_field_flags($result, $i);
    echo $name . " " . $type . "  " . $len . " " . $flags . "<br>";
}


ID do Insert

print "<h2>RECEBENDO ID GERADO POR INSERT</h2>";
mysql_query("INSERT INTO clientes (nome) values ('Jorge da Cunha')");
printf("O ltimo registro inserido tem id %d<br>", mysql_insert_id());


Lista de Campos

print "<h2>LISTAR BANCOS DO MYSQL</h2>";
$db_list = mysql_list_dbs($link);

while ($row = mysql_fetch_object($db_list)) {
     echo $row->Database . "<br>";
}


Lista de Campos de Tabela

print "<h2>LISTAR CAMPOS DE TABELA</h2>";
while ($row = mysql_fetch_assoc($result)) {
    echo $row["id"].'-';
    echo $row["nome"].'-';
    echo $row["data"]."<br>";
}


Lista de Tabelas de um Banco

print "<h2>LISTAR TABELAS DE BANCO</h2>";
$sql = "SHOW TABLES FROM cliente";
$result = mysql_query($sql);

if (!$result) {
    echo "Erro no banco, não pode listas as tabelas<br>";
    echo 'Erro no MySQL: ' . mysql_error();
    exit;
}

while ($row = mysql_fetch_row($result)) {
    echo "Tabela: {$row[0]}<br>";
}


Número de Campos

print "<h2>NÚMERO DE CAMPOS</h2>";
$result = mysql_query("SELECT id,nome FROM clientes WHERE id = '42'");
if (!$result) {
    echo 'Erro na consulta: ' . mysql_error();
    exit;
}

/* retorna 2 porque id,nome === 2 campos */
echo mysql_num_fields($result);


Nome de Tabela

print "<h2>NOME DE TABELA</h2>";
mysql_connect("localhost", "root", "");
$result = mysql_list_tables("cliente");

for ($i = 0; $i < mysql_num_rows($result); $i++) {
    echo "Tabela: ", mysql_tablename($result, $i), "<br>";
}


<h2>Automaticamente instalar uma tabela no MySQL com PHP</h2>

<pre>
$table_def = "id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,";
$table_def .= "student_id INT(11) NOT NULL,";
$table_def .= "f_name TINYTEXT NOT NULL,";
$table_def .= "l_name TINYTEXT NOT NULL,";
$table_def .= "supervisor TINYTEXT NOT NULL,";
$table_def .= "building TINYTEXT NOT NULL,";
$table_def .= "email TINYTEXT NOT NULL,";
$table_def .= "score SMALLINT(6) NULL,";
$table_def .= "stamp DATETIME NOT NULL,";
$table_def .= "UNIQUE KEY id (id)";

if (!@mysql_query ("CREATE TABLE $tablename ($table_def)")) {
echo "The database table, '$tablename', could not be created.";
} else {
echo "Successfully created the '$tablename' table.";
} 


Teste se tabela existe no MySQL

function table_exists ($table, $db) {
	$tables = mysql_list_tables ($db);
	while (list ($temp) = mysql_fetch_array ($tables)) {
		if ($temp == $table) {
			return TRUE;
		}
	}
	return FALSE;
}

/** How to use it **/
if (table_exists(test_table, my_database)) {
	echo"Yes the table is there.";
} 
/*
akxter, http://www.oxyscripts.com/itemdisplay.php?id=1003&code=yes

And a shorter way. In the above example mysql_list_tables is deprecated in favor of mysql_query().
*/

// here is a much more elegant method to check if a table exists ( no error generate)

if( mysql_num_rows( mysql_query("SHOW TABLES LIKE '".$table."'")))
{
//...
} 

Importar e Emportar no MySQL

Exportar CSV para MySQL

function exportarCSV_a_mySQL($fileCSV)
{
	$registros=0;

	$ruta=$fileCSV['tmp_name'];

	if(!file_exists($ruta))
	{return false;}

	$tabla=quitar_extension($fileCSV['name']);
	
	$borra_tabla="DROP TABLE `".$tabla."`";
	mysql_query($borra_tabla);
	$f=fopen($ruta,"r");
	if($f)
	{
		echo "<b>Guardando CSV en la BDD :</b><br />";
		$contenido=fread($f,filesize($ruta));
		fclose($f);
		$contenido=ereg_replace("\r\n", "\n" , $contenido); // convertimos windows a unix
		$lineas=explode("\n",$contenido);
		$titulo=explode(";",$lineas[0]);
		$NUM_CAMPOS=count($titulo);
		$sql_generado_para_eliminar="";
		$crear_tabla_campos="";
		for($i=0;$i<$NUM_CAMPOS;$i++)
		{
		$titulo[$i]=ereg_replace("\"", "" , $titulo[$i]); // kitamos comillas
		$sql_generado_para_eliminar.=" AND `".$titulo[$i]."` =''";
		$crear_tabla_campos.="`".$titulo[$i]."` varchar(60) NOT NULL";
			if($i+1!=$NUM_CAMPOS)// si no es el ultimo , ponemos coma
			{
			$crear_tabla_campos.=",";
			}
		}
		$crear_tabla="CREATE TABLE `".$tabla."` (".$crear_tabla_campos.") ENGINE=MyISAM DEFAULT CHARSET=latin1;";
		mysql_query($crear_tabla);
		$linea=1;
		do
		{
			$insertar_titulos="";
			$insertar_campos="";
			$campo=explode(";",$lineas[$linea]);
			for($i=0;$i<$NUM_CAMPOS;$i++)
			{
			$campo[$i]=ereg_replace("\"", "" , $campo[$i]);
			$insertar_titulos.=" `".$titulo[$i]."` ";
			$insertar_campos.=" '".$campo[$i]."' ";
				if($i+1!=$NUM_CAMPOS)// si no es el ultimo , ponemos coma
				{
				$insertar_titulos.=",";
				$insertar_campos.=",";
				}
			}
			$sql="INSERT INTO `".$tabla."` ( ".$insertar_titulos." ) VALUES ( ".$insertar_campos." );";
			if(mysql_query($sql))
			{
			echo ". ";
			$registros++;
			}
			else
			{echo "X ";return false;}
		$linea++;
		}while(next($lineas));

	$sql="DELETE FROM `".$tabla."` WHERE 1".$sql_generado_para_eliminar;mysql_query($sql);
	echo "<br />";
	return $tabla;
	}
	else
	{
	return false;
	}
}

function quitar_extension($archivo)
{
	$extension = strrchr($archivo,".");
	$pos=strpos($archivo,$extension);
	return substr($archivo,0,$pos);
}

Exemplo de chamada:

$tabla = exportarCSV_a_mySQL($_FILES['archivo_csv']);
if($tabla)
{
echo "Export OK in mysql table : ".$tabla;
}
else
{
echo "Error in export ...";
}

Fonte: http://snippets.dzone.com/posts/show/4344