How to avoid confusion of querys executed at the same time with Php and Mysql?

Asked

Viewed 169 times

1

I have this php function (setBet) that registers the bets in my system based on Betfair, the fact is that I am looking to expand the business and probably some bettor will make a bet at the same time as another. The function below Register first the header of the bet in the table "bet" and with the function Sleep(1) I wait 1 second for the insertion of the query soon after, with the function SELECT MAX(id) I select the id I just registered to use in the foreignkey of the table "bet_matches" who registers which match the customer bet, and the id of his bet.

MY PROBLEM : by using the Sleep(1) function and the MAX(id) I will definitely have some problem in the future, mixing bets or something.. so, how can I improve this function ?

public function setBet($punter_name, $punter_phone, $value, $colab_id, $array_match_and_bet)
{
    // Cadastrar Cabeçalho e Pegar ID Aposta
    $query =    "SET TIME_ZONE = '-03:00';";
    $query .= "INSERT INTO bet(id, punter_name, punter_phone, value, colab_id, date_time, possible_prize) values(NULL, '$punter_name', '$punter_phone', '$value', '$colab_id', now(), 0);";
    $data = mysqli_multi_query(Conexao::conectar(), $query) or die(Conexao::conectar());

    // Se Dados For Verdadeiro, Cabeçalho cadastrado
    if ($data){
        // Espera um segundo e Pega o id que acabamos de gerar
        sleep(1);
        $query = "SELECT MAX(id) FROM bet";
        $data = mysqli_query(Conexao::conectar(), $query);
        $line = mysqli_fetch_assoc($data);
        $last_id = $line["MAX(id)"];
        // Hora de cadastrar as partidas selecionadas Bitch
        sort($array_match_and_bet);
        $count = count($array_match_and_bet);
        for ($i=0; $i < $count ; $i++) { 
            $match_and_bet = explode('-', $array_match_and_bet[$i]);
            // var_dump($match_and_bet);
            $id_match = $match_and_bet[0];
            $type_bet = $match_and_bet[1];
            $odd_at_time = $match_and_bet[2];
            // Vetor para ser utilizado no calculo do premio possivel
            $odds[] = $match_and_bet[2];
            $query = "INSERT INTO `bet_matches` SET match_id = $id_match, type_bet = '$type_bet', bet_id = $last_id, datetime_add = now(), odd_at_time = $odd_at_time";
            // var_dump($query);
            $data = mysqli_query(Conexao::conectar(), $query);
            if (!$data) {
                exit();
            }
        }
        // Calcula a cotacao
        $possible_prize = Bet::calcBetPossiblePrize($odds) * $value;
        // Guarda o Premio Possivel
        Bet::setPossiblePrize($possible_prize, $last_id);

        if ($data) {
                header("Location: ../bet_details.php?bet_id=".$last_id."&msg=betMakeSuccess");
            }
            else{
                header("Location: ../bet_details.php?bet_id=".$last_id."&msg=betMakeDuplicate");
            }

    }
    else
        return 0;   
}

EDITED: FOLLOWS MY FUNCTION Connected::()

public static function conectar()
{
    $con = mysqli_connect('localhost', 'root', 'vagrant', 'boleiros') or trigger_error(mysql_error(),E_USER_ERROR);

    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
        //you need to exit the script, if there is an error
        exit();
    }
    return $con;
    // var_dump($con);
}
  • 2

    Because the use of Sleep?

  • Why sometimes there is a delay in the query record, and if the query has not been executed yet when the MAX(id) execution comes, it takes the id of the previous bet, then it covers everything .. pq he registers the new bet next to the previous bet :/

  • Delay da query? 6th

  • a Fleuquer delay in the query record. If the query processing time is 0.4s and the script execution time is 0.2s ? Obviously the script will not get the new id but the id of the previous bet --'

  • 2

    It will, because the php script itself will not advance without the previous step being completed. You would lose all the logic of a program if it were so. Suppose you state that x=1 and then makes y=x+2, obviously for y to be created there needs to be an x...

  • I know what a delay is, I asked why it was not for time to influence since one should only be executed after the other is finished. If this doesn’t happen you should review your structure for your own safety.

  • 2

    @Miguel is right, it doesn’t make sense for the next step to be executed without the previous one being completed.

  • I’ll test it first this way then you’re talking and I’ll come back to give you the feedback

  • 1

    @Yurifoxx by that logic which would assure him that one second was enough?

Show 4 more comments

1 answer

3


It is very important that you store the connection in a variable so that you don’t always connect. I don’t know how you have your connection but try this way:

....
$conn = Conexao::conectar(); 
$query = "SET TIME_ZONE = '-03:00';";
$conn->query($query) or die('Erro na definição da timezone, tente mais tarde');
$query = "INSERT INTO bet (id, punter_name, punter_phone, value, colab_id, date_time, possible_prize) values(NULL, '$punter_name', '$punter_phone', '$value', '$colab_id', now(), 0);";
$data = $conn->query($query) or die('Erro na inserção, tente mais tarde');
$lastId = $conn->insert_id; // aqui guarda este e só este id, desta conecção que inseriu o novo dado

$query = "SELECT * FROM bet WHERE id=" .$lastId;
$data = mysqli_query($conn, $query);
    ....
  • I will test and answer you here ! But beforehand, I already liked your answer !

  • Thanks@Yurifoxx, just try to make sure Conexao::conectar() returns a connection, or I ask you to put the connect() method in the question also to help you with that

  • 1

    I edited a small detail above @Yurifoxx in the statement of $lastId

  • With this script there is no need for Sleep no

  • 1

    You don’t even need the if($data) {, because $date either exists or is die()

  • i could pass the connection by a $con parameter in this case ? and always when I call $con it will reference the same connection or open another ?

  • 1

    Yes, if you store the connection in a variable, everything you do in the database with that connection will only belong to that connection

  • 1

    I edited the die('Erro na inserção, tente mais tarde') upstairs, I don’t know if you ever saw it... but then you’ll get what you wanted, the last id inserted by that connection... I need to have Sleep like this. And then inside the if can change $data = mysqli_query(Conexao::conectar(), $query); for $data = mysqli_query($conn, $query);

  • I came to see I’m implementing now. let’s see if it runs smooth

  • the $con->insert_id; is returning (0) ! why sera ?

  • 1

    You can edit the question and put your way there conectar() sff

  • 1

    Is inserting?

  • ready, edited, edited out

Show 9 more comments

Browser other questions tagged

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