Javascript – Error registering in a PHP, MySQL, Ajax form

I am trying to create an application form with PHP, MySQL and Ajax.

The error is that the user does not register me in the database. I specify all parameters with the appropriate variables, but nothing is registered in the database

I use PDO, it happens that sending the Submit via the button skips errors and I do not understand why, thanks in advance = D

I also use Google Recaptcha, I deleted the secret key for security reasons.
I would appreciate suggestions to improve the safety of the form!

PHP Code:

`

require '../../config.php'; // datos de la base de datos, database data

function isNull($data){
    if (strlen(trim($data)) < 1) {
        return true;
    } else {
        return false;
    }
}

function verifyPassword($pass1, $pass2) {
    if (strcmp($pass1, $pass2) !== 0) {
        return false;
    } else {
        return true;
    }
}

function isEmail($email) {
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return true;
    } else {
        return false;
    }
}

function registerUser($username, $email, $password, $btc_wallet, $user_type){
    global $con;
    $stmt = $con->prepare("INSERT INTO usuarios (username, email, password, btc_wallet, user_type) VALUES(:username, :email, :password, :btc_wallet, :user_type)");
    $stmt->bindParam(':username', $username, PDO::PARAM_STR);
    $stmt->bindParam(':email', $email, PDO::PARAM_STR);
    $stmt->bindParam(':password', $password, PDO::PARAM_STR);
    $stmt->bindParam(':btc_wallet', $btc_wallet, PDO::PARAM_STR);
    $stmt->bindParam(':user_type', $user_type, PDO::PARAM_STR);

    if ($stmt->execute()) {
        return $con->insert_id;
    } else {
        return 0;
    }
}

if (!empty($_POST)) {
    $giveBack = ();
    $user_type = 2;
    $secretKey = "google_secret_key";
    introducir el código aquí
    $username = $_POST('username');
    $btc_wallet = $_POST('wallet');
    $email = strtolower($_POST('email'));
    $clave = $_POST('password');
    $con_password = $_POST('con_password');
    $captcha = $_POST('grecaptcha');

    $search_user = $con->prepare("SELECT * FROM usuarios WHERE username='$username' LIMIT 1");
    $search_user->bindParam(':username', $username, PDO::PARAM_STR);
    $search_user->execute();

    //if (!captcha) $giveBack() = "Por favor, verifica el captcha";
    if (isNull($username) || isNull($btc_wallet) || isNull($email) || isNull($clave) || isNull($con_password)) $giveBack() = "Por favor, completa todos los campos.";
    if (!isEmail($email)) $giveBack() = "Email invalido";
    if (!verifyPassword($clave, $con_password)) $giveBack() = "Las contraseñas no coinciden";
    if ($search_user->rowCount() == 1) {
        # Usuario ya existe, proceder a enviar un mensaje
        $giveBack('usernameError') = "Este usuario ya existe";
        $giveBack('isLogin') = false;
    }

    if (count($giveBack) == 0) {
        $response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$captcha");
        $arr = json_decode($response, TRUE);

        if ($arr('success')) {
            # Creamos el hash para el password
            $password = password_hash($clave, PASSWORD_DEFAULT);

            $register = registerUser($username, $email, $password, $btc_wallet, $user_type);

            if ($register > 0) {
                # Recuperando el id
                $user_id = $con->lastInsertId();
                $_SESSION('user_id') = (int) $user_id;
                $giveBack('redirect') = '';
                $giveBack('isLogin') = true;
            } else {
                $giveBack() = 'Error al registrar';
            }
        } else {
            $giveBack('errorToCheckCaptcha') = 'Error al comprobar el captcha';
        }
    }
    json_encode($giveBack);
} else {
    exit("Fuera de aquí");
}

`

Javascript code:
`

const url = 'http://localhost/faucet_st/api/user/signup/process-signup.php';

var username = document.getElementById("username").value;
var wallet = document.getElementById("btc_wallet").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var con_password = document.getElementById("con_password").value;

var data = {
    username: username,
    wallet: wallet,
    email: wallet,
    password: wallet,
    con_password: con_password,
    grecaptcha: grecaptcha.getResponse()
}

$.ajax({
    type: 'POST',
    url: url,
    data: data,
    dataType: 'json',
})
.done((res) => {
    console.log(res);
})
.fail((e) => {
    console.log(e);
})
.always(() => {});
});

`

I would be grateful if you could help me with this problem. I tried to solve it all day, but I did not find a solution. I will continue to search for a solution, but I look forward to every help from you.

php – doubt between relationships with Laravel and Eloquent

I have the following model with Laravel 5.8

Enter image description here

I have made all the entries and structured the relationships. In my dashboard, I need to list all the reports for a specific user in map form. How could I do that?

So far, I can get all the groups of this user to do this:

$obj = User::with('grupos')->get();

But how can I go to another table and get to the report?
I tried to do something like this:

$obj = User::with('grupos', 'relatorios')->get();

However, the relationship is in another table. I can not list the data

user template

Modelo Usuário:

App namespace;

Use Illuminate Notifications Notifiable.
Use Illuminate Contracts Auth MustVerifyEmail.
Use Illuminate Foundation Auth User as authenticated.

Class User Extended Authenticable
{
Use a reportable;

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = (
    'name', 'email', 'password','cliente_id'
);

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = (
    'password', 'remember_token',
);

/**
 * The attributes that should be cast to native types.
 *
 * @var array
 */
protected $casts = (
    'email_verified_at' => 'datetime',
);

public function client ()
{
return $ this-> belongTo (& # 39; App models Client & # 39;);
}

public function groups () {
return $ this-> belongToMany ("App models Group", "hits");
}
}

php – Post URL Base per category

By default, you can edit the permalink structure in WordPress:

Ideally, you want to have most posts as simple URLs like site / post name. However, some categories, such as events, news, and albums, should include site / category / postname. For a single category, you can easily use:

add_action( 'init', 'custom_rewrite_rules' );
function custom_rewrite_rules() {

    add_rewrite_rule(
        'event/((^/)+)(?:/((0-9)+))?/?$',
        'index.php?category_name=event&name=$matches(1)&page=$matches(2)',
        'top' // The rule position; either 'top' or 'bottom' (default).
    );
}

add_filter( 'post_link', 'custom_permalink', 10, 3 );
function custom_permalink( $permalink, $post, $leavename ) {
  $category = get_the_category($post->ID);
  if (  !empty($category) && $category(0)->slug == "event" ) {
      $permalink = home_url('event/'. $post->post_name);
  }
  return $permalink;
}

Try to use the least amount of code instead of duplicating the functions. want something more dynamic, you decide for:

$postCategory = get_the_category();
$pageSlug = $postCategory(0)->slug;

add_action( 'init', 'custom_rewrite_rules' );
function custom_rewrite_rules() {

    add_rewrite_rule(
        "$pageSlug".'/((^/)+)(?:/((0-9)+))?/?$',
        'index.php?category_name='."$pageSlug".'&name=$matches(1)&page=$matches(2)',
        'top' // The rule position; either 'top' or 'bottom' (default).
    );
}

// rewrites the url from site/post to site/category/name

add_filter( 'post_link', 'custom_permalink', 10, 3 );
function custom_permalink( $permalink, $post, $leavename ) {
  $category = get_the_category($post->ID);
  if (  !empty($category) && $category(0)->slug == "$pageSlug" ) {
      $permalink = home_url('/' . "$pageSlug" . '/'. $post->post_name);
  }
  return $permalink;
}

The dynamic version does not seem to work. It works fine when replacing $ pageSlug with the hard-coded values. Maybe add_rewrite_rule () does not accept values ​​that change? Make sure that the data type is strings. Also note that I need to write a switch () statement so that all other categories will not get a base URL.

PHP – Problem collecting data with Ajax

I'm having a problem trying to get an array of PHP with Ajax. I think it will be easier to understand the code.
This is a javascript function that generates a json and outputs it in a div.

function saveEvaluation(){


var idcompetencesactivitiesresults = document.getElementById('idcompetencesactivitiesresults').value;
var valueaddevaluation = document.getElementById('valueaddevaluation').value;
var addevaluation = document.getElementById('add_evaluation').value;
var idparticipant = document.getElementById('idparticipant').value;
var idobserver = document.getElementById('idobserver').value;
var token = document.getElementById('token').value;
var idcompetenceAv = document.getElementById('idcompetenceav').value;


        var parametros = {
                "idcompetencesactivitiesresults": idcompetencesactivitiesresults,
                "valueaddevaluation" : valueaddevaluation,
                "add_evaluation" : addevaluation,
                "idparticipant" : idparticipant,
                "idobserver" : idobserver,
                "token" : token,
                "idcompentenceAv" : idcompetenceAv
        };
        $.ajax({
                data:  parametros,
                url:   'addEvaluationAjax.php',
                type:  'post',
                success:  function (response) {
                     $('#addevaluation').modal('hide');
                     $('#add_evaluation').val('');
                     console.log(response);
                        var ToJson = JSON.parse(response);
                        console.log(ToJson);
                    //alert("successfully edited score!");
                    if (ToJson.a == '+') {
                    $('.evaluation-strenghts'+idcompetenceAv).fadeIn(1000).html(ToJson.b);
                    $('.alert').hide();
                }else if(ToJson.a == '-'){
                    $('.evaluation-weaknesses'+idcompetenceAv).fadeIn(1000).html(ToJson.b);
                    $('.alert').hide();
                }else{
                    $('.alert').show();
                    $('.alert').fadeIn(1000).html(ToJson.c);
                }}
        });

}

This is the file in PHP that executes the query.

    $query2 = "insert into evaluations_competences_activitiesresults (evaluation, id_competences_activitiesresults, value) values('$evaluation',$id_competences_activitiesresults,'$value') ";
                qry($query2);
                if ($value == '+') {
                    $query3 = "select id_competences_activitiesresults, evaluation, COUNT(*) as qty from evaluations_competences_activitiesresults left join competences_activitiesresults on evaluations_competences_activitiesresults.id_competences_activitiesresults = competences_activitiesresults.id left join activitiesresults on competences_activitiesresults.id_activitiesresults = activitiesresults.id where competences_activitiesresults.idcompetence = $idcompetenceAv and idparticipant = $idparticipant and evaluations_competences_activitiesresults.value = '+' group by evaluation";
                }elseif($value == '-') {
                    $query3 = "select id_competences_activitiesresults, evaluation, COUNT(*) as qty from evaluations_competences_activitiesresults left join competences_activitiesresults on evaluations_competences_activitiesresults.id_competences_activitiesresults = competences_activitiesresults.id left join activitiesresults on competences_activitiesresults.id_activitiesresults = activitiesresults.id where competences_activitiesresults.idcompetence = $idcompetenceAv and idparticipant = $idparticipant and evaluations_competences_activitiesresults.value = '-' group by evaluation"
                    ;
                }else{
                    echo 'oppss, an error here!';
                }
                $result3 = qry($query3);
                while ($row3 = mysqli_fetch_array($result3)) {

                    $r_id = $row3('id_competences_activitiesresults');
                    $r_evaluation = $row3('evaluation');
                    $r_qty = $row3('qty');

                    if ($value == '+') {
                        $sentence = '
  • '.$r_evaluation.'('.$r_qty.')

  • '; $response = array('a' => '+', 'b' => $sentence); echo json_encode($response); }else if($value == '-'){ $sentence = '
  • '.$r_evaluation.'('.$r_qty.')

  • '; $response = array('a' => '-', 'b' => $sentence); echo json_encode($response); }else{ echo 'oppss, an error here!'; } }

    The problem is that if the query contains more than two records, you try to convert the response variable to a JSON object that generates an error. I do not know how to do it to get more than two values. I know i would have to change the php generated by me but i am still very newbie, thank you very much who can help me.

    php – function to convert "path" into regular expression

    This function converts a string as follows:
    /{?lang(2-5):lowercase}/{page(2+):lowercase}/{article}-{id:integer}*.html*
    In the following regular expression:
    @^(?J)/(?:(?P(a-zd-_W){2,5})/)?(?P(a-zd-_W){2,})/(?P

    (wW)*?)-(?P(1-9)*?).*?.html.*?$@
    Ready to be used in a different location preg_match(),

    The basic structure is as follows:

    • Everything is in parentheses ({...})
    • The next character can be one ?to define it as optional
    • Then the name of the "object" arrives
    • In brackets you can specify the length. Lengths can be a single number (to mean "just as long"), an interval (2-5) or an interval without upper limit (2+).
    • You can say the type you want. It can be an integer, a 0-integer, a lowercase letter, a capital letter, and (if not specified) a case.

    This function converts the information there into a regular expression that can be used with preg_match,

     repeated names in capturing groups (the J modifier is only for PHP 7.2+)
        static $regex = '@(?J){
            (?P?)? #defined if it is optional
            (?P(a-z)w*) #item name
            (?:(
                (?P(1-9)d*) # fixed length (default), or minimum length
                (?P
                    + # no maximum length
                    |-(1-9)d* # specific maximum length
                )?
            ))?
            (?:
                # types are used as :
                :(?P
                    (?:0-)?int(?:eger)? # treats as an integer (starting from 0 or 1)
                    |num(?:ber)? # same as 0-int
                    |(lu)c(?:ase)? # (l)ower or (u)pper case
                    |(?:low|upp)er(?:case)? # lower, upper, lowercase, uppercase
                )
            )?
        }
        |(?P
            * # any case insensitive text
        )@x';
    
        // default options
        static $default = array(
            'optional' => '',
            'item' => '*',
            'type' => 'ci',
            'length' => 0,
            'length_max' => 0
        );
    
        // types to be used on {name:type}
        static $types = array(
            '0-int' => 'd',
            'int' => '(1-9)',
            'ci' => '(wW)',
            'lc' => '(a-zd-_W)',
            'uc' => '(A-Zd-_W)',
        );
    
        // alternative names for $types
        static $types_map = array(
            '' => 'ci',
            'integer' => 'int',
            '0-integer' => '0-int',
            'num' => '0-int',
            'number' => '0-int',
            'lcase' => 'lc',
            'lower' => 'lc',
            'lowercase' => 'lc',
            'ucase' => 'uc',
            'upper' => 'uc',
            'uppercase' => 'uc'
        );
    
        // will contain all the into about the {items}
        $items = array();
    
        $format = preg_replace_callback($regex, function($matches)use(&$default, &$types, &$types_map, &$items){
            $item = array_merge($default, $matches);
    
            // the default is to select any text
            if($item('item') === $default('item'))
            {
                $items() = '.*?';
    
                // return %s to be used later with sprintf
                return '%s';
            }
    
            $regex = '(?P<' . $item('item') . '>';
            $piece = isset($types_map($item('type')))
                ? $types($types_map($item('type')))
                : $types($item('type'));
    
            if($item('type') === 'int')
            {
                if($item('length') >= 2)
                {
                    // must subtract 1 from length and length_max to compensate for the (1-9) (1 char) at the beginning
                    $piece .= 'd{' . ($item('length') - 1) . (
                        $item('length_max')
                            ? ',' . (
                                $item('length_max') !== '+'
                                    ? abs($item('length_max') - 1)
                                    : ''
                            )
                            : ''
                        ) . '}';
                }
                else
                {
                    /*
                        if a length exists, it must be lower than 2 (1 char)
                            so, nothing else needs to be done ($piece contains (1-9), which matches 1 char)
    
                        if no length is provided, match all the numbers ahead
                    */
                    $piece .= $item('length') ? '' : 'd*';
                }
            }
            else if($item('length') >= 2 || ($item('length_max') && $item('length_max') !== '+'))
            {
                /*
                    only give it a length specification if and only if the length is 2 or higher
                        or if there's a maximum length
                    this means that (1) and (1+) are skipped, but (1-5) returns {1,5} (regex)
                */
                $piece .= '{' . $item('length') . (
                    $item('length_max')
                        ? ',' . (
                            $item('length_max') !== '+'
                                ? abs($item('length_max'))
                                : ''
                        )
                        : ''
                    ) . '}';
            }
            else if(!$item('length') || ($item('length') === '1' && $item('length_max') === '+'))
            {
                // if no length is specified (or is 1+), it means "all"
                $piece .= '+';
            }
            /*
                length of 1 doesn't need any treatment
                this is because $piece contains the specification for 1 character already
            */
    
            $regex .= $piece . ')';
    
            $items() = $item('optional') ? '(?:' . $regex . ')?' : $regex;
    
            // returns %s to be used with sprintf
            return '%s';
        }, $path);
    
        // all arguments must be in the same array, can't do $format, $items
        $new_regex = call_user_func_array(
            'sprintf',
            array_merge(
                array(preg_quote($format, '@')), // protects special chars, like periods and slashes
                $items
            )
        );
    
        return '@^(?J)' . str_replace(')?/', '/)?', $new_regex) . '$@';
    }
    

    It's pretty complicated and pretty massive.

    I've decided not to implement a memo schema because this feature is part of a larger project and is cached outside.

    This function works, as far as I can tell, as intended.

    Can I improve on this feature?

    8 – HTML field Print Select option in the PHP header of View

    The following code is used in PHP Block of Headers in View Page

    condition('type', 'media')->condition('status', 1);
    $results = $query->execute();
    $year_options = ();
    $print_html = '';
            foreach($year_options as $year_optionI=>$year_optionV){
                //echo '';
                $print_html = $print_html.'';
            }
            //echo  '';
        }
    }
    
    echo $print_html.'