check if the day exists or not with the if

Asked

Viewed 181 times

3

I need to check if the day doesn’t exist... do Insert, if yes, update.

I set an example in practice of what I need:

if(ver se existe no banco){ 

.....if(){ 

..........faz insert 
.....} 

}else{ 

.... faz updade 

}

The code I have:

if(!empty($_POST['arrachar'])){     
// Loop to store and display values of individual checked checkbox. 
foreach($_POST['arrachar'] as $selected){   
$string = implode(',', $selected);

preg_match('/(\d{4}-\d{2}-\d{2})/', $string, $dia); 
$dia = $dia[0];
$sq="SELECT Id, arrachar FROM centrodb.marcacao WHERE LOCATE('$dia', arrachar) > 0";;
$r1 = mysqli_query($conn,$sq);
while($rows_cursos = mysqli_fetch_array($r1)) {
    $id_do_registro = $rows_cursos['Id'];
}
if(!$id_do_registro){
if(preg_match('/(\d{4}-\d{2}-\d{2})/', $string)){
$sql="INSERT INTO marcacao (arrachar) VALUES ('".$string."')";
$r = mysqli_query($conn,$sql);

}else{ $sql1 = "UPDATE marcacao SET arrachar = '$string' WHERE Id = '$id_do_registro'";
$rs = mysqli_query($conn,$sql1);
}
}    
}
}

It is not working properly, because it only does Insert once, after having data in the database table does not re-enter and does not update.

I think the problem will be here, if(!$id_do_registro){ because after inserting values into the database does not re-enter or update

This is my html:

$calendar .= "<td bgcolor='#F5F5F5' align='center' data-semana=''><center><font size='2px'/> 
<input type='checkbox' name='arrachar[$year, $month, $day][dia]' value='$year-$month-$day' $marcado_data $disabled> $year-$month-$day <br /> 
<input type='checkbox' name='arrachar[$year, $month, $day][OpcaoA]' value='Peq_Almoço' $marcado_pequeno $disabled> Peq. Almoço <input $disabled type='number' name='arrachar[$year, $month, $day][Qtd]' value='$marcado_pequeno_qtd' style='width:65px; height: 22px' /> <br /> 
<input type='checkbox' name='arrachar[$year, $month, $day][opcaoB]' value='Almoço' $marcado_almoco $disabled> Almoço <input $disabled type='number' name='arrachar[$year, $month, $day][Qtd1]' value='$marcado_almoco_qtd' style='width:65px; height: 22px' /> <br /> 
<input type='checkbox' name='arrachar[$year, $month, $day][opcaoC]' value='Almoço_(Dieta)' $marcado_dieta $disabled> Almoço (Dieta) <input $disabled type='number' name='arrachar[$year, $month, $day][Qtd2]' value='$marcado_dieta_qtd' style='width:65px; height: 22px' /> <br /> 
<input type='checkbox' name='arrachar[$year, $month, $day][opcaoD]' value='Lanche' $marcado_lanche $disabled> Lanche <input $disabled type='number' name='arrachar[$year, $month, $day][Qtd3]' value='$marcado_lanche_qtd' style='width:65px; height: 22px' /><br /> 
<input type='checkbox' name='arrachar[$year, $month, $day][opcaoE]' value='Jantar' $marcado_jantar $disabled> Jantar <input $disabled type='number' name='arrachar[$year, $month, $day][Qtd4]' value='$marcado_jantar_qtd' style='width:65px; height: 22px' /> <br /> 
<input type='checkbox' name='arrachar[$year, $month, $day][opcaoF]' value='Jantar_(Dieta)' $marcado_jantardie $disabled> Jantar (Dieta) <input $disabled type='number' name='arrachar[$year, $month, $day][Qtd5]' value='$marcado_jantardie_qtd' style='width:65px; height: 22px' /> </font></center></td>";

}
  • Forehead without the exclamation: if($id_do_registro) { ...

  • Without the exclamation mark inserting as new lines the ones I should update and inserting the new records I made, the problem at this point is that it does not update

  • Puts echos in various places and see if the variables are correct and where he is entering (if or else), also test the SQL script right in phpMyAdmin or something to make sure that there was no missing or left any letters in some column

  • while($rows_cursos = mysqli_fetch_array($r1)) {&#xA; $id_do_registro = $rows_cursos['Id'];&#xA;} echo $id_do_registro;&#xA;if(!$id_do_registro){ returns 186187188185185188. It is working

  • if(!$id_do_registro){&#xA; echo $id_do_registro;&#xA; echo $string;&#xA;if(preg_match('/(\d{4}-\d{2}-\d{2})/', $string)){ here put these two Texts but does not return anything or inserts

  • Put a echo $id_do_registro before the if

  • while($rows_cursos = mysqli_fetch_array($R1)) { $id_do_registro = $rows_cursos['Id']; } echo $id_do_registro; if(!$id_do_registro){ retorno 186187188185188188.

  • Before the Insert I put these snippets echo $id_do_registro; echo $string; &#xA;$sql="INSERT INTO marcacao (arrachar) VALUES ('".$string."')"; and I detected a problem. The ids of what is already registered in the table are correct in what returns 1822018-04-24,Peq_lunch,10,Lunch,10,,Snack,10,1832018-04-25,,,,,Snack,15,Dinner,15,1842018-04-26,Peq_lunch,12,Lunch,12,,,,1852018-04-27,,,,,Snack,14,Dinner,14, but in the new registration repeats the id as I show 1852018-04-28,Lunch,10,Lunch,10,,,,,, where this id should be 324 which was the id that stayed on the table

  • @Beginner tries the way I did

Show 4 more comments

2 answers

4


You were trying to do UPDATE within the IF which checks whether there is no ID. It will not update because the id does not exist. It is right that this code is in an ELSE of this IF. Like this:

if(!$id_do_registro){ // se não existir id do registro
    // inclua
} else {
   // muda através do id
}

Also, you have the error in your while, also cited by @Ernando.

EDIT

As discussed on chat

Your code will look like this:

if(!empty($_POST['arrachar'])){     
    // Loop to store and display values of individual checked checkbox. 
    $stringSelect = "SELECT SUBSTRING_INDEX(arrachar, ',', 1) as data, Id, arrachar FROM marcacao WHERE ";
    $stringNew = "INSERT INTO marcacao (arrachar) VALUES ";
    $arrayValues = array();
    $statusNew = false;
    foreach($_POST['arrachar'] as $selected){

        $string = implode(',', $selected);
        $vazio = str_replace(",","",$string);
        $date = explode(",",$string);
        $data = $date[0];
        if($vazio != ""){
            $stringSelect .= "SUBSTRING_INDEX(arrachar, ',', 1) = '$data' OR ";
            $arrayValues[] = array(
                "data" => $data,
                "arrachar" => $string
            );
        }

    }
    $stringSelect = substr($stringSelect, 0, -3);
    $r1 = mysqli_query($conn,$stringSelect) or die(mysqli_error($conn));
    $index = array();
    if(mysqli_num_rows($r1) > 0){
        while($rows_cursos = mysqli_fetch_array($r1)){
            for($i=0; $i < count($arrayValues); $i++){
                if($rows_cursos['data'] == $arrayValues[$i]['data']){
                    if($rows_cursos['arrachar'] != $arrayValues[$i]['arrachar']){
                        $id = $rows_cursos['Id'];
                        $strin = $arrayValues[$i]['arrachar'];
                        $sql1 = "UPDATE marcacao SET arrachar = '$strin' WHERE Id = '$id'";
                        $rs = mysqli_query($conn,$sql1) or die(mysqli_error($conn));                        
                    }
                    $index[] = $i;
                }
            }
        }
    }

    if(isset($arrayValues[0])){
        for($i = 0; $i < count($arrayValues); $i++){
            if(!in_array($i,$index)){
                $stringNew .= "('".$arrayValues[$i]['arrachar']."'),";
                $statusNew = true;
            }
        }

        if($statusNew){
            $stringNew = substr($stringNew, 0, -1);
            mysqli_query($conn,$stringNew) or die(mysqli_error($conn));
        }
    }


}
  • Does not insert anything into the database table in this way nor if(!$id_do_registro){ and neither if($id_do_registro){

  • @Beginner tries now

  • It also does not insert in one way or the other, we can talk in the chat to explain better what I want and the idea of what I have there in the code?

  • @Beginner yes... we can

  • 1

    @Beginner worked out well?

3

You have a problem using variables. Check for example that within a while you make an assignment of values in a variable:

while($rows_cursos = mysqli_fetch_array($r1)) {
    $id_do_registro = $rows_cursos['Id'];
}

$id_do_record will always receive the last record of the 'Id' index of the $rows_courses array.

IF is to be simple as put into code but you need the right variables for that.

Possibly you would have to include the IF inside While but without more information about sent parameters there is no way to analyze it better.

See how it would look:

if(!empty($_POST['arrachar'])){     
    // Loop to store and display values of individual checked checkbox. 
    foreach($_POST['arrachar'] as $selected){
        $string = implode(',', $selected);

        preg_match('/(\d{4}-\d{2}-\d{2})/', $string, $dia);
        $dia = $dia[0];
        $sq="SELECT Id, arrachar FROM centrodb.marcacao WHERE LOCATE('$dia', arrachar) > 0";;
        $r1 = mysqli_query($conn,$sq);
        while($rows_cursos = mysqli_fetch_array($r1)) {
            $id_do_registro = $rows_cursos['Id'];
            if(!$id_do_registro){
                if(preg_match('/(\d{4}-\d{2}-\d{2})/', $string)){
                    $sql="INSERT INTO marcacao (arrachar) VALUES ('".$string."')";
                    $r = mysqli_query($conn,$sql);

                }else{ $sql1 = "UPDATE marcacao SET arrachar = '$string' WHERE Id = '$id_do_registro'";
                    $rs = mysqli_query($conn,$sql1);
                }
            }    
        }
    }
}

Enter in the code the logic used that makes it easy to understand what’s going on. The ideal would be to have everything separated with a method that would try to insert the records in the BD. In this method he would receive a record or an array of records (depending on the business) and for each one (within a loop) would make the check if it already exists to update or else does the Insert.

  • we can chat?

  • It didn’t work, with the if(!$id_do_registro){ does not insert anything in the database table, so I changed to if($id_do_registro){ and placed all existing empty lines in the database

Browser other questions tagged

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