Another connection within the try
Good afternoon everyone, I have a doubt.
I have a SELECT with PDO. More must be done within another SELECT WHILE to get data for that select, giving it more
Error (Error: There Is Already an active transaction).
If anyone can help me be grateful.
Example code.
t开发者_StackOverflowry{
$this->conex->beginTransaction();
$query = $this->conex->prepare("SELECT idUser FROM usuario WHERE id = :id ORDER BY data DESC LIMIT $pagin, $paginaF");
$query->bindParam(":id", $ID, PDO::PARAM_INT, 20);
$query->execute();
while ($lista = $query->fetch()){
$idUser = $lista['idUser'];
echo "<div id='avatar'>"box::avatar($idUser)."</div>"
}
//Here he works out of WHILE. Inside it does not work...
echo box::avatar($idUser);
$this->conex->commit();
}catch (PDOException $ex) {
echo "Erro: " . $ex->getMessage();
}
public function avatar($idUser){
$idUser = (int) $idUser;
$query = $this->conex->prepare("SELECT avatar FROM login WHERE id = :id LIMIT 1");
$query->bindParam(":id", $idUser, PDO::PARAM_INT, 20);
$query->execute();
while ($avatar = $query->fetch()){
$avatar = $avatar['avatar'];
}
return $avatar;
}
You have to close the cursor before calling for a new transaction. Besides, may I ask why are you creating transactions since you're only doing simple *select*s?
Nested Transactions are not possible (as mentioned by the error message). In the first line, you start one transaction. Within the loop, you call avatar()
, that starts another transaction, which fails, because there is already one.
However, for SELECT
-Queries you dont need transactions at all. Just omit it.
You may also think about JOIN
, so you can handle all in just one Query (and then transactions are really useless).
May not be an answer to the problem for now but this line :
echo "<div id="avatar">".$box = box::avatar($id)."</div>"
is full of errors.
"
aren't escaped.- no
;
at the end. - You're trying to give a value to a variable inside an
echo
. This'll throw an error.
If you don't use the avatar()
function elsewhere, you can do :
try{
$this->conex->beginTransaction();
$query = $this->conex->prepare("SELECT usuario.id as id, login.avatar as avatar FROM usuario, login WHERE usuario.id = :id and usuario.id ORDER BY data DESC LIMIT $pagin, $paginaF");
$query->bindParam(":id", $ID, PDO::PARAM_INT, 20);
$query->execute();
while ($lista = $query->fetch()){
$id = $lista['id'];
$avatar = $lista['avatar']
echo '<div id="avatar">'.$avatar.'</div>';
}
}catch (PDOException $ex) {
echo "Erro: " . $ex->getMessage();
}
精彩评论