Created
September 9, 2022 17:17
-
-
Save zerobugs-oficial/44415724b77e3af5157457ab234a38a2 to your computer and use it in GitHub Desktop.
Selects condicionais usando PHP e MySQL
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 | |
$hostname = 'localhost'; | |
$user = 'root'; | |
$password = ''; | |
$database = 'select'; | |
$conn = new mysqli($hostname, $user, $password, $database); | |
if($conn->connect_errno) { | |
die("Falha na conexão! (" . $conn->connect_errno . ") " . $conn->connect_error); | |
} | |
?> |
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 | |
include('conexao.php'); | |
if(isset($_GET['cidade'])) { | |
echo "Você selecionou a cidade com o id " . $_GET['cidade']; | |
die("<a href=\"index.php\">Voltar ao início</a>"); | |
} | |
$sql_code_states = "SELECT * FROM estados ORDER BY nome ASC"; | |
$sql_query_states = $conn->query($sql_code_states) or die($conn->error); | |
?> | |
<form method="GET" action=""> | |
<select <?php if(isset($_GET['estado'])) echo "disabled"; ?> required name="estado"> | |
<option value="">Selecione um estado</option> | |
<?php while($estado = $sql_query_states->fetch_assoc()) { ?> | |
<option <?php if(isset($_GET['estado']) && $_GET['estado'] == $estado['id']) echo "selected"; ?> value="<?php echo $estado['id']; ?>"><?php echo $estado['nome']; ?></option> | |
<?php } ?> | |
</select> | |
<?php if(isset($_GET['estado'])) { ?> | |
<select required name="cidade"> | |
<option value="">Selecione uma cidade</option> | |
<?php | |
$selected_state = $conn->real_escape_string($_GET['estado']); | |
$sql_code_cities = "SELECT * FROM cidades WHERE id_estado = '$selected_state' ORDER BY nome"; | |
$sql_query_cities = $conn->query($sql_code_cities) or die($conn->error); | |
while($cidade = $sql_query_cities->fetch_assoc()) { ?> | |
<option value="<?php echo $cidade['id']; ?>"><?php echo $cidade['nome']; ?></option> | |
<?php } ?> | |
</select> | |
<?php } ?> | |
<button type="submit">Avançar</button> | |
</form> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment