this is my HTML code:
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>supprimer un moyen</title>
<link rel="stylesheet" href="style.css">
</head>
<body class="example">
<br><br><br>
<form name="f" method="post" action=" supprimer_moyen.php ">
<center><b><h1>supprimer un moyen</h1> </b>
<label>   Entrer le code du moyen : </label>
<input type="text" name="code_moy" value="" placeholder="Code" required>
  <input id="gobutton" type="submit" name="sup" value="Supprimer"><br><br>
</center>
</form>
</body>
</html>
and this is my php code:
<?php
if (isset ($_POST['sup']))
{
$code_moy= $_POST["code_moy"];
$con=mysql_connect("localhost","root","") or die("Echec de connexion au serveur.".mysql_error());
mysql_select_db("ttp",$con) or die("Echec de sélection de la base.".mysql_error());
$sql = "delete from moyen_transport where ID='$code_moy'";
if (mysql_query($sql))
{
echo '<br>';
echo '<h1><center><font color="white"> suppression avec succès <font></center> </h1>';
echo '<center></center>';
}
else
{
echo '<br>';
echo '<h1><center><font color="red"> ce moyen n\'éxiste pas <font></center> </h1> ';
echo '<center></center>';
}
mysql_close();
}
?>
My problem is that no matter what i enter in input the php result is always "suppression avec succès" even if the "ID" dosen't exist in my database!!!
First try using mysqli
second you can use mysqli_num_rows like that
<?php
if (isset ($_POST['sup'])){
$code_moy= $_POST["code_moy"];
$con=mysqli_connect("localhost","root","","ttp") or die("Echec de connexion au serveur.".mysqli_error($con));
$sql = "select * from moyen_transport where ID='$code_moy'";
$query = mysqli_query($con,$sql);
if(mysqli_num_rows($query) == 0){
//No id found
echo '<br>';
echo '<h1><center><font color="red"> ce moyen n\'éxiste pas <font></center> </h1> ';
echo '<center></center>';
}else{
//id found
$sql = "delete from moyen_transport where ID='$code_moy'";
$query = mysqli_query($con,$sql)or die(mysqli_error($con));
echo '<br>';
echo '<h1><center><font color="white"> suppression avec succès <font></center> </h1>';
echo '<center></center>';}}
?>
Try checking if the returned value is empty
$result = mysql_query($sql);
if(!empty($result)){
//success code here
} else {
//fail code here
}
Related
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'm working in a simple login screen with PHP and MySQL with this full code:
<?php
include("conexion.php");
session_start();
if (isset($_SESSION['username'])) {
?>
<!DOCTYPE html>
<meta charset="utf-8">
<html lang="es">
<html>
<head>
<title></title>
</head>
<body>
<h1>YA INICIASTE SESION <?php echo $_SESSION['username']?></h1>
</body>
</html>
<?php
}else{
?>
<!DOCTYPE html>
<html lang="es">
<meta charset="utf-8">
<head>
<title>Login</title>
<link rel="stylesheet" type="text/css" href="css/estilos.css">
</head>
<body>
<center>
<div class="caja_login">
<form method="POST" action="inicio.php">
<label>Nombre de usuario:</label><input type="text" name="usuario" placeholder="Usuario" required/><br><br>
<label>Contraseña:</label><input type="password" name="contra" placeholder="Contraseña" required /><br><br>
<input type="submit" value="Entrar" name="iniciar-sesion"/><br>
</form>
</div>
<div class ="caja_registro">
<form method="POST">
<h4><label>¿Aún no estás registrado?</label></h4>
<label>Nombre de usuario:</label><br><input type="text" name="nombrerg" placeholder="Nombre de usuario" required><br>
<label>Contraseña:</label><br><input type="password" name="contrarg" placeholder="Contraseña" required><br>
<label>Repetir contraseña:</label><input type="password" name="contrarg2" placeholder="Repita la contraseña" required><br>
<input type="submit" name="registro" value="Crear Cuenta"><br>
</form>
</div>
</center>
<?php //----------------------PARA EL REGISTRO-----------------------
include("conexion.php");
if(isset($_POST['registro'])){
$sql = 'SELECT * FROM cuenta';
$rec = mysqli_query($conexion, $sql);
$verificar =0;
while ($resultado = mysqli_fetch_object($rec)) {
if($resultado->usuario == $_POST['nombrerg']) {//verificamos que el nombre de usuario no existe
$verificar = 1;//si verificar es 1 es que el usuario esta repetido
}
}
if ($verificar == 0) { //si varificar es 0 entonces el nombre no esta repetido
if ($_POST['contrarg'] == $_POST['contrarg2']) {
$nom = $_POST['nombrerg'];
$pw = $_POST['contrarg'];
$pw_en = password_hash($pw, PASSWORD_DEFAULT); //encripta la contraseña
$conexion->query("INSERT INTO cuenta (usuario, contra) VALUES ('$nom','$pw_en')");
mysqli_query($conexion, $sql);
header('Location: inicio.php');
}else{
echo "Intente con otro usuario y contraseña";
}
}else{
echo "Intente con otro usuario y contraseña";
}
}
//-----------------------------PARA EL LOGIN-------------------------
if (isset($_POST['iniciar-sesion'])) { //se comprueba que el boton iniciar sesion fue presionado
$username = $_POST['usuario'];
$sqlLogin= "SELECT usuario,contra FROM cuenta WHERE usuario= '$username'";
$recLogin= mysqli_query($conexion, $sqlLogin);
$sesion= mysqli_fetch_array($recLogin);
if(password_verify($_POST['contra'], $sesion['contra'])){
$_SESSION['username'] = $_POST['usuario'];
header('Location: inicio.php');
}else{
echo "Usuario o contraseña incorrectos";
header('Location: index.php');
}
}
?>
</body>
</html>
<?php
}
?>
But when I log in, whether or not the username and password is correct, it logs in, but I don't know why.
I get no error in the index.php screen.
You are submitting the form to inicio.php which the user should go here if they are logged in. change action=inicio.php in your form.
<form method="POST" action="">
<label>Nombre de usuario:</label><input type="text" name="usuario" placeholder="Usuario"
required/><br><br>
<label>Contraseña:</label><input type="password" name="contra" placeholder="Contraseña"
required/><br><br>
<input type="submit" value="Entrar" name="iniciar-sesion"/><br>
</form>
I have 2 questions. The first one is probably really easy but I don't know how to do it. I made a code that lets you save a music artist and a single and after you save it you can open it with a but I want to open it with a button how do i do that.
And the second question is when you open the saved files I get 20 lines of things that are empty and 1 that is full (sorry for my bad english). How do I change that into normal lines so it only makes a line if needed. Here are my 2 codes:
FILE NAME SEB2.php
<!DOCTYPE html>
<html>
<head>
<title></title>
<?php
if (!empty($_POST)) {
$artiest = $_POST["artiest"];
$single = $_POST["single"];
$fp = fopen("muziekcollectie.txt", "a+");
fputs($fp, $artiest."\r\n");
fputs($fp, $single."\r\n");
fclose($fp);
}
?>
</head>
<body>
<form name="woorden" method="post">
Artiest:<input type="text" name="artiest"><br>
Single:<input type="text" name="single"><br>
<input type="submit" name="Add" value="Add"><br><br>
<form>
<!-- <input type="submit" name="Watch" value="Watch" action="SEB2.php"> -->TEST
</body>
</html>
FILE NAME SEB2.php
<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="utf-8">
<title>Het gastenboek lezen</title>
</head>
<body>
<?php
$bestandsnaam = "muziekcollectie.txt";
// aantal regels per bijdrage om in te lezen
// elke bijdrage bestaat uit 5 regels
$aantal_regels = 2;
// teller om bij te houden hoeveel regels
// zijn gelezen
$teller = 0;
// Aantal bijdragen wordt bijgehouden.
$aantal_bijdragen = 0;
// gastenboek openen om te lezen
if (file_exists($bestandsnaam)){
$fp = fopen($bestandsnaam, "r");
}
else{
echo "<h2>De muziekcollectie is nog leeg!</h2>
<a href= 'SEB1.php'>
Wees de eerste die erin schrijft!</a> ";
exit;
}
while (!feof($fp)){
$regel = fgets($fp);
if (!feof($fp)){
if ($teller % $aantal_regels == 0){
// kop afdrukken
$aantal_bijdragen++;
// echo "<hr>";
echo "<h3>Bijdrage: $aantal_bijdragen</h3>";
}
}
// regel afdrukken
echo "$regel <br>";
// echo "<hr>";
$teller++;
}
echo "<a href='SEB1.php'>Terug naar de
homepage</a>";
?>
</body>
</html>
The button link is not that hard
<button onclick="window.location.href='SEB2.php';"></button>
I noticed you didn't close your form so that could be the problem when you tested it.
I'm not sure what you mean with the second part but I think it's just cause you do not have an if empty check on your post so empty input will be added to the file as well. If that's the problem this will solve it:
if (!empty($_POST['artiest']) && !empty($_POST['single']))
It is correctly printing in UTF-8_encode(), but after i update it , cause i have a button to update the database, it prints with some stupid characters...
I have it on the database in a table, and when i list it on a page and then change something and update it to the database it print with stupid characters
Code where i update:
<?php
if (!isset($_SESSION["auth"])) {
header('Location: index.php?backUrl='.$_SERVER['PHP_SELF']);
exit();
}
$host="localhost"; // Nome do host onde esta o banco de dados. Padrão ‘localhost’
$usuario="root"; // Usuário do Mysql. Padrão ‘root
$senha=""; // Senha do Mysql
$db ="teste"; // Nome da Database
?>
<meta charset="utf-8"/>
<h2 align="center" style="color:white; font-family:"Trebuchet MS", Helvetica, sans-serif; font-size:20px;">Alteração de Orgãos</h2>
<form action="" method="POST" name="alt" id="alt" enctype="multipart/form-data">
<div class="box">
<label>
<textarea rows="20" cols="100" id="texto" name="texto"><?php
$mysqli = mysqli_connect("$host", "$usuario", "$senha")or die("cannot connect");
mysqli_select_db($mysqli,$db)or die("cannot select DB");
$query2 = "Select * from teste";
$stat=$mysqli->query($query2);
if($stat->num_rows>0)
{
while ($row = $stat->fetch_assoc()) {
echo utf8_encode($row["texto"]);
}
} else
{
echo utf8_encode("Não existe nada na página");
}
?></textarea>
</label>
<label >
<input align="center" type="submit" value="Alterar" name="alterar_btn" id="alterar_btn" class="entrar">
</label>
</div>
</form>
<?php
$a1=$b1=$c1=$d1='';
//Alterar
if(isset($_POST['texto']))
{
if(isset($_POST['alterar_btn']))
{
$query="update teste set texto=? where titulo='orgaos'";
$stat = $mysqli->prepare($query);
$stat->bind_param('s',$_POST['texto']);
if ($stat->execute() && $stat->affected_rows>0){
echo "<div><strong>Foi alterado um Orgão!</strong></div>";
}
else{
echo "<div><strong>Nao foi alterado!</strong></div>";
}
$stat->close();
}
}
?>
When i try to do log in it always appear: "El usuario o contraseña es incorrecto", i dont know the problem.
I think i have done something bad when i was tipping the code.
Here i leave the code:
Acceso.php
<?php
session_start();
$titulo = "Acceso al panel";
include 'inc/header.php';
if($_SESSION['Logueado'] == TRUE) {
header('Location: funciones/panel.php');
}else{
?>
<html>
<center>
<form method="POST" action="funciones/panel.php">
<div class="form-group">
Nombre: <input type="text" name="nombre"></input>
<hr>
Contraseña: <input type="password" name="pass"></input>
<hr>
<input type="submit" name="enviar" value="Acceso"></input>
</div>
</form>
</center>
</html>
<?php
include 'inc/footer.php';
}
?>
The next step: panel.php
<?php
session_start();
include 'inc/header.php';
include 'panel_funciones.php';
$usuario = $_POST["nombre"];
$pass = $_POST["pass"];
try {
$bd = new PDO("mysql:host=localhost;dbname=b9_16267033_1","b9_16267033","123456");
$bd->query("SET NAMES 'utf8'");
} catch (Exception $e){
echo "No se ha podido conectar";
exit;
}
try{
$sql= "SELECT usuario, pass FROM usuarios WHERE usuario='$usuario' and pass='$pass'";
}catch(Exception $e){
echo "Error en consulta";
exit;
}
$iniciosesion=mysql_query($sql);
$contar = mysql_num_rows($iniciosesion);
// AQUI COMIENZA COMPROBACIÓN
if ($contar == 1) {
$_SESSION['Logueado'] = TRUE;
panel();
}
else{
echo "El usuario o contraseña es incorrecto";
}
include 'inc/footer.php';
?>
The function: panel_funciones.php
<?
$user = "Javier";
function panel(){
session_start();
echo "<center><h3>Bienvenido al Panel de Control</h1></center></h3></center>";
echo '<form action="logout.php" method="post">';
echo '<input type="submit" value="salir"></form>';
echo '<center>
<h4>Añadir Imagen</h4><hr>
<form method="POST" action="accion.php">
<div class="form-group">
Nombre: <input type="text" name="titulo"></input>
Link a Imagen: <input type="text" name="link"></input>
<input type="submit" name="enviar" value="Enviar"></input>
</div>
</form>
<center>';
echo '
<h4>Eliminar Imagen</h4><hr>
<form method="POST" action="accion2.php">
Escribe link <input type="text" name="imagen"></input>
<input type="submit" name="enviar2" value="Enviar"></input>';
}
?>
Thanks for your help, im trying to learn so from time to time i need to ask some questions.
Great job using PDO.
But i assume u forgot to check which paremeters take mysql_query :
U're using a PDOstatement instead of a string.
panel.php
...
$sql=$bd->query("SELECT usuario, pass
FROM usuarios
WHERE usuario='$usuario' and pass='$pass') ");
}
catch(Exception $e){
echo "Error en consulta";
exit;
}
// Continue to use PDO instead depreciated functions :'(
// Using fetchAll() & count instead
$iniciosesion=mysql_query($sql);
$contar = mysql_num_rows($iniciosesion);
.Move these 2 last lines into the last try & replace them by :
$iniciosesion = $bd->query($sql);
$result = $iniciosesion->fetchAll();
$contar = count($result);
Acceso.php
u missed <html> tags in ur main page.
<?php session_start(); ?>
<html>
<head></head>
<body>
<?php
...
//Then close body & html close at the end of your file.
Source :
PHP.net : PdoStatement::Fetchall
PHP.net mysql_query