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();
}
}
?>
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));
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>
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
}
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
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have 2 buttons on my table which delete and edit data from the table, (data from the database) the delete button works well but the edit isnt working.. It runs like it is working but when I list the data it is like I created in the PhpMyadmin..
here is the main edit code:
<?php
// Editar um registo de user
if (isset($_GET['editequip']) == False) {
// Caso seja chamado directamente na URL o ficheiro "editar.php",
// este é redireccionado para o ficheiro "lista.php"
header("location:javascript:history.go(-1);return false;;");
} else {
$editequip = trim($_GET['editequip']);
}
$connection = new mysqli('***', '****', '****', '****');
$obterequip = "SELECT * FROM fichas WHERE id_ficha LIKE '$editequip'";
$resultequip = $connection->query($obterequip);
// Se devolveu 0 ou mais do que um utilizador, termina script
if ($connection->affected_rows != 1) {
header("location:javascript:history.go(-1);return false;");
exit();
}
$objequip = $resultequip->fetch_object();
$id_ficha = $objequip->id_ficha;
$id_user = $objequip->id_user;
$avaria = $objequip->avaria;
$observacoes = $objequip->observacoes;
$observacoes_privadas = $objequip->observacoes_privadas;
$estado = $objequip->estado;
?> <!DOCTYPE HTML>
<html><head>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<link href="favicon.ico" rel="shortcut icon">
<title>Edição de Equipamentos</title></head>
<body>
<div id="links">
Voltar ao site |
Ínicio |
Utilizadores |
Upload de Ficheiros |
Logout
</div>
<h1>Editar Estado</h1>
<div id="container"><div class="left">
<form action="updatequip.php" method="post" id="editar">
<input type="hidden" name="ificha" value="<?php echo $id_ficha ?>"/>
<label>ID da Ficha: </label> <?php echo $id_ficha ?> <br>
<label>ID do Cliente: </label><input type="text" name="iuser" value="<?php echo $id_user ?>"><br>
<label>Avaria: </label><input type="text" name="iavaria" value="<?php echo $avaria ?>"><br>
<label>Observações: </label><input type="text" name="iobservacoes"value="<?php echo $observacoes ?>"><br>
<label>Observações Privadas: </label><input type="text" name="iobservacoes_privadas" value="<?php echo $observacoes_privadas?>"><br>
<label>Estado</label><input type="text" name="iestado" value="<?php echo $estado ?>"><br>
<input type="submit" value="Alterar"/>
<input type="button" value="Cancelar"onclick="javascript:history.go(-1);return false;"/>
</form>
</div>
</div>
<div class="footer">
<p>Copyright © 2013 - Todos os direitos reservados - Númica</p>
</div>
</body>
</html>
and the action page:
<?php
// Inserir o registo na BD
include_once ('config1.php');
// Estabelecer a ligação à BD
$connection = new mysqli('*****', '*****', '*******', '***');
//Verificar se a ligação foi estabelecida com sucesso
if (mysqli_connect_errno() ) {
echo "</h2>Erro no acesso a BD</h2>" . mysqli_connect_error();
exit();
}
// Validar se os campos do formulário foram preenchidos pelo utilizador
// Verificar se "username" foi enviado
if (isset($_POST['ificha']) == FALSE) {
echo ("Erro de submissão no ida da ficha");
exit();
} else {
$id_ficha = trim($_POST['ificha']);
}
if (isset($_POST['iuser']) == FALSE) {
echo ("Erro de submissão do id do user");
exit();
} else {
$id_user = trim($_POST['iuser']);
}
if (isset($_POST['iavaria']) == FALSE) {
echo ("Erro de submissão da avaria");
exit();
} else {
$avaria = trim($_POST['iavaria']);
}
if (isset($_POST['iobservacoes']) == FALSE) {
echo ("Erro de submissão nas observacoes");
exit();
} else {
$observacoes = trim($_POST['iobservacoes']);
}
if (isset($_POST['iobservacoes_privadas']) == FALSE) {
echo ("Erro de submissão nas observacoesprivadas");
exit();
} else {
$observacoes_privadas = trim($_POST['iobservacoes_privadas']);
}
if (isset($_POST['iestado']) == FALSE) {
echo ("Erro de submissão no estado");
exit();
} else {
$estado = trim($_POST['iestado']);
}
// Final das validações (avisa caso algum erro seja detectado)
if ($erro) {
echo "<p>Formulário submetido com erros</p>";
echo $msgerro;
echo "<br>";
// Desenha 2 botões "Corrigir" e "Listar"
echo "<a class='ains' href='javascript:history.go(-1)' title='Volta à página anterior'>Corrigir </a>";
echo "<br/>";
echo "<a class='ains' href='verificarequipamentos.php'>Listar</a>";
exit();
}
$sql = "UPDATE fichas SET
id_user = '$id_user';
avaria = '$avaria';
observacoes = '$observacoes';
observacoes_privadas = '$observacoes_privadas';
estado = '$estado';
WHERE
id_ficha = '$id_ficha'";
$connection->query($sql);
// Lista users depois de actualizar
header("location:verificarequipamentos.php");
?>
Change the semicolons to comas on the update query Or concat the variables with dots, You shoud also use a framework for this kind of things, it could be much easier.