0
I have a form with the following elements:
<form name="dadosLocacao" action="registra_locacao.php" method="POST">
<div class="form-group">
<label for="filme">Filme</label>
<br>
<select class="selectpicker lg" multiple data-live-search="true" name="select_filmes[]">
<option>Selecione o Filme</option>
<?php
$result_filmes = "SELECT * FROM filmes";
$resultado = mysqli_query($conn, $result_filmes);
while($row_filmes = mysqli_fetch_assoc($resultado)){
?>
<option value="<?php echo $row_filmes['id']; ?>"> <?php echo utf8_encode($row_filmes['descricao']); ?>
</option>
<?php
}
?>
</select>
</div>
<div class="form-group">
<label for="datalocacao">Data da Locação</label>
<input type="date" class="form-control" name="datalocacao" id="datalocacao">
</div>
<div class="form-group">
<label for="filme">Cliente</label>
<br>
<select class="selectpicker lg" data-live-search="true" name="select_clientes">
<option>Selecione o Cliente</option>
<?php
$result_filmes = "SELECT * FROM cliente";
$resultado = mysqli_query($conn, $result_filmes);
while($row_cliente = mysqli_fetch_assoc($resultado)){
?>
<option value="<?php echo $row_cliente['id']; ?>"> <?php echo utf8_encode($row_cliente['nome']); ?>
</option>
<?php
}
?>
</select>
</div>
<div class="form-group">
<label for="observacao">Observação</label>
<textarea class="form-control" rows="2" id="observacao" name="observacao"></textarea>
</div>
<input type="hidden" name="acao" value="inserir">
<div class="form-group">
<button type="submit" class="btn btn-success">Cadastrar</button>
</div>
</div>
</form>
My file registra_locacao.php:
<?php
if(isset($_POST['acao'])){
if($_POST['acao'] == "inserir"){
insereLocacao();
}
if($_POST['acao'] == "alterar"){
alteraLocacao();
}
if($_POST['acao'] == "excluir"){
excluiLocacao();
}
}
function abrirBanco(){
$conexao = new mysqli("localhost", "root", "", "locadora");
return $conexao;
}
function insereLocacao(){
$select_filmes = $_POST["select_filmes"];
$datalocacao = $_POST["datalocacao"];
$select_clientes = $_POST["select_clientes"];
$observacao = $_POST["observacao"];
$dados = count($select_filmes);
$banco = abrirBanco();
for($i=0; $i<$dados;$i++){
$filmeindice = $select_filmes[$i];
$sql = "INSERT INTO locacao(id_locacao,id_cliente,id_filme,data_locacao,observacao) VALUES (NULL,'$select_clientes', '$filmeindice', '$datalocacao', '$observacao' ";
$banco->query($sql);
}
$banco->close();
header('Location: home.php');
}
I am unable to enter records, when I query the database works normally, but through php I cannot. someone knows where I’m going wrong?
Good tip Valdeir, I would just add consider using PDO, because this code like this is totally vulnerable to injections
– Marcelo
@Marcelo
PDO
will not return to that query safe and theMySQLi
is as safe as (and faster as well). But it has been well observed, it needs to improve security (in case it is not filtering the data before executing the query).– Valdeir Psr