Last active
July 19, 2016 22:21
-
-
Save joffilyfe/a556828f3a86a662c0059a025a320361 to your computer and use it in GitHub Desktop.
Exercício 1 PDO
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// CREATE TABLE aluno ( id int PRIMARY KEY auto_increment, nome varchar(255) null, curso_id int null ); | |
// CREATE TABLE curso ( cursoid int PRIMARY KEY auto_increment, nomecurso varchar(255) not null ); | |
/* | |
* Esta é a implementação do exercício 1 da disciplina de Desenvolvimento WEB com PHP | |
* Assunto: PDO | |
*/ | |
try { | |
$usuario = 'root'; | |
$password = ''; | |
$conexao = new PDO('mysql:host=localhost;dbname=estudar_php', $usuario, $password); | |
// SELECT de buscar curso | |
$sql = "SELECT * FROM curso"; | |
// Recebendo um POST e cadastrando o curso | |
if (isset($_POST['curso_nome'])) { | |
$nome = $_POST['curso_nome']; | |
/* | |
* Inserimos o novo curso no Banco de dados | |
* NOTA: o valor SEMPRE deve estar entre ASPAS ou vai dar erro | |
*/ | |
$insert = $conexao->exec("INSERT INTO curso(nomecurso) VALUES ('$nome')"); | |
if ($insert) { | |
echo "<span>Curso cadastrado com sucesso..</span>"; | |
} | |
} | |
} catch(PDOException $e) { | |
echo $e->getMessage(); | |
// Se não for possível conectar ao banco matamos a execução do script PHP | |
die(); | |
} | |
?> | |
<html> | |
<body> | |
<h2>Lista de cursos cadastrados</h2> | |
<ul> | |
<!-- Fazemos um select no banco e utilizamos o foreach para exibir --> | |
<?php foreach($conexao->query($sql) as $curso ) { ?> | |
<li> | |
<?php echo $curso['nomecurso']; ?> | |
</li> | |
<?php } ?> | |
</ul> | |
<h3>Formulário para cadastrar novos cursos</h3> | |
<form method="POST"> | |
<input type="text" name="curso_nome" placeholder="Nome do curso"> | |
<button>Enviar</button> | |
</form> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment