CI3.0 passing variable between controller and module - php

I have this method:
public function signup_validation() {
//definizioni setting per email di conferma
$emailsetting = array('mailtype' => 'html' );
$emailfrom = 'misure#lagiumentabardata.netsons.org';
$emailsubject ='Conferma registrazione';
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','required|trim|valid_email|is_unique[user.email]'); //check se la mail è davvero una mail valida e se esiste gia nel database $this->form_validation->set_rules('password','Password','required|trim'); $this->form_validation->set_rules('cpassword','Conferma Password','required|trim|matches[password]');
$this->form_validation->set_message('is_unique','email già esistente nel nostro database'); //override messaggio di errore
//check se il form è valido allora passa altrimenti ritorna al form. if ($this->form_validation->run() == true) {
//generare key
$key = sha1(uniqid());
//inviare una mail all'utente
$this->load->library('email', $emailsetting); //caricamento libreria
$this->load->model('model_users'); //caricamento modello per il controllo del db utente
$this->email->from($emailfrom,'La Giumenta Bardata');
$this->email->to($this->input->post('email'));
$this->email->subject($emailsubject);
$emailmessage = "<h1>ciao mondo</h1>
<a href='".base_url()."signup/register_user/$key'>click qui</a>"; //fare riferimento alla funzione register_user
$this->email->message($emailmessage);
//controllo scrittura dell'utente nel db
if ($this->model_users->add_temp_user($key) == true) { //passaggio chiave al modello che si occupa di aggiungerlo al DB
//invio email utente
if ($this->email->send() == true) {
echo "email inviata correttamente";
} else { echo "errore nell'invio stronzo";}
} else { echo "problemi nell'inserimento del db"; }
} else {
echo '<script>alert("TU NON PUOI PASSARE!");</script>';
$this->registrazione(); } }
In a signup.php controller.
First of all I don't understand why if I move $emailmessage variable where I set all the variables ($emailsetting, $emailfrom etc.) I get an error that the $emailmessage variable is undefined -.-
but, the real problem is that i can't pass the $key variable to a module:
public function add_temp_user($key){
$data = array('email' => $this->input->post('email'),
'nome' => $this->input->post('nome'),
'cognome' => $this->input->post('cognome'),
'password' => md5($this->input->post('password')),
'userkey'=>$key
);
$query = $this->db->insert('temp_users',$data); //generazione query
//check se la query è stata eseguita correttamente
if ($query) {
return true;
} else {
return false;
}
}
How can I pass a variable from a controller to a module? I try everything, from set the $key as public to set the __construct and nothing work...when the app needs to call the model I have an Undefined $key variable..
Thanks for help

You can move $emailmessage = up where the other things are set. But the line $key = sha1(uniqid()); must come before those assignments.
I tested this as best I could without having your database. Seems to work. $key makes it to the model anyway.
Notice that I build the link <a href=... a little differently, making better use of Codeigniter's abilities.
public function signup_validation()
{
//generare key
$key = sha1(uniqid());
//definizioni setting per email di conferma
$emailsetting = array('mailtype' => 'html');
$emailfrom = 'misure#lagiumentabardata.netsons.org';
$emailsubject = 'Conferma registrazione';
$emailmessage = "<h1>ciao mondo</h1>
<a href='".base_url("signup/register_user/$key")."'>click qui</a>"; //fare riferimento alla funzione register_user
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|is_unique[user.email]'); //check se la mail è davvero una mail valida e se esiste gia nel database $this->form_validation->set_rules('password','Password','required|trim'); $this->form_validation->set_rules('cpassword','Conferma Password','required|trim|matches[password]');
$this->form_validation->set_message('is_unique', 'email già esistente nel nostro database'); //override messaggio di errore
//check se il form è valido allora passa altrimenti ritorna al form. if ($this->form_validation->run() == true) {
//inviare una mail all'utente
$this->load->library('email', $emailsetting); //caricamento libreria
$this->load->model('model_users'); //caricamento modello per il controllo del db utente
//use chaining here, much more efficient
$this->email
->from($emailfrom, 'La Giumenta Bardata')
->to($this->input->post('email'))
->subject($emailsubject)
->message($emailmessage);
//controllo scrittura dell'utente nel db
if($this->model_users->add_temp_user($key))
{ //passaggio chiave al modello che si occupa di aggiungerlo al DB
//invio email utente
if($this->email->send() == true)
{
echo "email inviata correttamente";
}
else
{
echo "errore nell'invio stronzo";
}
}
else
{
echo "problemi nell'inserimento del db";
}
//these lines are not connected to anything as you have them in your question.
// So I have commented them out
//else {
// echo '<script>alert("TU NON PUOI PASSARE!");</script>';
// $this->registrazione(); }
}
Here's the model function.
I capture the inputs like this input->post(NULL, TRUE); because it grabs all the inputs at once. That eliminates multiple calls to input->. With the second argument=TRUE the inputs are sanitized.
Because db->insert() returns either true or false there is no need for the if/then statement.
public function add_temp_user($key)
{
$posted = $this->input->post(NULL, TRUE);
$data = array('email' => $posted('email'),
'nome' => $posted('nome'),
'cognome' => $posted('cognome'),
'password' => md5($posted('password')),
'userkey' => $key
);
//tornare successo o il fallimento di ricerca
return $this->db->insert('temp_users', $data); //generazione query
}

Related

How to make contact form multilanguage

So I have to make contact form multilingual, but im stuck for 7 hours already.
SO i have to make ajax ok/error messages without duplicating code.
$language = $_GET["language"] OR $language == "en";
$language = $_GET["language"] OR $language == "es";
$language = $_GET["language"] OR $language == "pl";
if ($language == "en") {
$okMessage = 'Thank you, we will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
}
if ($language == "pl") {
$okMessage = 'Dziękujemy, skontaktujemy się niedługo';
$errorMessage = 'W wiadomości pojawił się błąd, prosimy spróbować później';
}
if ($language == "es") {
$okMessage = 'Gracias, nos pondremos en contacto con usted pronto!';
$errorMessage = 'Hubo un error al enviar la solicitud. Por favor intente de nuevo.';
}
So what i want my code to do is that when im on poland contact form page. like www.website.com/pl-contact-page.php?language=pl - it gives me error/success messages in poland
After reading this thread I decided to give my little help, I changed a bit your code to get it more easy and secure... what that you need is Query String and Parse String... the rest is simple... I tested on my localtest and works fine...
<?php
#ini_set('default_charset', 'UTF-8');
$gurl = $_SERVER['QUERY_STRING'];
$ourl = array();
parse_str($gurl, $ourl);
if (isset($ourl['language']) || (!empty($ourl['language']))) {
$language = htmlspecialchars($ourl['language'], ENT_NOQUOTES, 'UTF-8');
if ($language == "en") {
$okMessage = 'Thank you, we will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
} elseif ($language == "pl") {
$okMessage = 'Dziekujemy, skontaktujemy sie niedlugo';
$errorMessage = 'W wiadomosci pojawil sie blad, prosimy spróbowac pózniej';
} elseif ($language == "es") {
$okMessage = 'Gracias, nos pondremos en contacto con usted pronto!';
$errorMessage = 'Hubo un error al enviar la solicitud. Por favor intente de nuevo';
}
// echo $okMessage; #Debug purpose
// echo $errorMessage; #Debug purpose
} else {
echo ("No language available!");
}
?>
Version with my function get_messages() that detect the correct string code (UTF-8 or ANSI):
<?php
#ini_set('default_charset', 'UTF-8');
$gurl = $_SERVER['QUERY_STRING'];
$ourl = array();
parse_str($gurl, $ourl);
if (isset($ourl['language']) || (!empty($ourl['language']))) {
$language = htmlspecialchars($ourl['language'], ENT_NOQUOTES, 'UTF-8');
function get_messages($string) {
return mb_convert_encoding($string, 'UTF-8', mb_detect_encoding($string, 'UTF-8, ISO-8859-1', true));
}
if ($language == "en") {
$okMessage = get_messages('Thank you, we will get back to you soon!');
$errorMessage = get_messages('There was an error while submitting the form. Please try again later');
} elseif ($language == "pl") {
$okMessage = get_messages('Dziekujemy, skontaktujemy sie niedlugo');
$errorMessage = get_messages('W wiadomosci pojawil sie blad, prosimy spróbowac pózniej');
} elseif ($language == "es") {
$okMessage = get_messages('Gracias, nos pondremos en contacto con usted pronto!');
$errorMessage = get_messages('Hubo un error al enviar la solicitud. Por favor intente de nuevo');
}
// echo $okMessage; #Debug purpose
// echo $errorMessage; #Debug purpose
} else {
echo ("No language available!");
}
?>
http://localhost-test/contact-page.php?language=pl
http://localhost-test/contact-page.php?language=en
http://localhost-test/contact-page.php?language=es
http://localhost-test/contact-page.php
Notes: you have to echo somewhere your messages otherwise the code appears not working well...
I hope this helps.

cant show up my image php from a DB

the problem is when it does return the binary file, pls help me
<!DOCTYPE html>
<html>
<head>
<title>Tienda Online</title>
<FORM action="upload_imagen.php" enctype="multipart/form-data" method="POST">
<input type="file" name="imagen"> Buscar imagen
<input type="submit" value="Buscar">
</FORM>
<div id="visualizar">
</div>
<form action="mostrar_imagen.php" method="POST">
<input type="text" name="valor" >
<input type="submit" value="mostrar">
</form>
</html>
upload_imagen.php this file upload an image and does storage in a DB
<?php
// Conexion a la base de datos
require "db_model.php";
class upload extends db_model {
function whatever() {
// Comprobamos si ha ocurrido un error.
if (!isset($_FILES["imagen"]) || $_FILES["imagen"]["error"] > 0) {
echo "Ha ocurrido un error.";
} else {
var_dump($_FILES["imagen"]);
// Verificamos si el tipo de archivo es un tipo de imagen permitido.
// y que el tamaño del archivo no exceda los 16MB
$permitidos = array("image/jpg", "image/jpeg", "image/gif", "image/png");
$limite_kb = 16384;
if (in_array($_FILES['imagen']['type'], $permitidos) && $_FILES['imagen']['size'] <= $limite_kb * 1024) {
// Archivo temporal
$imagen_temporal = $_FILES['imagen']['tmp_name'];
// Tipo de archivo
$tipo = $_FILES['imagen']['type'];
// Leemos el contenido del archivo temporal en binario.
$fp = fopen($imagen_temporal, 'r+b');
$data = fread($fp, filesize($imagen_temporal));
fclose($fp);
//Podríamos utilizar también la siguiente instrucción en lugar de las 3 anteriores.
// $data=file_get_contents($imagen_temporal);
// Escapamos los caracteres para que se puedan almacenar en la base de datos correctamente.
$data = mysql_real_escape_string($data);
// Insertamos en la base de datos.
$this->query ="INSERT INTO imagenes (imagen, tipo_imagen) VALUES ('$data', '$tipo')";
$resultado = $this->execute_query();
if ($resultado) {
echo "El archivo ha sido copiado exitosamente.";
} else {
echo "Ocurrió algun error al copiar el archivo.";
}
} else {
echo "Formato de archivo no permitido o excede el tamaño límite de $limite_kb Kbytes.";
}
}
}
}
$obj = new upload();
$obj->whatever();
?>
mostrar_imagen.php this section retrives the image in binary format, then i want to show it, so i read that i need a header and send it the type of image it is for example .jpg, .gif but i dont know if a i have an error
<?php
require 'db_model.php';
class mostrar extends db_model {
function __construct()
{
$id = $_POST['valor'];
$this->query = "SELECT imagen, tipo_imagen
FROM imagenes
WHERE imagen_id=$id";
$datos = $this->execute_query_as();
$imagen = $datos['imagen']; // Datos binarios de la imagen.
$tipo = $datos['tipo_imagen']; // Mime Type de la imagen.
// Mandamos las cabeceras al navegador indicando el tipo de datos que vamos a enviar.
---- > my problem is here, i guess
header("Content-type: image/jpg");
echo $imagen;
// A continuación enviamos el contenido binario de la imagen.
}
}
$obj = new mostrar();
?>
db_model.php
<?php
/**
* clase de la base de datos
*/
include_once('config.php');
class db_model
{
private $db_host = "localhost";
private $db_user = "root";
private $db_pass = "";
protected $db_name = "tienda_cartas";
protected $query;
protected $rows = array();
private $conection;
private function open_conection()
{
$this->conection = new mysqli($this->db_host,$this->db_user,$this->db_pass,$this->db_name);
if ($this->conection->connect_errno) {
echo "error al conectar";
die();
} else {
echo "conectado";
}
}
private function close_conection() {
$this->conection->close();
}
protected function execute_query() {
$this->open_conection();
$result = $this->conection->query($this->query);
if(!$result){
echo "no se pudo ejecutar el sql";
}
$this->close_conection();
return $result;
header("location:index.php");
}
protected function execute_query_as() {
$this->open_conection();
$result = $this->conection->query($this->query);
if(!$result){
echo "no se pudo ejecutar el sql";
}
$array_as = $result->fetch_assoc();
if(!$array_as){
echo "no hay incidencias";
die();
}
$this->close_conection();
return $array_as;
}
}
?>
This could be your problem:
$data = mysql_real_escape_string($data);
In your classes you use mysqli_* functions, but this one belongs to the deprecated mysql_* functions. When you call it it will automatically try to open a new database connection with mysql_connect(), which will fail because it doesn't have any information about your host. mysql_real_escape_string() will then return false:
Warning: mysql_real_escape_string(): A link to the server could not be established in test.php on line 2
bool(false)
Just remove the line, escaping binary data will most probably ruin it anyway. Instead you should use prepared statements to prevent SQL injections.

Check if user login data exists in a table and if not check in another table

Hello! I'm having some trouble making a login for normal users, I have to tables, one is for admin users and the other for employees. The thing is that I want to use the same login and in the PHP first check if the username exists in the table admintable and if not check if it exits in empTable.
Here is my code:
It is working and recognizing only admin users but then when I try to log in with employee users it doesn't log in.
THANKS!!
<?php
include 'cod/php/utils.php';
if(isset($_POST['txtuser']) )
{
//get data from POST
$txtuser = $_POST['txtuser'];
$txtpass = $_POST['txtpass'];
//verificar que exista el usuario en la tabla de admins
if(exists('admintable', 'Username', $txtuser))
{
//obtener el password del usuario
if(get_value('admintable', 'Password', 'Username', $txtuser) == $txtpass)
{
//iniciar sesion
session_start();
//almacenar el usuario en esta sesion
$_SESSION['usuario'] = $txtuser;
header('Location: web/admin.php');
}
}
//verificar que exista el usuario en la tabla de admins
else if(exists('empTable', 'empUsername', $txtuser))
{
//obtener el password del usuario
if(get_value('empTable', 'empPassword', 'empUsername', $txtuser) == $txtpass)
{
//iniciar sesion
session_start();
//almacenar el usuario en esta sesion
$_SESSION['usuario'] = $txtuser;
header('Location: web/usr.php');
}
}
else
{
print_login(true);
}
}
else
{
print_login(true);
}
else
{
print_login(false);
}
}
function print_login($showerror)
{}
?>

How to validate my contact form?

I used this code to connect my contact form to mysql but the problem is I don't know how to validate each item like the name has to be fill or the email should be valid so it will not bother me later when I take care all of it, here is my code :can you help me :
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
You should have client side validation (e.g using jquery)
and in your php you can try like this:
if(!empty($_POST['lastname']) && !empty($_POST['age']) && !empty($_POST['firstname']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('mysqli_real_escape_string($con,$_POST[firstname])','mysqli_real_escape_string($con,$_POST[lastname])','mysqli_real_escape_string($con,$_POST[age])')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
}
You can validate email in php like this:
filter_var($emailAddress, FILTER_VALIDATE_EMAIL)
php filter
For proper validation of a form, some aspects have to be taken into account, to help filter an excess of garbage input. My approach is this:
First of all, check the minimum lenght of the text. This way, you decrease the risk of getting meaningless input. Secondly, check the maximum lenght of the text; you don't want someone flooding your database with a ton of text just for fun. And thirdly, you should use regular expressions to check proper formats for the different fields (a postal code, a phone number, an e-mail) and very important, allow only characters that are required in that field, to avoid or minimize the risk of someone sending miserable cross-site injections thru the input.
Here an orientative example:
function validate_form() {
$errors = array();
// El nombre del usuario es necesario
if (! strlen(trim($_POST['user_name']))) {
$errors[] = 'The username is required.';
}
// El nombre del usuario no debe contener caracteres problemáticos
if (preg_match('#[^a-zA-Z0-9_\- ]#', trim($_POST['user_name']))) {
$errors[] = 'The username cannot contain invalid characters.';
}
// El nombre del usuario no debe tener menos de 3 caracteres
if (strlen(trim($_POST['user_name'])) < 3) {
$errors[] = 'The username cannot have less than 3 characters long.';
}
// El nombre del usuario no debe tener más de 24 caracteres
if (strlen(trim($_POST['user_name'])) > 24) {
$errors[] = 'The username cannot have more than 24 characters long.';
}
// La contraseña es necesaria
if (! strlen(trim($_POST['password']))) {
$errors[] = 'The password is required.';
}
// La contraseña no debe contener caracteres problemáticos
if (preg_match('#[^a-zA-Z0-9_\-]#', trim($_POST['password']))) {
$errors[] = 'The password cannot contain invalid characters.';
}
// La contraseña no debe tener menos de 6 caracteres
if (strlen(trim($_POST['password'])) < 6) {
$errors[] = 'The password cannot have less than 6 characters long.';
}
// La contraseña no debe tener más de 12 caracteres
if (strlen(trim($_POST['password'])) > 12) {
$errors[] = 'The password cannot have more than 12 characters long.';
}
// La contraseña debe contener letras y números
if (! preg_match('/([a-zA-Z][0-9]|[0-9][a-zA-Z])+/', trim($_POST['password']))) {
$errors[] = 'The password must contain letters and numbers.';
}
// Password y Password Check deben ser iguales
if ($_POST['password'] != $_POST['password_check']) {
$errors[] = 'Password and Password Check do not match.';
}
// El correo electrónico es necesario
if (! strlen(trim($_POST['e_mail']))) {
$errors[] = 'The e-mail is required.';
}
// El correo electrónico no debe contener caracteres problemáticos
if (preg_match('/[^a-zA-Z0-9_\-#\.]/', trim($_POST['e_mail']))) {
$errors[] = 'The e-mail cannot contain invalid characters.';
}
// El correo electrónico no debe tener más de 64 caracteres
if (strlen(trim($_POST['e_mail'])) > 64) {
$errors[] = 'The e-mail cannot have more than 64 characters long.';
}
// El correo electrónico debe tener un formato correcto
if (! preg_match('/[^#\s]{3,}#([-a-z0-9]{3,}\.)+[a-z]{2,}/', trim($_POST['e_mail']))) {
$errors[] = 'The e-mail must have a valid format.';
}
// El país seleccionado debe ser válido
if (! array_key_exists($_POST['country'], $GLOBALS['countries'])) {
$errors[] = 'Please select a valid country.';
}
// La ciudad es necesaria
if (! strlen(trim($_POST['city']))) {
$errors[] = 'The city is required.';
}
// La ciudad no debe contener caracteres problemáticos
if (preg_match('#[^a-zA-Z\- ]#', trim($_POST['city']))) {
$errors[] = 'The city cannot contain invalid characters.';
}
// La ciudad no debe tener menos de 3 caracteres
if (strlen(trim($_POST['city'])) < 3) {
$errors[] = 'The city cannot have less than 3 characters long.';
}
// La ciudad no debe tener más de 64 caracteres
if (strlen(trim($_POST['city'])) > 64) {
$errors[] = 'The city cannot have more than 64 characters long.';
}
// El mes seleccionado debe ser válido
if (! array_key_exists($_POST['month'], $GLOBALS['months'])) {
$errors[] = 'Please select a valid month.';
}
// El día seleccionado debe ser válido
if (! array_key_exists($_POST['day'], $GLOBALS['days'])) {
$errors[] = 'Please select a valid day.';
}
// El año seleccionado debe ser válido
if (! array_key_exists($_POST['year'], $GLOBALS['years'])) {
$errors[] = 'Please select a valid year.';
}
// El nombre real del usuario es necesario
if (! strlen(trim($_POST['real_name']))) {
$errors[] = 'Your real name is required.';
}
// El nombre real del usuario no debe contener caracteres problemáticos
if (preg_match('#[^a-zA-Z\- ]#', trim($_POST['real_name']))) {
$errors[] = 'Your real name cannot contain invalid characters.';
}
// El nombre real del usuario debe tener menos de 3 caracteres
if (strlen(trim($_POST['real_name'])) < 3) {
$errors[] = 'Your real name cannot have less than 3 characters long.';
}
// El nombre real del usuario no debe tener más de 64 caracteres
if (strlen(trim($_POST['real_name'])) > 64) {
$errors[] = 'Your real name cannot have more than 64 characters long.';
}
// El número CAPTCHA introducido debe ser correcto
$captcha_num_1 = substr($_POST['captcha'], 0, 1);
$captcha_num_2 = substr($_POST['captcha'], 1, 1);
$captcha_num_3 = substr($_POST['captcha'], 2, 1);
$captcha_num_4 = substr($_POST['captcha'], 3, 1);
$captcha_num_5 = substr($_POST['captcha'], 4, 1);
if (($_SESSION['num1'] != crypt($captcha_num_1, $_SESSION['num1'])) ||
($_SESSION['num2'] != crypt($captcha_num_2, $_SESSION['num2'])) ||
($_SESSION['num3'] != crypt($captcha_num_3, $_SESSION['num3'])) ||
($_SESSION['num4'] != crypt($captcha_num_4, $_SESSION['num4'])) || ($_SESSION['num5'] != crypt($captcha_num_5, $_SESSION['num5']))) {
$errors[] = 'The CAPTCHA number entered is not correct.';
}
// El nombre de usuario y la dirección de e-mail deben ser únicos en la base de datos
global $db;
$sql = 'SELECT user_name, e_mail FROM users';
$q = mysqli_query($db, $sql);
if (mysqli_num_rows($q) > 0) {
while ($users = mysqli_fetch_object($q)) {
if ($users->user_name == $_POST['user_name']) {
$errors[] = 'This username already exists in the database. Please use a different one.';
}
if ($users->e_mail == $_POST['e_mail']) {
$errors[] = 'This e-mail address already exists in the database. Please use a different one.';
}
}
}
// Si hay errores, resetear el CAPTCHA
if (is_array($errors)) { reset_captcha();
}
return $errors;
}
Please find the following answer
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
//Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$c=0;
if($_POST['firstname']=="")
{
$msg='Please enter firstname';
$c++;
}
if($_POST['lastname']=="")
{
$msg1='Please enter lastname';
$c++;
}
if($_POST['age']=="")
{
$msg2='Please enter age';
$c++;
}
if($c==0)
{
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
mysqli_close($con);
?>
Print $msg,$msg1,$msg2 in respective places

update php database with data of two

I have two tables where I need to display text in a table corresponding to the users of the users table.
So I did this:
$email = $_SESSION['email'];
$select = mysql_query("SELECT t.id, t.id_textos, t.userTitleSite, t.userTextSobre, t.userTextContatos, t.userTextMaisInfos FROM vms_textos t INNER JOIN vms_users u ON (t.id = u.id) LIMIT 1") or print (mysql_error());
while($res_select = mysql_fetch_array($select)){
$userTitleSite = $res_select["userTitleSite"];
$userTextSobre = $res_select["userTextSobre"];
$userTextContatos = $res_select["userTextContatos"];
$userTextMaisInfos = $res_select["userTextMaisInfos"];
$id = $res_select["id"];
and working.
Now i need to update this information straight from the INPUTS..
but I can not do because my field UPDATE must be wrong because it always resets everything after that grip on SUBMIT.
This is the code I'm using. Please see what is wrong:
$query=mysql_query("UPDATE vms_textos SET userTitleSite='$userTitleSite', userTextSobre='$userTextSobre', userTextContatos='$userTextContatos', userTextMaisInfos='$userTextMaisInfos' WHERE t.id=u.id");
Thanks!
[EDIT]
ALL IMPORTANT CODE:
// INCLUDES.PHP
// Starts
ob_start();
session_start();
// Globais
$startaction="";
// Ação
if(isset($_GET["acao"])){
$acao=$_GET["acao"];
$startaction=1;
}
// Conexão com o banco de dados
$conectar=new DB;
$conectar=$conectar->conectar();
// Metodos de Cadastro
if($startaction == 1){
if($acao == "cadastrar"){
$usuario=$_POST["usuario"];
$nome=$_POST["nome"];
$sobrenome=$_POST["sobrenome"];
$telefone=$_POST["telefone"];
$email=$_POST["email"];
$senha=$_POST["senha"];
if(empty($usuario) || empty($nome) || empty($sobrenome) || empty($telefone) || empty($email) || empty($senha)){
$msg="Preencha todos os campos!";
}
// Todos os campos preenchidos
else {
// Email válido
if(filter_var($email,FILTER_VALIDATE_EMAIL)){
// Senha inválida
if(strlen($senha) < 8){
$msg="As senhas devem conter no mínimo oito caracteres!";
}
// Senha válida
else {
// Executa a classe de cadastro
$conectar=new Cadastro;
echo "<div class=\"flash\">";
$conectar=$conectar->cadastrar($usuario, $nome, $sobrenome, $telefone, $email, $senha);
echo "</div>";
}
}
// Email invalido
else{
$msg="Digite seu e-mail corretamente!";
}
}
}
}
// Método de Login
if($startaction == 1){
if($acao == "logar"){
// Dados
$email=addslashes($_POST["email"]);
$senha=addslashes(sha1($_POST["senha"].""));
if(empty($email) || empty($senha)){
$msg="Preencha todos os campos!";
} else{
if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
$msg="Digite seu e-mail corretamente!";
} else {
// Executa a busca pelo usuário
$login=new Login;
echo "<div class=\"flash\">";
$login=$login->logar($email, $senha);
echo "</div>";
}
}
}
}
// Método de Checar usuário
if(isset($_SESSION["email"]) && isset($_SESSION["senha"])){
$logado=1;
$nivel=$_SESSION["nivel"];
}
// LOGIN.PHP -- CLASSE DE LOGIN
class Login {
public function logar($email, $senha){
$buscar=mysql_query("SELECT * FROM vms_users WHERE email='$email' AND senha='$senha' LIMIT 1");
if(mysql_num_rows($buscar) == 1){
$dados=mysql_fetch_array($buscar);
if($dados["status"] == 1){
$_SESSION["email"]=$dados["email"];
$_SESSION["senha"]=$dados["senha"];
$_SESSION["nivel"]=$dados["nivel"];
setcookie("logado",1);
$log=1;
} else{
$flash="Usuário bloqueado! Entre em contato conosco!";
}
}
if(isset($log)){
$flash="Você foi logado com sucesso!";
} else{
if(empty($flash)){
$flash="Ops, digite seu e-mail e sua senha corretamente!";
}
}
echo $flash;
}
}
// CADASTRO.PHP -- CLASSE DE CADASTRO
class Cadastro{
public function cadastrar($usuario, $nome, $sobrenome, $telefone, $email, $senha){
// Tratamento das variaveis
$usuario=ucwords(strtolower($usuario));
$nome=ucwords(strtolower($nome));
$sobrenome=ucwords(strtolower($sobrenome));
$telefone=ucwords(strtolower($telefone));
$email=ucwords(strtolower($email));
$senha=sha1($senha."");
// Inserção no banco de dados
$validaremail=mysql_query("SELECT * FROM vms_users WHERE email='$email' OR usuario='$usuario'");
$contar=mysql_num_rows($validaremail);
if($contar == 0){
$insert=mysql_query("INSERT INTO vms_users(usuario, nome, sobrenome, telefone, email, senha, nivel, status) VALUES('$usuario','$nome','$sobrenome','$telefone','$email','$senha','1','0')");
} else{
$flash="Desculpe, mas já existe um usuário cadastrado com este e-mail em nosso sistema!";
}
if(isset($insert)){
// Cadatro ok
$flash="Cadastro realizado com sucesso, aguarde nossa aprovação!";
} else{
if(empty($flash)){
$flash="Ops, houve um erro em nosso sistema!";
}
}
// Retorno para o usuário
echo $flash;
}
}
$query=mysql_query("UPDATE vms_textos SET t.userTitleSite='$userTitleSite' WHERE t.id='u.id'");
$query=mysql_query("UPDATE vms_textos SET userTitleSite='$userTitleSite' WHERE t.id=u.id");
what field do u want to update in db? SET that particular field in mysql_query(). i mentioned here.. try like this if u set all fields then all fields are updated..

Categories