PHP and many other languages have a special construct to combine state an behavior – because that’s what you want. That construct is called an object.
Objects are defined by classes. So you need a class that remembers the current user data (the state) and delivers the parts that you need (the behavior). This can be very simple. Create a new PHP file named UserData.php
and include it right before you register the shortcode.
The content of the file should look similar to this:
namespace WPSE;
class UserData
{
private $user, $sql_u, $sql_p, $sql_db, $sql_ip;
public function __construct( $sql_u, $sql_p, $sql_db, $sql_ip )
{
$this->sql_u = $sql_u;
$this->sql_u = $sql_p;
$this->sql_u = $sql_db;
$this->sql_u = $sql_ip;
}
public function fetch( $atts )
{
if ( empty ( $this->user ) {
$this->fetch_user();
}
return $this->user->{$atts['text']};
}
private function fetch_user()
{
$reg = new \wpdb(
$this->sql_u,
$this->sql_p,
$this->sql_db,
$this->sql_ip
);
$user_id = get_query_var('user');
$this->user = $reg->get_row(
$reg->prepare(
"SELECT * from data_table WHERE url_id=%s",
$user_id
)
);
}
}
And then you register the shortcode with the namespace:
include_once ('UserData.php');
$user_data = new \WPSE\UserData( $sql_u, $sql_p, $sql_db, $sql_ip );
add_shortcode( 'fetch_data', [ $user_data, 'fetch' ] );
Note that this is completely untested. I just want to give you an idea on how to handle cases like this one.
Also, welcome to WordPress Stack Exchange! 🙂