Insert into field in mysql

Asked

Viewed 103 times

0

I have a system where have registered matches and the logged user tries to hit the results of these matches, Each match has a registration id that is with the name (game) in the database, I already have an if and I if he hits or misses the score, However I can’t make that if he hits or misses insert in the bank in the field result if he Won or Lost, I tried with an UPDATE inside the if and Else but when I give an UPDATE he is updating all results, like he plays Victory for all bets. Follow the betting code...

bet php.

<?php
session_start();
include_once("../conn/conexao.php");
if(!empty($_SESSION['email'])){

}else{
   echo"<script language='javascript' type='text/javascript'>alert('Aréa Restrita.');
   window.location.href='/bolao/index.php';</script>";
}

$nome=$_SESSION['nome'];
$email=$_SESSION['email'];
$saldo="SELECT * FROM tb_usuario WHERE email= '$email'";
$exe= mysqli_query($conexao, $saldo);
$linha = mysqli_fetch_array($exe);

$btnApostar = filter_input(INPUT_POST, 'btnApostar', FILTER_SANITIZE_STRING);
if($btnApostar){
   include_once ("../conn/conexao.php");
   $dados = filter_input_array(INPUT_POST, FILTER_DEFAULT);

   $aposta = "INSERT INTO tb_aposta(apostacasa, apostafora, valor, data, usuario, jogo)VALUES(
   '".$dados['apostacasa']."',
   '".$dados['apostafora']."',
   '".$dados['valor']."',
   '".$dados['data']."',
   '".$_SESSION['email']."',
   '".$dados['jogo']."'
   )";
   $r_aposta = mysqli_query($conexao, $aposta) or die (mysqli_error($conexao));
   $verificacao = "SELECT * FROM  tb_jogos WHERE jogo=".$dados['jogo'];
   $exe= mysqli_fetch_array(mysqli_query($conexao, $verificacao));
   $email=$_SESSION['email'];
   $saldo=$linha['saldo'];
   $valor=$_POST['valor'];
   // var_dump($exe);
   if (($valor) > ($saldo)){
      echo
      "<script>
      alert('Voce nao possui saldo para realizar a aposta.')
      window.location = 'apostar.php';
      </script>";
   }else{

      if(($dados['apostacasa'] == $exe['placarcasa']) && ($dados['apostafora'] == $exe['placarfora'])){

         $up = mysqli_query($conexao,"UPDATE tb_usuario SET saldo=saldo+'$valor' WHERE email = '$email' ")or die (mysqli_error($conexao));

         echo "<script> alert('Voce acertou, parabéns')
         window.location.href='apostar.php';
         </script>";

      }else{ //se estiver errado irá diminuir o valor apostado

         $up = mysqli_query($conexao,"UPDATE tb_usuario SET saldo=saldo-'$valor' WHERE email = '$email' ")or die (mysqli_error($conexao));

         echo "<script> alert('Voce errou, tente outra partida')
         window.location.href='apostar.php';
         </script>";
      }
   }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
   <meta charset="utf-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel='stylesheet' href='//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css'/>
   <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
   <!-- As 3 meta tags acima *devem* vir em primeiro lugar dentro do `head`; qualquer outro conteúdo deve vir *após* essas tags -->
   <title>Lance Web</title>
   <!-- Bootstrap -->
   <link href="../bootstrap/css/bootstrap.min.css" rel="stylesheet">
   <!-- HTML5 shim e Respond.js para suporte no IE8 de elementos HTML5 e media queries -->
   <!-- ALERTA: Respond.js não funciona se você visualizar uma página file:// -->
   <!--[if lt IE 9]>
   <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
   <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
   <![endif]-->
   <style type="text/css">
   /*Aqui deixa a imagem de fundo responsiva*/
   body{ 
      background: url(../img/principal.png) no-repeat center center fixed; 
      -webkit-background-size: cover;
      -moz-background-size: cover;
      -o-background-size: cover;
      background-size: cover;
   }

   #font{
      color:white;
      font-family: 'Open Sans', sans-serif;
      font-size: 20px;
      text-align: center;
   }

   .img-responsive {
      max-width:250px;
      max-height:150px;
      width: auto;
      height: auto;
   }
   </style>
</head>
<body>
<!-- nav e o menu -->   
<nav class="navbar navbar-inverse">
   <div class="container-fluid">

      <!-- Aqui e como ira aparece em um telefone -->
      <div class="navbar-header">
         <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
            <!-- Aqui no span, são os 3 pontos ao abrir em um telefone -->
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
         </button>
         <a class="navbar-brand" href="index.php">Voltar</a>
      </div>

      <!-- Aqui se edita a parte do saldo -->
      <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
         <ul class="nav navbar-nav">
            <li class=""><a>Saldo&nbsp; R$<?php echo $linha['saldo']; ?><span class="sr-only">(current)</span></a></li>
         </ul>
         <ul class="nav navbar-nav">
            <li class=""><a href="apostar.php">Apostar<span class="sr-only">(current)</span></a></li>
         </ul>
         <ul class="nav navbar-nav">
            <li class=""><a href="historico.php">Histórico<span class="sr-only">(current)</span></a></li>
         </ul>
         <ul class="nav navbar-nav">
            <li class=""><a href="ranking.php">Ranking<span class="sr-only">(current)</span></a></li>
         </ul>
         <ul class="nav navbar-nav">
            <li class=""><a href="loja/loja.php">Loja<span class="sr-only">(current)</span></a></li>
         </ul>
         <!-- Aqui se edita a parte do sair -->  
         <ul class="nav navbar-nav navbar-right">
            <li><a href="sair.php"><i class="glyphicon glyphicon-off"></i></a></li>
         </ul>

      </div><!-- fim da div collapse, ela faz com que abra um menu ao aumentar o site -->
   </div><!-- /.container-fluid -->
</nav>

<!------------------------------------------------------------------------------------------------------------------------>

<?php
include("../conn/conexao.php");
//ORDER BY serve para organizar os dados de acordo com o que voce quiser
$buscar="SELECT *, a.jogo as id_jogo FROM tb_jogos a LEFT JOIN tb_aposta b ON (a.jogo = b.jogo) GROUP BY id_jogo ORDER BY id_jogo DESC";
$exe= mysqli_query($conexao, $buscar) or die ("OCORREU UM ERRO AO MOSTRAR OS DADOS");
//começo da tabela
echo "<br><br><div class='container'>
<table class='table table-inverse'>
<thead>
<tr bgcolor='#222222' align='center'>
<th><font color='white'>Codigo Partida</font></th>
<th><font color='white'>Time Casa</font></th>
<th><font color='white'>Placar</font></th>
<th><font color='white'>Time Fora</font></th>
<th><font color='white'>Placar</font></th>
<th><font color='white'>Lance</font></th>
<th><font color='white'></font></th>
</tr>
</thead>
</div>";


while($linha = mysqli_fetch_array($exe)){
   $desativa_btn = "type='submit'";
   if($linha['usuario'] == $_SESSION['email']){
      $desativa_btn = "disabled='disabled' type='button'";
   }
   echo "<form class='form-group' action='' method='post'>
   <input class='form-control' type='hidden' name='data' id='id_01' readonly>
   <tbody>
   <tr bgcolor='#222222'>
   <td><font color='white'><input type='int' class='form-control' name='jogo' maxlength='1' value=".$linha['id_jogo']." style='text-align: center;' readonly='readonly'></font></td>
   <td><font color='white'>".$linha['casa']."</font></td>
   <td><input type='int' class='form-control' name='apostacasa' maxlength='1' value='' style='text-align: center;'></td>
   <td><font color='white'>".$linha['fora']."</font></td>
   <td><input type='int' class='form-control' name='apostafora' maxlength='1' value='' style='text-align: center;'></td>
   <td><input type='int' class='form-control' name='valor' maxlength='5' value='' style='text-align: center;'></td>
   <td><input ".$desativa_btn." class='btn btn-success submit-botao' type='submit' value='Apostar' name='btnApostar'></td>
   </tr>
   </tbody>
   </form>";
}
?>

<script> // script da data atual...
var today = new Date();
var dy = today.getDate();
var mt = today.getMonth()+1;
var yr = today.getFullYear();
document.getElementById('id_01').value= yr+"-"+mt+"-"+dy;
</script>

<script src='http://code.jquery.com/jquery-2.1.3.min.js'></script>
<script src='//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js'></script>

</body>
</html>
  • You want to "insert" or "update"?

  • 1

    Must be missing an AND in the update WHERE clause. As is the table tb_usuario?

  • It will not be in the table tb_usuario will be in another table tb_bet that has a field result, and the same table where I enter the bet data...

  • @DVD will be inserted in the case... but I already make an entry in this table in the same code

  • In the question you say you want to do an UPDATE. Which is right?

  • The question only has 2 UPDATES and are in the table tb_usuario. I will summon my magical powers to guess the error in your code :)

  • Serious an UPDATE but the Result field is not in tb_usuario is in tb_bet, tb_usuario has the balance of the user and each hit the user receives the amount bet so have the UPDATE in tb_usuario, what I need and that an UPDATE is made on another table that is the tb_bet in the result field that will receive victory if you hit or lose if you miss.

Show 2 more comments

1 answer

1


Put in the if...else where you are updating the balance, the query regarding the UPDATE when the player hits or misses, respectively:

mysqli_query("UPDATE tb_aposta SET resultado='vitoria' WHERE usuario = '$email' AND jogo = '$dados['jogo']'")or die (mysqli_error($conexao));

and

mysqli_query("UPDATE tb_aposta SET resultado='derrota' WHERE usuario = '$email' AND jogo = '$dados['jogo']'")or die (mysqli_error($conexao));

The if would look like this:

if (($valor) > ($saldo)){
   echo
   "<script>
   alert('Voce nao possui saldo para realizar a aposta.')
   window.location = 'apostar.php';
   </script>";
}else{

   if(($dados['apostacasa'] == $exe['placarcasa']) && ($dados['apostafora'] == $exe['placarfora'])){

      $up = mysqli_query($conexao,"UPDATE tb_usuario SET saldo=saldo+'$valor' WHERE email = '$email' ")or die (mysqli_error($conexao));
      mysqli_query("UPDATE tb_aposta SET resultado='vitoria' WHERE usuario = '$email' AND jogo = '$dados['jogo']'")or die (mysqli_error($conexao));

      echo "<script> alert('Voce acertou, parabéns')
      window.location.href='apostar.php';
      </script>";

   }else{ //se estiver errado irá diminuir o valor apostado

      $up = mysqli_query($conexao,"UPDATE tb_usuario SET saldo=saldo-'$valor' WHERE email = '$email' ")or die (mysqli_error($conexao));
      mysqli_query("UPDATE tb_aposta SET resultado='derrota' WHERE usuario = '$email' AND jogo = '$dados['jogo']'")or die (mysqli_error($conexao));

      echo "<script> alert('Voce errou, tente outra partida')
      window.location.href='apostar.php';
      </script>";
   }
}

Suggestion:

Instead of using "victory" and "defeat" as values, try using 1 for "victory" and 0 to "defeat", to dry up your bank, and I think it’s best to work.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.