Você está na página 1de 12

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, 'Joo Brito10', '2007-01-12'); INSERT INTO `clientes` VALUES (11, 'Joo 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'); Recomendaes: - Usar sempre os mesmos nomes de variveis para mesmas funes. Exemplo: $link para receber a conexo. - Usar sempre as mesmas mensagens de erro para certos erros. Exemplo: mysql_query... 'Erro na consulta: ' . mysql_error() no esquecer de passar a funoo do MySQL que retorna o erro

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

Fechar a Conexo
print "<h2>FECHAR A CONEXO COM O MYSQL</h2>";

mysql_close($link);

Selecionar um Banco aps a Conexo


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

Executar Consulta SQL


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

Mover Ponteiro para um Registro Especfico


print "<h2>MOVER PARA UM REGISTRO ESPECFICO</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 "No foi possvel 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 numrico 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 excludos: %d\n", mysql_affected_rows()); /* Com uma clusula WHERE que nunca verdadeira isso deve retornar 0 */ mysql_query('DELETE FROM mytable WHERE 0');

printf("Registros excludos: %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 excludo com sucesso<br>"; } else { echo 'Erro ao excluir o banco de dados: ' . mysql_error() . "<br>"; } <pre>

<h2>Retornar Nmero do Erro</h2>

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

Informaes sobre os Campos


print "<h2>INFORMAES SOBRE CAMPOS</h2>"; $i = 0; while ($i < mysql_num_fields($result)) { echo "Informao para a coluna $i:<br><br>"; $meta = mysql_fetch_field($result, $i); if (!$meta) { echo "Sem informao disponvel<br>"; } echo "<pre> blob: max_length: name: not_null: numeric: primary_key: table: type: default: unique_key: unsigned: zerofill: "; $i++; } $meta->blob $meta->max_length $meta->name $meta->not_null $meta->numeric $meta->primary_key $meta->table $meta->type $meta->def $meta->unique_key $meta->unsigned $meta->zerofill

multiple_key: $meta->multiple_key

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; } // Recebero 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 $table = mysql_num_rows($result); = 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 $type $len = mysql_field_name($result, $i); = mysql_field_type($result, $i); = mysql_field_len($result, $i); " . $len . " " . $flags . "<br>";

$flags = mysql_field_flags($result, $i); echo $name . " " . $type . " }

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, no pode listas as tabelas<br>"; echo 'Erro no MySQL: ' . mysql_error(); exit; } while ($row = mysql_fetch_row($result)) { echo "Tabela: {$row[0]}<br>"; }

Nmero de Campos
print "<h2>NMERO 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 ..."; }

Você também pode gostar