i'm here trying to learn some php but i'm having some problems with my code now i'm trying to solve the "getimagesize(): Filename cannot be empty" but there are many others like:/
-Undefined variable: date/
-Undefined variable: imgData /
And yes i've tried other codes and still have the same problem/
So here's my code.
<?php
$link = mysqli_connect("blah", "blah", "blah", "blah");
if($link === false){
die("ERRRO: Não foi possivel a conexão com a base de dados. " . mysqli_connect_error());
}
if(!empty($_FILES['userImage']['tmp_name'])
&& file_exists($_FILES['userImage']['tmp_name'])) {
$imgData= addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
}
$imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
$portal = mysqli_real_escape_string($link, $_POST['field1']);
$datacri = mysqli_real_escape_string($link, $_POST['field2']);
$datacri = date('Y-m-d', strtotime(str_replace('-', '/', $date)));
$datapub = mysqli_real_escape_string($link, $_POST['field3']);
$datapub = date('Y-m-d', strtotime(str_replace('-', '/', $date)));
$titulo = mysqli_real_escape_string($link, $_POST['field4']);
$keyword = mysqli_real_escape_string($link, $_POST['field5']);
$hashtags = mysqli_real_escape_string($link, $_POST['field6']);
$pedido = mysqli_real_escape_string($link, $_POST['field7']);
$autor = mysqli_real_escape_string($link, $_POST['field8']);
if (!$portal) {
echo '<script type="text/javascript"> alert("Preencha todos os campos "); </script>';
mysqli_close($link);
}
$sql = "INSERT INTO pedidos (p_portal, p_datacri, p_datapub, p_titulo, p_titulo, p_keywords, p_hashtags, p_imageType, p_imageData, p_pedido, p_autor)
VALUES('$portal', '$datacri', '$datapub', '$titulo', '$keyword', '$hashtags', '{$imageProperties['mime']}', '{$imgData}', '$pedido', '$autor')";
if(mysqli_query($link, $sql)){
echo '<script type="text/javascript"> alert("Portal Criado"); </script>';
} else{
echo "ERRO: Não foi possivel executar o comando $sql. " . mysqli_error($link);
}
?>
And my html file:
<form action="php\pedidos\p_ins.php" enctype="multipart/form-data" method="post">
<link rel="stylesheet" href="css\pedidos.css">
<fieldset>
<legend><span class="number">1</span> Criar Pedido</legend>
<label for="portal">Portal</label
<?php
$link = mysqli_connect("blah", "blah", "blah", "blah");
if($link === false){
die("ERRRO: Não foi possivel a conexão com a base de dados. " . mysqli_connect_error());}
$result = $link->query("select po_id, po_nome from portais");
echo "<html>";
echo "<body>";
echo "<select name='field1' name='po_id'>";
echo "<option value=''>----Selecione um Portal----</option>";
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['po_id'];
$name = $row['po_nome'];
echo '<option value="'.$id.'">'.$name.'</option>';
} echo "</select>";
echo "</body>";
echo "</html>";?>
<label>Data de Criação</label>
<input type="date" name="field2" placeholder="Data de publicacao do Post">
<label>Data de Publicação</label>
<input type="date" name="field3" placeholder="Data de publicacao do Post">
<label>Titulo</label>
<input type="text" name="field4" placeholder="Insira aqui o Titulo">
<label>Keywords</label>
<input type="text" name="field5" placeholder="Insira aqui as Keywords">
<label>Hashtags</label>
<input type="text" name="field6" placeholder="Insira aqui as Hashtags">
<label>Imagem</label>
<p> </p>
<input type="file" name="userImage" accept="image/*" class="inputFile"> <p> </p>
<label>Pedido</label>
<textarea type="text" name="field7" placeholder="Insira aqui o Pedido"></textarea>
<label for="autores">Autor</label>
<?php
$result = $link->query("SELECT *FROM autores");
echo "<html>";
echo "<body>";
echo "<select name='field8' name='a_id'>";
echo "<option value=''>----Selecione um autor----</option>";
while ($row = $result->fetch_assoc()) {
unset($id, $name)
; $id = $row['a_id'];
$name = $row['a_nome'];
echo '<option value="'.$id.'">'.$name.'</option>';
} echo "</select>";
echo "</body>";
echo "</html>";?>
<input type="submit" value="Enviar" />
<div id='footer'>
</div>
</form>
Thanks.
Make sure your input type="file" is inside a form that has an enctype="multipart/form-data" or it will not send to file to your PHP script and $_FILES['userImage']['tmp_name'] will be empty
<form method="post" enctype="multipart/form-data" action="yourphpfile.php">
<label>Data de Criação</label>
<input type="date" name="field2" placeholder="Data de publicacao do Post">
<label>Data de Publicação</label>
<input type="date" name="field3" placeholder="Data de publicacao do Post">
<label>Titulo</label>
<input type="text" name="field4" placeholder="Insira aqui o Titulo">
<label>Keywords</label>
<input type="text" name="field5" placeholder="Insira aqui as Keywords">
<label>Hashtags</label>
<input type="text" name="field6" placeholder="Insira aqui as Hashtags">
<label>Imagem</label>
<p> </p>
<input type="file" name="userImage" class="inputFile"> <p> </p>
<label>Pedido</label>
<textarea type="text" name="field7" placeholder="Insira aqui o Pedido"></textarea>
<label for="autores">Autor</label>
</form>
As for your PHP code, I would advise putting all the block concerning the insert to database inside your if block. Plus you have some errors that are fixed here :
if(!empty($_FILES['userImage']['tmp_name'])
&& file_exists($_FILES['userImage']['tmp_name'])) {
$imgData= mysqli_real_escape_string($link, file_get_contents($_FILES['userImage']['tmp_name']));
$imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
$portal = mysqli_real_escape_string($link, $_POST['field1']);
$date = mysqli_real_escape_string($link, $_POST['field2']);
$datacri = date('Y-m-d', strtotime(str_replace('-', '/', $date)));
$date = mysqli_real_escape_string($link, $_POST['field3']);
$datapub = date('Y-m-d', strtotime(str_replace('-', '/', $date)));
$titulo = mysqli_real_escape_string($link, $_POST['field4']);
$keyword = mysqli_real_escape_string($link, $_POST['field5']);
$hashtags = mysqli_real_escape_string($link, $_POST['field6']);
$pedido = mysqli_real_escape_string($link, $_POST['field7']);
$autor = mysqli_real_escape_string($link, $_POST['field8']);
if (!$portal) {
echo '<script type="text/javascript"> alert("Preencha todos os campos "); </script>';
mysqli_close($link);
}
$sql = "INSERT INTO pedidos (p_portal, p_datacri, p_datapub, p_titulo, p_keywords, p_hashtags, p_imageType, p_imageData, p_pedido, p_autor)
VALUES('$portal', '$datacri', '$datapub', '$titulo', '$keyword', '$hashtags', '{$imageProperties['mime']}', '{$imgData}', '$pedido', '$autor')";
if(mysqli_query($link, $sql)) {
echo '<script type="text/javascript"> alert("Portal Criado"); </script>';
} else{
echo "ERRO: Não foi possivel executar o comando $sql. " . mysqli_error($link);
}
} else {
echo "ERROR: couldn't get image Data";
}
?>
......
Related
I'm doing something like a posting tool and it was working fine with the data being inserted on the database. I decided adding the field link and this error appeared:
Recoverable fatal error: Object of class mysqli could not be converted to string in C:\xampp\htdocs\Pequeno Davi 2 Versão completa\Painel de postagens\armazenar_postagens.php on line 23
My code:
<body>
<div class="col-md-4"></div>
<div class="col-md-4">
<div id="well well-sm">
<div id="panel">
<form action="armazenar_postagens.php" method="POST" enctype="multipart/form-data">
<h4>Escolha uma imagem de capa</h4>
<p><input type="file" name="image" id="image" class="form form-control"/></p>
<h4>Título da publicação</h4>
<p><input type="text" name="titulo" id="titulo" placeholder="Insira um título" class="form form-control"/></p>
<h4>Texto da publicação</h4>
<p><textarea name="descricao" id="descricao" placeholder="Texto da publicação" class="form form-control"></textarea></p>
<h4>Link</h4>
<p><input type="text" name="link" id="link" placeholder="Insira o endereço de um link" class="form form-control"/></p>
<h4>Adicione uma imagem para o corpo da publicação</h4>
<p><input type="file" name="image_imagem" id="image_imagem" class="form form-control"/></p>
<button type="submit" class="btn btn-primary form-control">Publicar</button>
</form>
<!--<?php
//if($campo_vazio == 1){
//echo '<font color="#FF0000">Você não preencheu algum dos campos!</font>';
//}
?> -->
</div>
</div>
</div>
<div class="col-md-4"></div>
<div class="col-md-4"></div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
<?php
require_once('db.class.php');
$titulo = $_POST['titulo'];
$descricao = $_POST['descricao'];
$link = $_POST['link'];
date_default_timezone_set('America/Sao_Paulo');
$data = date("d/m/Y");
$hora = date("H:i");
$uploaddir = 'imagens/uploads/';
$uploadfile = $uploaddir.basename($_FILES['image']['name']);
$imagename = $uploaddir.basename($_FILES['image']['name']);
$objDb = new db();
$link = $objDb-> conecta_mysql ();
if(move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)){
echo "Imagem enviada com sucesso";
$sql = "INSERT INTO postagens(titulo, descricao, data, hora, imagem_capa, link) VALUES ('$titulo', '$descricao', '$data', '$hora', '$imagename', '$link')";
echo'<img src="'.$imagename.'"/>' ;
if(mysqli_query($link, $sql)){
if(empty($titulo) || empty($descricao)){
header('Location: Ferramenta_postagem.php?campo_vazio=1');
}else{
header('Location: Ferramenta_postagem.php');
}
} else {
echo 'Erro ao registrar postagem!';
echo("Error description: " . mysqli_error($link));
}
}
?>
This line causes the problem
if(mysqli_query($link, $sql)){
You defined at the start
$link = $_POST['link'];
And in the middle
you used following code
$link = $objDb-> conecta_mysql ();
Where used the same varaible name
but mysqli_query($link expects a mysql connection instead of your $Link defined at the start
Exchange $link with $conn and use that in
$conn = $objDb-> conecta_mysql ();
----
mysqli_query($conn,sql
And please read up on prepared statements because of sql injection
Change your database connection variable $link.
You used this variable ($link) in POST method for data input, and also use database connection variable
$link = $objDb-> conecta_mysql ();
Change this variable like this:
$connect = $objDb-> conecta_mysql ();
If you change this variable then you should also change those line
if(mysqli_query($connect, $sql)){
And
echo("Error description: " . mysqli_error($connect));
by means of an if attempt that can not be created two records with the same name, it does not work and you can create a record with a dupiclate name
this is the controller
include_once 'model/solucion.php';
public function Guardar()
{
$this->model->Duplicado($_POST['Nombre']);
$name = $this->model->resultado2['Nombre'];
if($name == $_POST['Nombre']){
die("No se puede crear una solucion con el mismo nombre");
}else{
$solucion = new solucion();
$solucion->id = $_REQUEST['id'];
$solucion->Nombre = $_REQUEST['Nombre'];
$solucion->Tipo = $_REQUEST['Tipo'];
$solucion->Descripcion = $_REQUEST['Descripcion'];
$solucion->Pagina = $_FILES['Pagina']['name'];
}
header("Location: index.php");
}
this is the model
public $resultado2;
public function Duplicado($Nombre)
{
try {
$stm = $this->pdo->prepare("SELECT * FROM fallas WHERE Nombre = '$Nombre'");
$stm->execute();
$res=$stm->fetch(PDO::FETCH_ASSOC);
$this->resultado2 = array();
$i = 0;
foreach ($res as $row)
{
$this->resultado2[$i]['id'] = $row['id'];
$this->resultado2[$i]['Nombre'] = $row['Nombre'];
$this->resultado2[$i]['Tipo'] = $row['Tipo'];
$this->resultado2[$i]['Descripcion'] = $row['Descripcion'];
$this->resultado2[$i]['Pagina'] = $row['Pagina'];
$i++;
}
} catch (Exception $ex) {
die($e->getMessage());
}
}
this is the view
<ol class="breadcrumb">
<li>Inicio</li>
<li class="active"><?php echo $solucion->id != null ?
$solucion->Nombre : 'Nueva Solución'; ?></li>
</ol>
<form id="frm-alumno" action="?c=solucion&a=Guardar" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="<?php echo $solucion->id; ?>" />
<div class="form-group">
<label>Nombre</label>
<input type="text" name="Nombre" value="<?php echo $solucion->Nombre; ?>" class="form-control" placeholder="Ingrese su nombre" required>
</div>
<div class="form-group">
<label for="exampleFormControlSelect1">Tipo de fallo</label>
<select class="form-control" id="exampleFormControlSelect1" name="Tipo" value="<?php echo $solucion->Tipo; ?>">
<option value="software">software</option>
<option value="hardware">hardware</option>
<option value="red">red</option>
</select>
</div>
<div class="form-group">
<label>Descripcion</label>
<textarea type="text" name="Descripcion" value="<?php echo $solucion->Descripcion; ?>" class="form-control" rows="10" cols="40" required>
</textarea>
</div>
<div class="form-group">
<label>Pagina.php</label>
<input type="file" name="Pagina" value="<?php echo $solucion->Pagina; ?>" >
</div>
<div class="form-group">
<label >Imagenes</label>
<input type="file" class="form-control" id="archivo[]" name="archivo[]" multiple="" >
</div>
<hr />
<br>
<div class="text-right">
<button class="btn btn-success">Guardar</button>
</div>
What do I have to change in the controller to avoid creating duplicate records with the same name?
You need to pass the array and check whether this is empty or not . Check below for the code and run it and let me know if you get any error .
public function Duplicado($Nombre)
{
try{
$stm = $this->pdo->prepare("SELECT * FROM fallas WHERE Nombre = '$Nombre'");
$stm->execute();
$res=$stm->fetch(PDO::FETCH_ASSOC);
return $res;
}catch (Exception $ex) {
die($e->getMessage());
}
}
include_once 'model/solucion.php';
public function Guardar()
{
$name = $this->model->Duplicado($_POST['Nombre']);
//$name = $this->model->resultado2['Nombre'];
if(!empty($name)){
die("No se puede crear una solucion con el mismo nombre");
}else{
$solucion = new solucion();
$solucion->id = $_REQUEST['id'];
$solucion->Nombre = $_REQUEST['Nombre'];
$solucion->Tipo = $_REQUEST['Tipo'];
$solucion->Descripcion = $_REQUEST['Descripcion'];
$solucion->Pagina = $_FILES['Pagina']['name'];
}
header("Location: index.php");
}
I have a problem with my form, when I get in my website with Xampp, the webpage is not completed, doesn't appear the "region" combo box, the "fono" text field and the buttons, I don't know why it happens :( I wonder if someone could help me with this issue, please, as I fixed the bracket problems, now this problem is really freaking me out indeed.
<!DOCTYPE html>
<html>
<head>
<title>Formulario de datos</title>
<meta charset="UTF-8">
<script src="js/jquery.js"></script>
<script src="js/NumeroLetra.js"></script>
<script src="js/Hora.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/jquery.Rut.js"></script>
<script src="js/jquery.validate.js"></script>
</head>
<body onLoad="IniciarReloj24()">
<?php
ini_set('error_reporting',0);
include ('funciones.php');
?>
<form action = " " method="post">
<?php
//comprobamos el evento del boton
if ($_POST['btnRutBuscar'] == "Buscar"){
$cnn = Conectar();
//concatenamos los inputs para realizar el formato del rut
$rutt = $_POST['txtRut']."-".$_POST['txtDigito'];
//sentencia sql anidada entre registro y regiones
$sql = "select re.rut, re.nombres, re.apellidos, re.fnac, re.sexo, r.id, r.region, re.fono from registro re, regiones r where (re.region = r.id) and (re.rut = '$rutt')";
$rs = mysqli_query($cnn, $sql);
while ($row = mysqli_fetch_array($rs)){
$rut = $row['rut'];
$nom = $row['nombres'];
$ape = $row['apellidos'];
$fna = $row['fnac'];
$sex = $row['sexo'];
//recogemos el id de la tabla regiones que sera utilizada en el combo box de regiones
$id = $row['id'];
$reg = $row['region'];
$fon = $row['fono'];
//se les añade los value a los inputs para poder recibir los valores de la base de datos
}
}
?>
<center><h1>Formulario de datos: todo en uno</h1></center>
<center><h2>Creado por Matías Cáceres y Francisco Tello</h2></center>
<br>
<br>
<div align="center"><label>Rut:</label>
<input type="text" name="txtRut" id="txtRut" onkeypress="ValidaSoloNumeros()" value="<?php echo $rut?>" /> -
<input type="text" name="txtDigito" id="Verificador" size="2" onkeypress="ValidaSoloNumeros()" />
<input type="submit" name="btnRutBuscar" id="btnBuscar" value="Buscar" /></div>
<br>
<br>
<div align="center"><label>Nombres:</label>
<input type="text" name="txtNombres" id="txtNombres" onkeypress="txNombres()" value="<?php echo $nom ?>" />
<br>
<br>
<div align="center"> <label>Apellidos:</label>
<input type="text" name="txtApellidos" id="txtApellidos" onkeypress="txNombres()" value="<?php echo $ape ?>"/>
<br>
<br>
<div align="center"><label>Fecha de Naciemiento:</label>
<input type="date" name="txtFecha" value="<?php echo $fnac ?>" />
<br>
<br>
<div align="center"><label>Sexo:</label>
<select name="txtSexo">
<option value=""><?php $sex ?></option>
<option value = "Masculino">Masculino</option>
<option value = "Femenino">Femenino</option>
</select></div>
<br>
<br>
<div align="center"><label>Región:</label>
<?php
$cnn=Conectar();
$sql="select region from regiones";
$rs = mysqli_query($cnn,$sql); ?>
<select name="txtRegion">
<option value=""><?php echo $reg ?></option>
<?php while ($row=mysqli_fetch_array($rs))
{echo '<option>'.$row["region"];}
?>
</select>
</div>
<br>
<br>
<div align="center"><label>Fono:</label>
<input type="text" name="txtFono" id="txtFono" onkeypress="ValidaSoloNumeros()" value="<?php echo $fon ?>" />
</div>
<br>
<br>
<table>
<td><input type="submit" name="btnAgregar" id="btnAgregar" value="Agregar"/></div></td>
<td><input type="submit" name="btnModificar" id="btnModificar" value="Modificar"/></div></td>
<td><input type="submit" name="btnEliminar" id="btnEliminar" value="Eliminar"/></div></td>
<td><input type="submit" name="btnVerTodos" id="btnVerTodos" value="Ver Todos"/></div></td>
</table>
<?php
if($_POST['btnAgregar']=="Agregar")
{
$cnn = Conectar();
$rutt = $_POST['txtRut']."-".$_POST['txtDigito'];
$nom = $_POST['txtNombres'];
$ape = $_POST['txtApellidos'];
$fna = $_POST['txtFecha'];
$sexo = $_POST['txtSexo'];
$reg = $_POST['txtRegion'];
$fon = $_POST['txtFono'];
$sql = "insert into registro values('$rutt','$nom','$ape','$fna','$sexo','$reg','$fon')";
//este if lo acabo de colocar, es mas que nada para saber si ocurrio algo malo al momento de ejecutar la funcion (***** El if es necesario en todos los botones*****)
#Comprobar el nombre de las variables
if (empty($rut) || empty($nom) || empty($ape) || empty($fnac) || empty($sex) || empty($reg) || empty($fon)) {
echo "<script>alert('Todos los campos son obligatorios');</script>";
if( mysqli_query($cnn,$sql)){
echo "<script>alert('Se han grabado los datos')</script>";
echo "<script>window.location='index.php'</script>";
}else{
echo "<script>alert('ocurrio un problema');</script>";
}
}
}
if($_POST['btnEliminar']=="Eliminar")
{
$cnn = Conectar();
$rut = $_POST['txtRut']."-".$_POST['txtDigito'];//es necesario concadenar los dos inputs para que funcione la consulta
$sql = "delete from registro where (rut = '$rut')";
mysqli_query($cnn,$sql);
echo "<script>alert('Se eliminó el registro')</script>";
}
if($_POST['btnModificar']=="Modificar")
{
$cnn = Conectar();
$rutt = $_POST['txtRut']."-".$_POST['txtDigito']; //es necesario concadenar los dos inputs para que funcione la consulta
$nom = $_POST['txtNombres'];
$ape = $_POST['txtApellidos'];
$fna = $_POST['txtFecha'];
$sex = $_POST['txtSexo'];
$reg = $_POST['txtRegion'];
$fon = $_POST['txtFecha'];
$sql = "update registro set nombres='$nom', apellidos='$ape', fnac='$fna', sexo='$sex', region='$reg', fono='$fon' where rut='$rutt'";
mysqli_query($cnn,$sql);
echo "<script>alert('Se han editado los datos')</script>";
}
?>
</form>
<table border = '1'>
<tr>
<?php date_default_timezone_set('America/Santiago');
$vaFecha = date('d-m-y');
?>
<td>Fecha</td>
<td><input type = "text" name="caja_fecha" value = "<?php echo $vaFecha; ?>" disabled="disabled"></td>
</tr>
</table>
<form name="reloj24">
<input type="text" size="8" name="digitos" value=" " disabled="disabled">
</form>
<script>
$('#txtRut').Rut( {
digito_verificador: '#Verificador',
on_error: function(){ alert('Rut incorrecto');
$("#txtRut").val("");
$("#Verificador").val("");
}
} );
</script>
</body>
</html>
enter image description here
I can't get my form to submit. I used similar code to submit a different form and it worked fine, I just can't see why it does not work this time.
I don't get any errors. I tried error reporting I couldn't get any errors. The form input is sticky so the page reloads and the input is still there.
This is my html form:
<form action="evenement_maken.php" method="POST" enctype="multipart/form-data">
<input type="text" name="ev_naam" class="input-lg form-control" value='<?php echo (isset($_POST['ev_naam']) ? $_POST['ev_naam'] : "" );?>'>
<input type="text" name="ev_datum">
<input type="text" name="ev_adres" class="input-lg form-control" placeholder="Vul hier het adres van het evenement in..." value='<?php echo (isset($_POST['ev_adres']) ? $_POST['ev_adres'] : "" );?>'>
<textarea class="input-lg form-control" rows="10" name="ev_omschrijving" id="textarea" placeholder="Korte omschrijving van het evenement...">
<?php
if(isset($_POST['ev_omschrijving'])){
echo htmlentities($_POST['ev_omschrijving'], ENT_QUOTES);
}
?>
</textarea>
<button type="submit" class="pull-right btn btn-danger" name="submit">Opslaan</button>
</form>
And my php code:
<?php
$ev_naam = $ev_datum = $ev_omschrijving = $ev_adres = "";
if(isset($_POST['submit'])) {
$ev_naam = mysqli_real_escape_string($conn, $_POST['ev_naam']);
$ev_datum = mysqli_real_escape_string($conn, $_POST['ev_datum']);
$ev_omschrijving = mysqli_real_escape_string($conn, $_POST['ev_omschrijving']);
$ev_adres = mysqli_real_escape_string($conn, $_POST['ev_adres']);
if ($ev_naam=='') {
echo "<script>alert('Vul alsjeblieft alle velden in!')</script>";
exit();// zorgt ervoor dat de rest van het script niet wordt uitgevoerd
} else {
$insert_evenementen = "INSERT INTO evenementen (ev_naam,ev_datum,ev_omschrijving,ev_adres)
VALUES ( '$ev_naam','$ev_datum','$ev_omschrijving','$ev_adres')";
$run_evenementen = mysqli_query($conn, $insert_evenementen);
if (mysqli_query($conn, $insert_evenementen)) {
echo "<script>alert('Post is succesvol opgeslagen!')</script>";
echo "<script>window.open('evenement_maken.php','_self')</script>";
}
}
}
?>
This is the form that does submit properly (only uploading the img to ftp is not working):
<form action="post_maken.php" method="post" enctype="multipart/form-data">
<h4>Titel: </h4>
<input type="text" name="post_titel" class="input-lg form-control" value='<?php echo (isset($_POST['post_titel']) ? $_POST['post_titel'] : "" );?>' required>
<h4>Inhoud: </h4>
<textarea class="input-lg form-control" rows="10" name="post_inhoud" id="textarea" required>
if(isset($_POST['post_inhoud'])){
echo htmlentities($_POST['post_inhoud'], ENT_QUOTES);
}
?>
</textarea>
<h4>Categorie:</h4>
<select class="form-control" name="categorie_id" >
<option value="null" >selecteer een categorie...</option>
<?php
$categorie = mysqli_query($conn, "SELECT * FROM categorie");
while ($cat_row=mysqli_fetch_array($categorie, MYSQLI_ASSOC)) {
$cat_naam=$cat_row['cat_naam'];
echo "<option value='$cat_naam'>$cat_naam</option>";
}
</select>
<h4>Afbeelding toevoegen</h4>
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Zoeken…
</span>
</span>
</div>
<input type="file" name="post_img"/>
<p class="help-block">Voeg een afbeelding voor je blogpost toe.</p>
<br>
<button type="submit" class="pull-right btn btn-danger" name="submit">Opslaan</button>
</form>
And the php code:
<?php
$post_titel = $post_datum = $post_inhoud = $categorie_id = "";
if(isset($_POST['submit'])) {
$post_titel = mysqli_real_escape_string($conn, $_POST['post_titel']);
$post_datum = mysqli_real_escape_string($conn, date('m-d-y'));
$post_inhoud = mysqli_real_escape_string($conn, $_POST['post_inhoud']);
$categorie_id = mysqli_real_escape_string($conn, $_POST['categorie_id']);
$post_img = mysqli_real_escape_string($conn, $_FILES['post_img']['name']);
$post_img_tmp = mysqli_real_escape_string($conn, $_FILES['post_img']['tmp_name']);
if ($post_titel=='' || $categorie_id=='null' || $post_inhoud=='') {
echo "<script>alert('Vul alsjeblieft alle velden in!')</script>";
exit();
} else {
move_uploaded_file($post_img_tmp, "post_img/$post_img");
$post_bron = 0;
$post_datum = date("y-m-d");
$insert_posts = "INSERT INTO post (post_title,post_inhoud,post_datum,categorie_id, post_img, post_bron)
VALUES ( '$post_titel','$post_inhoud','$post_datum','$categorie_id','$post_img','$post_bron')";
$run_posts = mysqli_query($conn, $insert_posts);
if (mysqli_query($conn, $insert_posts)) {
echo "<script>alert('Post is succesvol opgeslagen!')</script>";
echo "<script>window.open('post_maken.php','_self')</script>";
}
}
}
?>
I am retrieving values from both databases (connection workes) and displaying it on the website, that also works. I'm using bootstrap 3.
Screenshot of my database table:
Can anyone see what I am doing wrong? I have been staring at this for hours.
You probably have a SQL error. Its always good to check and output mysqli_erros when they occur. Switch your code up to do this
if (mysqli_query($conn, $insert_evenementen)) {
// query was succesful
}else{
echo mysqli_erro($cnon); // sthing went wrong
}
Your code is open to SQL injection, I suggest you look into prepared statements
<?php
//procedural example from http://php.net/manual/en/mysqli.prepare.php
$city = "Amersfoort";
/* create a prepared statement */
if ($stmt = mysqli_prepare($link, "SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $city);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $district);
/* fetch value */
mysqli_stmt_fetch($stmt);
printf("%s is in district %s\n", $city, $district);
/* close statement */
mysqli_stmt_close($stmt);
}
I want a query to check if the user IP is already in database, and if it is, to not allow that user to make a new account.
Here's Register.php, if you want, I will post it all
<!-- Body Start -->
<div id="body">
<?php
if(!$login)
{
$form = true;
if(isset($_POST['userbox']))
{
$user_ip = $_SERVER['REMOTE_ADDR'];
$user = $_POST['userbox'];
$mail = $_POST['email'];
$pw = $_POST['password'];
$pw2 = $_POST['password2'];
//require_once('includes/recaptchalib.php');
//$resp = recaptcha_check_answer (CMS_PRKEY,
// $_SERVER["REMOTE_ADDR"],
// $_POST["recaptcha_challenge_field"],
//$_POST["recaptcha_response_field"]);
$user = mysql_real_escape_string($user);
$mail = mysql_real_escape_string($mail);
if(check_mail($mail) && $pw == $pw2 && check_name($user) && strlen($user) < 21 && strlen($user) > 5)
{
$sql0 = "SELECT szUserID FROM TGLOBAL_GSP.dbo.TACCOUNT WHERE szUserID = '".$user."'";
$q0 = odbc_exec($ms_con, $sql0);
$nFree = odbc_num_rows($q0);
if($nFree == 0)
{
$sql0 = "SELECT MAX(dwUserID) AS Result FROM TGLOBAL_GSP.dbo.TACCOUNT";
$q0 = odbc_exec($ms_con, $sql0);
$count0 = odbc_fetch_array($q0);
$count = $count0['Result'];
$date = date("Y-m-d H:i:s");
$sql = "INSERT INTO TGLOBAL_GSP.dbo.TACCOUNT(szUserID, szPasswd, bCheck, dFirstLogin, szMail, szLastLoginIp)
VALUES('".$user."','".$pw."', '1', {ts'".$date."'},'".$mail."','".$user_ip."')";
$stmt = odbc_prepare($ms_con, $sql);
odbc_execute($stmt, array($count + 1, $user, $pw, $mail));
echo '<p>Dein Account wurde erfolgreich erstellt! Du kannst dich nun einloggen.<br />» Zum Login</p>';
$form = false;
}
else
{
$error = 'Der Benutzername ist bereits vergeben!';
}
}
else
{
$error = 'Das Passwort, die eMail-Adresse oder der Benutzername waren nicht korrekt!';
}
}
if($form)
{
echo '<h4>Register</h4>';
echo'
<form action="register.php" method="post">
<label>Name <small><em>(required)</em></small></label>
<input type="text" name="userbox" id="userbox" />
<label>eMail-Adresse <small><em>(required)</em></small></label>
<input type="text" name="email" id="email" />
<label>Passwort <small><em>(required)</em></small></label>
<input type="password" name="password" id="password" />
<label>Password wiederholen <small><em>(required)</em></small></label>
<input type="password" name="password2" id="password2" /><br /><br />';
//require_once('includes/recaptchalib.php');
//echo recaptcha_get_html(CMS_PUKEY);
echo '<br /><input type="submit" value="Account anlegen" class="read_more2" />
</form>';
if(isset($error))
{
echo '<br /><p>'.$error.'</p>';
}
}
}
else
{
echo '<p>Du kannst keinen Account erstellen, da du eingeloggt bist!<br />» Zurück zur Startseite</p>';
}
?>
</div>
<!-- Body end -->