I'm trying to UPDATE multiple rows of my DB, but it UPDATE only the last row.
I got all DATA from database and fill the SELECT OPTION MULTIPLE:
<select name="numerosdasorte[]" class="form-control" multiple="">
<?php
$consulta = $PDO->query("SELECT * FROM cota1 WHERE status = '0' ORDER BY cota ASC");
while ($linha = $consulta->fetch(PDO::FETCH_ASSOC)) {
?>
<option value="<?php echo $linha['cota']; ?>"><?php echo $linha['cota']; ?></option>
<?php } ?>
</select>
I got these numbers and I put ',' before save data:
$numerosdasorte = '';
foreach ($_POST['numerosdasorte'] as $numeros) {
$numerosdasorte .= ',' . $numeros;
}
$numerosdasorte = ltrim($numerosdasorte, ',');
I INSERT the data on DATABASE. It works like I want:
$sql = "INSERT INTO users SET name = :name, email = :email, password = :password, endereco = :endereco, numero = :numero, bairro = :bairro, cep = :cep, cidade = :cidade, estado = :estado, telefonefixo = :telefonefixo, telefonecelular = :telefonecelular, datadenascimento = :datadenascimento, cpfcnpj = :cpfcnpj, rg = :rg, numerosdasorte = :numerosdasorte";
Now, I got the problem: I need to get the number that was picked in the form to change this status. All the numbers picked, I need to change to '1'. All the numbers picked needs to be unavailable:
$exploded = explode(",", $numerosdasorte);
foreach( $exploded as $key => $value ) {
$query = "UPDATE cota1 SET status = '1' WHERE cota = $value";
$stmt = $PDO->prepare($query);
}
The problem is, the only row affected is the last. If I choice 5 numbers, for example (001, 002, 003, 004 and 005), only the last number (005) will be affected and changed to '1'.
COMPLETE CODE:
<?php
require '../config.a/conexao.php';
$name = $_POST['name'];
$email = $_POST['email'];
$password = md5(uniqid(""));
$endereco = $_POST['endereco'];
$numero = $_POST['numero'];
$bairro = $_POST['bairro'];
$cep = $_POST['cep'];
$cidade = $_POST['cidade'];
$estado = $_POST['estado'];
$telefonefixo = $_POST['telefonefixo'];
$telefonecelular = $_POST['telefonecelular'];
$datadenascimento = $_POST['datadenascimento'];
$cpfcnpj = $_POST['cpfcnpj'];
$rg = $_POST['rg'];
$numerosdasorte = '';
foreach ($_POST['numerosdasorte'] as $numeros) {
$numerosdasorte .= ',' . $numeros;
}
$numerosdasorte = ltrim($numerosdasorte, ',');
$sql = "INSERT INTO users SET name = :name, email = :email, password = :password, endereco = :endereco, numero = :numero, bairro = :bairro, cep = :cep, cidade = :cidade, estado = :estado, telefonefixo = :telefonefixo, telefonecelular = :telefonecelular, datadenascimento = :datadenascimento, cpfcnpj = :cpfcnpj, rg = :rg, numerosdasorte = :numerosdasorte";
$stmt = $PDO->prepare($sql);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $password);
$stmt->bindParam(':endereco', $endereco);
$stmt->bindParam(':numero', $numero);
$stmt->bindParam(':bairro', $bairro);
$stmt->bindParam(':cep', $cep);
$stmt->bindParam(':cidade', $cidade);
$stmt->bindParam(':estado', $estado);
$stmt->bindParam(':telefonefixo', $telefonefixo);
$stmt->bindParam(':telefonecelular', $telefonecelular);
$stmt->bindParam(':datadenascimento', $datadenascimento);
$stmt->bindParam(':cpfcnpj', $cpfcnpj);
$stmt->bindParam(':rg', $rg);
$stmt->bindParam(':numerosdasorte', $numerosdasorte);
$exploded = explode(",", $numerosdasorte);
foreach( $exploded as $key => $value ) {
$query = "UPDATE cota1 SET status = '1' WHERE cota = $value";
$stmt = $PDO->prepare($query);
}
$result = $stmt->execute();
if (!$result) {
var_dump($stmt->errorInfo());
} else {
$subjectPrefix = '[Você foi cadastrado na TOP BRASIL]';
$assunto = 'Você foi cadastrado na TOP BRASIL';
$mensagemHTML = '<h3>Parabéns por fazer parte do nosso GRUPO COOPERATIVO!</h3>
<p>Olá <b>' . $name . '</b>, você fez uma ótima escolha! Acompanhe os sorteios e boa sorte! <br> Agora você está habilitado a acompanhar todo o processo por seu PAINEL de cliente. Para acessar, é muito simples: <br> Acesse nosso site (https://topbrasilbr.com.br/painel), digite seu usuário e senha, e pronto! Fique por dentro das novidades! <br><br> Segue seus dados de cadastro:
<p><b>E-mail:</b> ' . $email . ' <br> <b>Senha:</b> ' . $password . '
<p>Para dúvidas, entre em contato conosco, pelo telefone (24) 2252-3196, ou pelo e-mail: contato#topbrasilbr.com.br.
<p>Um grande abraço!
<p><b>Equipe TOP BRASIL</b>
<hr>';
$headers = "MIME-Version: 1.1\r\n";
$headers .= "Content-type: text/html; charset=utf-8\r\n";
$headers .= "From: TOP BRASIL\r\n";
$headers .= 'Cc: contato#topbrasilbr.com.br' . "\r\n";
$headers .= "Return-Path: $email \r\n";
$envio = mail($email, $assunto, $mensagemHTML, $headers);
if ($envio)
echo "<script>alert('Cadastro realizado com sucesso!'); window.top.location.href = 'index.php';</script>";
}
exit;
?>
For your first insert query, you never execute it. No records are being created. For the second, you're preparing a statement over and over again with different values, but you only execute once at the end of it all. One of the primary reasons for using a prepared statement is so that you DO NOT put the user data directly into the SQL, as you are doing.
In addition to all that, your whole script can be shortened considerably.
<?php
require '../config.a/conexao.php';
// I don't know what you're doing here, but it's not good
$_POST["password"] = md5(uniqid(""));
// here just turn post into your parameters by prefixing key with :
foreach ($_POST as $k=>$v) {
$params[":$k"] = $v;
}
// this is a special case, but the fact that it's here means
// your database structure is no good and needs normalizing
$params[":numerosdasorte"] = implode($_POST["numerosdasorte"], ',');
// prepare the statement
$stmt = $PDO->prepare(
"INSERT INTO users SET name = :name, email = :email, password = :password, endereco = :endereco, numero = :numero, bairro = :bairro, cep = :cep, cidade = :cidade, estado = :estado, telefonefixo = :telefonefixo, telefonecelular = :telefonecelular, datadenascimento = :datadenascimento, cpfcnpj = :cpfcnpj, rg = :rg, numerosdasorte = :numerosdasorte"
);
// no need to bind parameters, just include them as an array in the execution
$result = $stmt->execute($params);
// again, prepare a statement
$stmt = $PDO->prepare("UPDATE cota1 SET status = 1 WHERE cota = ?");
foreach($_POST["numerosdasorte"] as $value ) {
// execute it repeatedly
$stmt->execute([$value]);
}
if (!$result) {
// don't show users this stuff
var_dump($stmt->errorInfo());
} else {
// send your email
}
Try where ... in query for the update. I am assuming that $exploded has an array of numbers like [121, 122, 123];
$exploded = explode(",", $numerosdasorte); // holds only numbers in the array
Then you can do something like this:
$query = "UPDATE cota1 SET status = '1' WHERE cota in ($exploded)"; // it is similar to fire query like "UPDATE cota1 SET status = '1' WHERE cota in (121, 122, 123)"
$stmt = $PDO->prepare($query);
In that case, you don't need the foreach loop as you are passing an array directly for update.
Just a quick reference to help you https://www.w3resource.com/mysql/comparision-functions-and-operators/in-function.php
Related
If i don't change at least 1 of the fields values, the update fails.
Insert works ok.
My git
https://github.com/emerson-cs-santos/TSI-PI_2-2019/blob/master/PHP/novo_user.php
If i keep doing this:
$status = $status . ' ';
works, but it's sound me the right solution
-- MYSQL --
CREATE DATABASE IF NOT EXISTS SENAC_PI;
USE SENAC_PI;
CREATE TABLE IF NOT EXISTS USUARIOS
(
codigo INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY
,nome VARCHAR(20) NOT NULL
,senha VARCHAR(200) NOT NULL
,tipo VARCHAR(20) NOT NULL
)
;
-- PHP --
<?php
// Open a Connection to MySQL
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "SENAC_PI";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
echo 'errado';
return;
}
$query = 'use SENAC_PI';
$result = $conn->query($query);
$codigo = 0;
$login = 'teste';
$senha = '123';
$status = 'Ativo';
$query =
" INSERT INTO USUARIOS ( codigo, nome, senha, tipo ) Values (?, ?, ?, ?)";
$querytratada = $conn->prepare($query);
$querytratada->bind_param("isss",$codigo,$login,$senha,$status);
$querytratada->execute();
if ($querytratada->affected_rows > 0)
{
$resposta = 'ok';
}
else
{
$resposta = 'erro';
}
-- update
$query =
" UPDATE USUARIOS SET nome = ? ,senha = ? , tipo = ? where codigo = ? ";
$querytratada = $conn->prepare($query);
$querytratada->bind_param("sssi",$login,$senha,$status,$codigo);
$querytratada->execute();
if ($querytratada->affected_rows > 0)
{
$resposta = 'ok';
}
else
{
$resposta = 'erro';
}
}
?>
If i don't change at least 1 of the fields values, then query returns: affected_rows = 0
Thanks to Nigel, i managed to verif the result.
I was using "affected_rows" to valid for errors, but if the user doesn't change something, my code will return as an error.
Using "Rows matched" and "Warnings", i can make sure that my query doesn't have errors.
My final code for the problem:
preg_match_all ('/(\S[^:]+): (\d+)/', $conn->info, $querytratada);
$info = array_combine ($querytratada[1], $querytratada[2]);
// Linhas encontradas com base na condição da where
$linhas_encontradas = $info['Rows matched'];
// Linhas que foram alteradas, quando os dados não forem alterados, mesmo o comando estando certo, não é retornado linhas afetadas
$linhas_afetadas = $info['Changed'];
// Avisos de problemas
$avisos_problemas = $info['Warnings'];
//if ($querytratada->affected_rows > 0)
if ($linhas_encontradas == '1' and $avisos_problemas == '0')
{
$resposta = 'ok';
}
else
{
$resposta = 'erro';
}
Anyway, thanks again Nigel!
I have encountered an error and I do not know what is wrong with my code. Can someone help me?
Error: UPDATE users SET voornaam = Test, achternaam = Test2, mail = test#test.com, tel = ,adres = , geslacht = man, bestuur = 0, tc = 0, ic = 0, jec = 0, rvr = , instructeur = 0, webmaster = 0 WHERE id = 1
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'adres = , geslacht = man, bestuur = 0, tc = 0, ic = 0, jec = 0, rvr = , instruct' at line 1
$id = $_GET['u'];
$sql = "UPDATE users SET voornaam = $voornaam, achternaam = $achternaam,
mail = $mailadres, tel = $tel, adres = $adres, geslacht = $geslacht,
bestuur = $bestuur, tc = $tc, ic = $ic, jec = $jec, rvr = $rvr,
instructeur = $instructeur, webmaster = $webmaster WHERE id = ".$id."";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
You should have something like:
$sql = "UPDATE `users`
SET `voornaam` = '$voornaam',
`achternaam` = '$achternaam',
`mail` = '$mailadres',
`tel` = '$tel',
`adres` = '$adres',
`geslacht` = '$geslacht',
`bestuur` = '$bestuur',
`tc` = '$tc',
`ic` = '$ic',
`jec` = '$jec',
`rvr` = '$rvr',
`instructeur` = '$instructeur',
`webmaster` = '$webmaster'
WHERE id = '".$id."'";
This way you are protected if there are empty fields anywhere. You should also make sure you sanitize all the entries you wish to insert in the database.
You must quote ANY string like 'xxxx' else empty strings are missing and string with spaces are see as 2 strings achternaam= van mueller is wrong but achternaam = 'van mueller' is ok and also achternaam=''
You need add quote ' around the updated value, like
$sql = "UPDATE users SET voornaam = '$voornaam', achternaam = '$achternaam', mail = '$mailadres', tel = '$tel', adres = '$adres', geslacht = '$geslacht', bestuur = '$bestuur', tc = '$tc', ic = '$ic', jec = '$jec', rvr = '$rvr', instructeur = '$instructeur', webmaster = '$webmaster' WHERE id = '".$id."'";
If you are not sure that your variables are set before your query, then check them before you create sql query with isset:
if (!isset($a)) {
$a = ''
}
and put your variables in quote:
$sql = "UPDATE users SET voornaam='$voornaam', achternaam='$achternaam',
mail='$mailadres', tel='$tel', adres='$adres', geslacht='$geslacht',
bestuur='$bestuur', tc='$tc', ic='$ic', jec='$jec', rvr='$rvr',
instructeur='$instructeur', webmaster='$webmaster' WHERE id='".$id."'";
I got a problem with PDO...
I have this code:
<center>
<?php
/*
$payid = $_GET["payid"];
$data = mysql_connect('localhost','cheapacc_ross2','dsaikoepwq2312','cheapacc_account');
mysql_select_db('cheapacc_account',$data);
$pay1 = mysql_query("SELECT ID,Categorie,Naam,Email,md5_ID FROM acount_Betalingen WHERE md5_ID = '".$payid."' ");
$pay = mysql_fetch_object($pay1);
if($pay){
echo 'betaling is gelukt';
}else{
echo 'Oops jij liegt ons voor?? '.$pay->md5_ID .mysql_error();
}
*/
$flag=0;
require_once '../../include/config.php';
require_once '../../include/processes.php';
$Login_Process = new Login_Process;
$Login_Process->check_status($_SERVER['SCRIPT_NAME']);
$type = base64_decode($_GET["t"]);
$amount = (int)base64_decode($_GET["a"]);
$host = "localhost";
$username = "root";
$password = "20101998";
$dbname = "ross23";
try
{
$db = new PDO("mysql:host=" . $host . ";dbname=" . $dbname, $username, $password);
}
catch(PDOException $e)
{
exit("Error database connection. E: " . $e);
}
$info = $_SESSION['info'];
if(!isset($_GET["t"]) || !isset($_GET["a"]) || !isset($_GET["h"]) || sha1(md5($info)) != $_GET["h"])
{
exit("1: FOUT! / You may not change the url, or you get a ip ban!");
}
if(isset($_GET["t"]) && isset($_GET["a"]) && isset($_GET["h"]) && sha1(md5($info)) == $_GET["h"])
{
$q = $db->query("SELECT COUNT(*) FROM account_" . $type . " ");
$count = $q->fetchColumn();
if($count < $amount)
{
die("Er zijn te weinig accounts voor jouw betaling, meld dit aan de administrator!");
}
for($i = 0; $i < $amount; $i++)
{
$flag=0;
$getid = $db->prepare("SELECT id FROM account_".$type." WHERE used = ?");
$getid->execute( array('0') );
$pid = $getid->fetch();
if($pid[0] == null)
{
exit("Er zijn geen accounts over, meld dit aan de administrator!");
}
$id = $pid[0];
$stmt = $db->prepare("SELECT * FROM account_" . $type . " WHERE id = ? AND used = ?");
$stmt->execute( array($id, '0') );
$result = $stmt->fetch();
if(!$result)
{
exit("2: FOUT! / You may not change the url, or you get a ip ban.");
}
$userinfo = $db->prepare("SELECT userid FROM cw_users WHERE info = ?");
$userinfo->execute( array($info) );
$userinfo = $userinfo->fetch();
$sql = $db->prepare("INSERT INTO account_lijst SET user_id = ? WHERE account = ?");
$sql->execute(array($userinfo[0], $result));
$user_id = $_SESSION['userid'] ;
// query
$sql = "INSERT INTO account_lijst (user_id,soort) VALUES (:user_id,:soort)";
$q = $db->prepare($sql);
$q->execute(array(':author'=>$user_id,
':title'=>$type));
$account_info = explode(":", $result[1]);
$html = "Account Username: " . $account_info[0] . "<br />";
$html .= "Account Password : " . $account_info[1];
$html .= "<br /><br />";
$flag = 1;
if ($flag==1){
$sql = $db->prepare("UPDATE account_" . $type . " SET used = ? WHERE ID = ?");
$sql->execute( array("1", $id) );
echo $html;
}
echo 'test';
}
}
The most of the part works but by INSERT INTO account_lijst
It doesn't works...
But i checked everything but i think everything is fine:S...
Can someone help me with this code please?
*EDIT SQL
CREATE TABLE IF NOT EXISTS `account_lijst` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`account` text NOT NULL,
`date` text NOT NULL,
`soort` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
On your query :
$sql = $db->prepare("INSERT INTO account_lijst SET user_id = ? WHERE account = ?");
$sql->execute(array($userinfo[0], $result));
Try that instead :
$sql = $db->prepare("INSERT INTO account_lijst SET user_id = :user_id WHERE account = :account");
$sql->bindValue(':user_id', $userinfo['0']);
$sql->bindValue(':account', $result);
$sql->execute();
Should work perfectly if the parameters you gave are the good ones?
If you it doesn't can you please dump the parameters used into the query and the table's structure so we can debug deeper? :)
Check your code i guess (probably) there is an error near of this line due to the way you wrote the where clause:
$userinfo = $db->prepare("SELECT userid FROM cw_users WHERE info = ?");
Try this instead:
$userinfo = $db->prepare("SELECT userid FROM cw_users WHERE info = ' ? ' ");
As well in your insert you should use simple apostrophe in ordert o execute that insert:
$sql = $db->prepare("INSERT INTO account_lijst SET user_id = ? WHERE account = ?");
Hope it heps!!
I have an script that sometimes takes more than 40 seconds to run. But the microtime thing returns less thatn 1 second.
First issue is WHY IS THIS TAKING SO LONG???? and second issue is why microtime don't return time correctly?
<?
$inicio = microtime(true);
session_start();
header('Content-Type: text/html; charset=utf-8');
include 'coneccion-base-mails.php';
include 'coneccion.php';
include 'funciones.php';
$id = $_POST["id"];
//recuperamos los datos del envio
$R = $mysqli->query("SELECT * FROM envios WHERE id=".$id."")->fetch_array();
$remitente = $R["remitente"];
$lista = $R["lista"];
$asunto = $R["asunto"];
$cuerpo = $R["cuerpo"];
$sustituto = $R["sustituto"];
$contactos = array();
//ahora creamos cargamos la lista
if($lista=="Todos"){
$result = $mysqli->query("SELECT * FROM listas WHERE usuario='".$_SESSION["usuario"]."'");
while($R = $result->fetch_array()){
$dato = array($R["nombre"],$R["apellido"],$R["mail"]);
array_push($contactos,$dato);
}
}
else{
$result = $mysqli->query("SELECT * FROM segmentos WHERE titulo='".$lista."' and usuario='".$_SESSION["usuario"]."'");
$R = $result->fetch_array();
$idsegmento = $R["id"];
$result = $mysqli->query("SELECT * FROM listasegmentos WHERE idsegmento=".$idsegmento."");
while($R = $result->fetch_array()){
$dato = array(nombreContacto($R["idcontacto"]),apellidoContacto($R["idcontacto"]),mailContacto($R["idcontacto"]));
array_push($contactos,$dato);
}
}
//ya tenemos los contactos,
//ahora los recorremos uno a uno, fijandonos si ya fue enviado ese mail, si fue enviado vamos al siguiente, sino lo mandamos y cortamos.
$total = count($contactos);
$mm = 0;
if( mailsEnviadosEstaHora() < $limiteMailsPorHora){
foreach($contactos as $contacto){
$nombre = $contacto[0];
$apellido = $contacto[1];
$mail = $contacto[2];
if(mailEnviado($mail)=="no"){
if(strpos($mail,";")===false){
enviarMail($nombre." ".$apellido." <".$mail.">",$mail,$nombre);
}
else{
$mails = explode(";",$mail);
$comp = "";
foreach($mails as $mailss){
if($comp == ""){
$comp = $nombre." ".$apellido." <".$mailss.">";
}
else{
$comp .= ",".$nombre." ".$apellido." <".$mailss.">";
}
}
enviarMail($comp,$mail,$nombre);
}
break;
}
else{
$mm++;
}
}
if($mm == $total){
$mysqli->query("UPDATE envios SET estado='enviada' WHERE id=".$id."");
echo "actualizar";
}
}
else{
//se llego al limite de mails por hora
echo "limite";
}
function marcarEnviado($mail){
global $mysqli;
global $id;
global $remitente;
global $lista;
global $asunto;
global $cuerpo;
global $mm;
global $total;
global $inicio;
$fecha = date("Y")."-".date("m")."-".date("d");
$mysqli->query("INSERT INTO procesoenvio (idenvio,destinatario,estado,fecha,hora,solohora) VALUES (".$id.",'".$mail."','enviado','".$fecha."','".date('H:i:s')."','".date('H')."')");
$caca = $mm+1;
echo $caca." / ".$total;
$actual = microtime(true);
$totalsss= $actual- $inicio;
echo 'Tiempo : '.$totalsss.' segundos<br>';
}
function enviarMail($para,$mail,$nombre){
global $mysqli;
global $id;
global $remitente;
global $lista;
global $asunto;
global $cuerpo;
global $sustituto;
if($nombre==''){
$nombre = $sustituto;
}
//from
$from = array();
$_datos = explode("<",$remitente);
$_nombre = trim($_datos[0]);
$_mail = $_datos[1];
$_mail = trim(str_replace(">","",$_mail));
$from[$_mail] = $_nombre;
$cuentas = explode("---",$_SESSION['correo']);
foreach($cuentas as $cuenta){
$correo = explode("|||",$cuenta);
$username = $correo[0];
$password = $correo[1];
if($username == $_mail){
break;
}
}
//
require_once 'swiftmailer-master/lib/swift_required.php';
// Create the mail transport configuration
$transport = Swift_SmtpTransport::newInstance("mail.dxxxxxxxxxxx.com",25);
$transport->setUsername($username);
$transport->setPassword($password);
// Create the message
$message = Swift_Message::newInstance();
$destinatarios = explode(",",$para);
$destin = array();
foreach($destinatarios as $destinatario){
$s = strpos($destinatario,"<");
if($s===false){
array_push($destin,$destinatario);
}
else{
$_datos = explode("<",$destinatario);
$_nombre = trim($_datos[0]);
$_mail = $_datos[1];
$_mail = trim(str_replace(">","",$_mail));
$destin[$_mail] = $_nombre;
}
}
$message->setTo($destin);
$message->setSubject($asunto);
$message->setFrom($from);
// adjuntos!!!
$ruta = '../../panel/envios/adjuntos/' . $id . '/'; // Relative to the root
if(file_exists($ruta)){ // Abrir archivos
$n = 0;
$archivos = array();
foreach (new DirectoryIterator($ruta) as $file) {
if($file->isDot()) continue;
array_push($archivos,$file->getFilename());
}
sort($archivos);
foreach($archivos as $archivo){
$message->attach(Swift_Attachment::fromPath('http://xxxxxxxxxxxxxxxxxxxx.com'.str_replace('../../','/',$ruta).str_replace(' ','-',$archivo)));
$n+=1;
//break;
}
if($n==0){
//no hay fotos en la carpeta
}
}
$cuerpoPersonalizado = str_replace('[[[Nombre]]]',$nombre,$cuerpo);
$message->setBody($cuerpoPersonalizado,'text/html');
$msg = $message->toString();
$msg = str_replace('http://xxxxxxxxxxxx.com/img.php?i','#',$msg);
$verificacion = base64_encode($id.'|||'.$mail);
$cuerpoPersonalizado = str_replace('numeroidentificacion',$verificacion,$cuerpoPersonalizado);
$message->setBody($cuerpoPersonalizado,'text/html');
// Send the email
$mailer = Swift_Mailer::newInstance($transport);
//$mailer->send($message) or die($msg);
$mailer->send($message);
marcarEnviado($mail);
$hostname = '{localhost:143}Sent Items';
$conn = imap_open($hostname,$username,$password) or die('No se pudo conectar con: usuario: '.$username.' y clave: '.$password.' ' . imap_last_error());
imap_append($conn, '{localhost:143}Sent Items', $msg, "\\Seen") or die("error");
}
?>
As an important tangent to your question, please ensure you cleanse your data - those $_POSTs are wide open for SQL injection:
Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection?
Think about using PDO prepared statements. It's more secure (helps prepare statements against SQL injection) and makes transactions easy (for several repeated queries).
As for your answer, I think you are misunderstanding what microtime() returns. I've included a link to format the number of microseconds in the way you may expect.
php microtime() format value
i did it my way because i'm very bad getting results from two tables...
Basically, first i get all the id items that correspond to the user, and then i calculate the ratings of each item.
But, there is two different types of object item, so i do this 2 times: show you:
function votos_usuario($id){
// $previa = "SELECT id FROM preguntas WHERE id_usuario = '$id'";
// $r_previo = mysql_query($previa);
// $ids_p = '0, ';
// while($items_previos = mysql_fetch_array($r_previo)){
// $ids_p .= $items_previos['id'].", ";
// //echo "ids pregunta usuario: ".$items_previos['id']."<br>";
// }
// $ids = substr($ids_p,0,-2);
// //echo $ids;
//
// $consulta = "SELECT valor FROM votos_pregunta WHERE id_pregunta IN ( $ids )";
// //echo $consulta;
//
// $resultado = mysql_query($consulta);
// $votos_preguntas = 0;
// while($voto = mysql_fetch_array($resultado)){
// $votos_preguntas = $votos_preguntas + $voto['valor'];
// }
$votos_preguntas= 0;
$votos_preguntas = mysql_query("SELECT SUM(valor) FROM votos_pregunta WHERE id_pregunta IN (SELECT id FROM preguntas WHERE id_usuario = '$id')");
$previa_r = "SELECT id FROM recetas WHERE id_usuario = '$id'";
$r_previo_r = mysql_query($previa_r);
$ids_r = '0, ';
while($items_previos_r = mysql_fetch_array($r_previo_r)){
$ids_r .= $items_previos_r['id'].", ";
//echo "ids pregunta usuario: ".$items_previos['id']."<br>";
}
$ids = substr($ids_r,0,-2);
$consulta_b = "SELECT valor FROM votos_receta WHERE id_receta IN ( $ids )";
//echo $consulta;
$resultado_b = mysql_query($consulta_b);
$votos_recetas = 0;
while($voto_r = mysql_fetch_array($resultado_b)){
$votos_recetas = $votos_recetas + $voto_r['valor'];
}
$total = $votos_preguntas + $votos_recetas;
return $total;
}
As you can si this is two much.. O(n^2)
Feel like thinking?
thanks!
You can do this for both:
$votos_preguntas = mysql_query("SELECT SUM(valor) FROM votos_pregunta WHERE id_pregunta IN (SELECT id FROM preguntas WHERE id_usuario = '$id')");
If votos_pregunta and votos_rectas have the same structure, I would only have it as one table with a newly added type column that could be either rectas or preguntas. Then you need to only do one statement for $total.