How to load grouped mysql data to table in php

I’m trying to build something as chained / bundle products and use these as variations. Here’s my query for loading the products:

$related_query = database::query( 
"select p.*, pi.name
from ". DB_TABLE_PRODUCTS ." p 
left join ". DB_TABLE_PRODUCTS_INFO ." pi on (pi.product_id = p.id and pi.language_code = '". language::$selected['code'] ."') 
where p.main_product = ". $product_id ." 
order by p.color asc;" );

With this query I get results like in this picture:
1
Gray XS, Gray S, and then Pink XS,S,M,L..

But instead I would like to get data sorted like this:
2

Here’s the rest of the code:

<?php foreach($products as $product) echo functions::draw_listing_product($product, 'similar'); ?>

and for listing style:

" data-name="" data-price="">
">
:
'. $quantity_unit['name'] .'
' : ''; ?> </div> </div> </div> <?php echo functions::form_draw_form_end(); ?> </div> </div>

So my question is how to load data to table, using one row per color? Like picture 2.

Advertisements

Add a User Email to a JS file as JSON string

I’m trying to integrate the intercom messenger on my WordPress multisite network using a custom plugin. I can’t use the official plugin because I want it to only load the script for Admin/Editor users and also have it load on the admin pages. (This is so site admins can access our support team that assists the network.)

I have the messenger working properly, but I am having trouble getting it to send user data to intercom so I can know who is messaging our team. Here’s what the intercom documentation says regarding this kind of information:

Things to remember:

  • Key names are case sensitive, and can’t contain periods (‘.’), dollar signs (‘$’), characters like ~`!@#%^&*'{}|\'” or the NULL character.
  • Data values must be sent as JSON strings, numbers or booleans (true or false).
  • We can’t accept object, nested hashes and array data formats.
    Text string values can only hold up to 255 characters.
  • You can clear existing data values by sending empty strings.

So I think I need to pull the user’s email address using a JSON string in my script. I have the script separated into it’s own .js file and I’m calling that from a .php file that contains my conditional statements. Here are those files:

/*
Intercom Multisite Activation
Intercom Role Limiter
*/

// Get User ID
add_filter( 'intercom_settings', function( $settings ) {                                                  
  $settings['user_id'] = $user_id;                
  return $settings;                                                      
} );

// Generate Hash Keys for Users
hash_hmac(
  'sha256', // hash function
  $user->email, // user's email address
  'thiscontainsmysecretkey' // secret key (keep safe!)
);

// Load Intermon on Front End for Administrator or Editor Roles
add_action('wp_enqueue_scripts', 'dgtl_intercom_enqueue');
function dgtl_intercom_enqueue() {
    if ( current_user_can('editor') || current_user_can('administrator') ) {
        wp_enqueue_script(
            'dgtl-intercom',
            plugin_dir_url(__FILE__).'/js/dgtl-intercom.js'
        );
    }
}

// Load Intermon in admin for Administrator or Editor Roles
add_action('admin_enqueue_scripts', 'dgtl_intercom_admin_enqueue');
function dgtl_intercom_admin_enqueue() {
    if ( current_user_can('editor') || current_user_can('administrator') ) {
        wp_enqueue_script(
            'dgtl-intercom',
            plugin_dir_url(__FILE__).'/js/dgtl-intercom.js'
        );
    }
}

And here is my JS file:

var APP_ID = "xxxxxxxx",
CLIENT_EMAIL = "email";

window.intercomSettings = {
    app_id: "APP_ID",
    email: "CLIENT_EMAIL", // Email address
    user_hash: "INSERT_HMAC_VALUE_HERE" // HMAC using SHA-256
};

(function(){var w=window;var ic=w.Intercom;if(typeof ic==="function"){ic('reattach_activator');ic('update',intercomSettings);}else{var d=document;var i=function(){i.c(arguments)};i.q=[];i.c=function(args){i.q.push(args)};w.Intercom=i;function l(){var s=d.createElement('script');s.type='text/javascript';s.async=true;s.src='https://widget.intercom.io/widget/xxxxxxxx';var x=d.getElementsByTagName('script')[0];x.parentNode.insertBefore(s,x);}if(w.attachEvent){w.attachEvent('onload',l);}else{w.addEventListener('load',l,false);}}})()

I think my issue is that I don’t know how to properly call the username into a JSON string. Thank you for the help!

Php mail send not working in localhost

I have set my settings in php.ini and sendmail.ini. Still, this script doesnt work. I havent tried it yet on the real server, where I have my website. Can anyone please tell me why this doesnt work?
My code:

<?php

if(isset($_POST['submit'])){
	$name = $_POST['name'];
	$email = $_POST['email'];
	$subject = $_POST['subject'];
	$message = $_POST['message'] . "\n\n\n\n\n" . "Name: " . $name . "\n" . "Email: " . $email;

	mail('gamanware@gmail.com', $subject, $message);
	header('Location: mailSent.php?mailsend=success&back=' . $back);
	exit;
}
else{
	header('Location: mailSent.php?mailsend=error&back=' . $_GET['back']);
	exit;
}

Nginx Reverse Proxy Rewriting HTTP Response Codes

Full disclosure: I asked this on Server Fault and let it sit for a week without any answers and low views. I’m moving it here as I feel it might be more programming related based on the reception on Server Fault. I’ve flagged the original question on Server Fault for deletion.

I have a PHP application (app-two) that communicates with another PHP application (app-one) via RESTful API requests. Both are behind a nginx reverse proxy. When app-two sends a request to app-one, it makes it to app-one unmodified. The response from app-one, though, comes back consistently with a 200 status code, instead of the status code I’ve programmatically dictated it should. Each app is containerized in their own docker container

Nginx version: 1.9.15

PHP-FPM version: php:7-fpm

Docker: 18.03.0-ce, build 0520e24



It seems to me that nginx is rewriting this request, per what I’m seeing in the logs:

app_one | 172.18.0.6 -  20/Apr/2018:16:30:47 -0700 "POST /index.php" 401
nginx   | 172.18.0.3 - - [20/Apr/2018:23:30:47 +0000] "POST /api/member/SessionManager HTTP/1.1" 200 38 "-" "GuzzleHttp/6.3.2 curl/7.38.0 PHP/7.1.10" "-"
app_two | 172.18.0.6 -  20/Apr/2018:16:30:47 -0700 "POST /index.php" 200
nginx   | 172.18.0.1 - - [20/Apr/2018:23:30:47 +0000] "POST /login/ HTTP/1.1" 200 917 "https://app-two.local/login" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36" "-"

You can see that app_one sends the response with a 401 status code. It gets to nginx and is immediately converted to a 200, which is passed back to app-two.



Here are my *.conf files for app_one, app_two, and the base nginx config. I’ve also attached my docker-compose.yml file.

app_one.conf:

upstream app_one {
        server app_one:9000;
}

server {
        listen 80;
        listen [::]:80;
        server_name app-one.local app-one;
        return 301 https://$server_name$request_uri;
}

server {
        listen 443 ssl;
        listen [::]:443 ssl;
        server_tokens off; 

        ssl on;
        ssl_certificate /etc/nginx/certs/app_one.crt;
        ssl_certificate_key /etc/nginx/certs/app_one.key;
        ssl_dhparam /etc/nginx/certs/dhparam.pem;

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;
        ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
        ssl_ecdh_curve secp384r1;
        ssl_session_cache shared:SSL:10m;
        ssl_session_tickets off;
        resolver 8.8.8.8 8.8.4.4 valid=300s;
        resolver_timeout 5s;

        server_name app-one.local;

        root /var/www/app_one;
        index index.php index.html;

        gzip_types text/plain text/css application/json application/x-javascript
                   text/xml application/xml application/xml+rss text/javascript;

        # Add headers to serve security related headers
        #
        # Disable preloading HSTS for now.  You can use the commented out header line that includes
        # the "preload" directive if you understand the implications.
        # add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
        add_header Strict-Transport-Security "max-age=63072000; includeSubdomains";
        add_header X-Frame-Options DENY;
        add_header X-Content-Type-Options nosniff;
        add_header X-XSS-Protection "1; mode=block";
        add_header X-Robots-Tag none;
        add_header Pragma "no-cache";
        add_header Cache-Control "no-cache";
        add_header X-uri "$uri";

        location ~* \.(eot|otf|ttf|woff|woff2)$ {
                add_header Access-Control-Allow-Origin *;
        }

        location / {
                proxy_read_timeout    90;
                proxy_connect_timeout 90;
                proxy_redirect        off;

                proxy_set_header      X-Real-IP $remote_addr;
                proxy_set_header      X-Scheme $scheme;
                proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header      X-Forwarded-Proto $scheme;
                proxy_set_header      X-Forwarded-Host $server_name;
                proxy_set_header      Host $host;
                proxy_set_header      X-Forwarded-Port 443;
                proxy_set_header      Authorization $http_authorization;
                proxy_pass_header     Authorization;

                proxy_hide_header X-Powered-By;
                proxy_hide_header X-Pingback;
                proxy_hide_header Link;

                try_files $uri $uri/ /index.php?$args;
        }

        # Pass all .php files onto a php-fpm/php-fcgi server.
        location ~ [^/]\.php(/|$) {
                add_header X-debug-message "A php file was used" always;
                # regex to split $uri to $fastcgi_script_name and $fastcgi_path
                fastcgi_split_path_info ^(.+?\.php)(/.*)$;
                # This is a robust solution for path info security issue and 
                # works with "cgi.fix_pathinfo = 1" in /etc/php.ini (default)
                # if (!-f $document_root$fastcgi_script_name) {
                #         return 404;
                # }
                # Check that the PHP script exists before passing it
                # try_files $fastcgi_script_name =404;
                # Bypass the fact that try_files resets $fastcgi_path_info
                # see: http://trac.nginx.org/nginx/ticket/321
                set $path_info $fastcgi_path_info;
                fastcgi_param PATH_INFO $path_info;
                fastcgi_intercept_errors on;
                fastcgi_pass app_one;
                fastcgi_index index.php;
                include fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;

                fastcgi_hide_header X-Powered-By;
                fastcgi_hide_header X-Pingback;
                fastcgi_hide_header Link;
        }

        location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
                add_header X-debug-message "A static file was served" always;
                expires max;
                # log_not_found off;
        }

        location ~ /\. {
                deny all;
        }
}

app_two.conf:

upstream app_two {
        server app_two:9000;
}

server {
        listen 80;
        listen [::]:80;
        server_name app_two.local;
        return 301 https://$server_name$request_uri;
}

server {
        listen 443 ssl;
        listen [::]:443 ssl;
        server_tokens off; 

        ssl_certificate /etc/nginx/certs/app_two.crt;
        ssl_certificate_key /etc/nginx/certs/app_two.key;
        ssl_dhparam /etc/nginx/certs/dhparam.pem;


        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;
        ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
        ssl_ecdh_curve secp384r1;
        ssl_session_cache shared:SSL:10m;
        ssl_session_tickets off;
        resolver 8.8.8.8 8.8.4.4 valid=300s;
        resolver_timeout 5s;

        server_name app_two.local;

        root /var/www/app;
        index index.php index.html;

        gzip_types text/plain text/css application/json application/x-javascript
                   text/xml application/xml application/xml+rss text/javascript;


        # Add headers to serve security related headers
        #
        # Disable preloading HSTS for now.  You can use the commented out header line that includes
        # the "preload" directive if you understand the implications.
        # add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
        add_header Strict-Transport-Security "max-age=63072000; includeSubdomains";
        add_header X-Frame-Options DENY; # prevents page from being embedded in other pages
        add_header X-Content-Type-Options nosniff; # prevents MIME type sniffing
        add_header X-XSS-Protection "1; mode=block"; # prevents XSS rendering
        add_header X-Robots-Tag none; # prevents robots from crawling the requested page
        add_header Pragma "no-cache"; # don't store a cached version of the site resources
        add_header Cache-Control "no-cache"; # don't store a cached version of the site resources
        add_header X-uri "$uri"; # requested URI

        location ~* \.(eot|otf|ttf|woff|woff2)$ {
                add_header Access-Control-Allow-Origin *;
        }

        location / {
                proxy_read_timeout    90;
                proxy_connect_timeout 90;
                proxy_redirect        off;

                proxy_set_header      X-Real-IP $remote_addr;
                proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header      X-Forwarded-Host $server_name;
                proxy_set_header      Host $host;
                proxy_set_header      X-Forwarded-Proto $scheme;
                proxy_set_header      X-Forwarded-Port 443;
                proxy_set_header      Authorization $http_authorization;
                proxy_pass_header     Authorization;

                proxy_hide_header X-Powered-By;
                proxy_hide_header X-Pingback;
                proxy_hide_header Link;

                try_files $uri $uri/ /index.php;
        }

        # Pass all .php files onto a php-fpm/php-fcgi server.
        location ~ [^/]\.php(/|$) {
                # add_header Location "$uri" always;
                # regex to split $uri to $fastcgi_script_name and $fastcgi_path
                fastcgi_split_path_info ^(.+?\.php)(/.*)$;
                # This is a robust solution for path info security issue and 
                # works with "cgi.fix_pathinfo = 1" in /etc/php.ini (default)
                if (!-f $document_root$fastcgi_script_name) {
                        return 404;
                }
                # Check that the PHP script exists before passing it
                try_files $fastcgi_script_name =404;
                # Bypass the fact that try_files resets $fastcgi_path_info
                # see: http://trac.nginx.org/nginx/ticket/321
                set $path_info $fastcgi_path_info;
                fastcgi_param PATH_INFO $path_info;
                fastcgi_intercept_errors on;
                fastcgi_pass app_two;
                fastcgi_index index.php;
                include fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;

                fastcgi_hide_header X-Powered-By;
                fastcgi_hide_header X-Pingback;
                fastcgi_hide_header Link;
        }

        location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
                expires max;
                log_not_found off;
        }
}

nginx.conf:

worker_processes 1;

daemon off;

events {
    worker_connections 1024;
}

error_log   /var/log/nginx/error.log warn;
pid         /var/run/nginx.pid;

http {
    default_type application/octet-stream;
    include /etc/nginx/conf/mime.types;

    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
    '$status $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log main;

    sendfile on;
    #tcp_nopush on;

    keepalive_timeout 65;

    gzip on;
    gzip_disable "msie6";

    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
    application/x-font-ttf ttc ttf;
    application/x-font-otf otf;
    application/font-woff woff;
    application/font-woff2 woff2;
    application/vnd.ms-fontobject eot;

    include /etc/nginx/conf.d/*.conf;   
}

docker-compose.yml:

version: '3.3'
services:
  nginx:
    image: evild/alpine-nginx:1.9.15-openssl
    container_name: nginx
    volumes:
      - ./app:/var/www/app/:ro
      - ./app_one:/var/www/app_one/:ro
      - ./batterystore:/var/www/wp/:ro
      - ./nginx/conf/nginx.conf:/etc/nginx/conf/default.conf:ro
      - ./nginx/conf.d:/etc/nginx/conf.d:ro
      - ./certs:/etc/nginx/certs
    ports:
      - 80:80
      - 443:443
    expose:
      - "80"
      - "443"
    depends_on:
      - php-mp
      - php-wp
    environment: 
      TZ: "America/Los_Angeles"
    networks:
      default:
        aliases:
          - app_one.local
          - app_two.local

  app_one:
    environment: 
      TZ: "America/Los_Angeles"
    image: joebubna/php
    container_name: app_one
    restart: always
    volumes:
      - ./app_one:/var/www/app_one
    ports:
      - 9001:9000
    networks:
      - default

  app_two:
    environment: 
      TZ: "America/Los_Angeles"
    image: joebubna/php
    container_name: app_two
    restart: always
    volumes:
      - ./app_two:/var/www/app_two
    ports:
      - 9000:9000
    networks:
      - default

  db:
    image: mysql:5.6
    container_name: mysql
    volumes:
      - db-data:/var/lib/mysql
      - ./mysql/my.cnf:/etc/mysql/conf.d/ZZ-app_one.cnf:ro
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_USER: user
      MYSQL_PASSWORD: password
      MYSQL_DATABASE: cora
      TZ: "America/Los_Angeles"
    ports:
      - 3306:3306
    expose:
      - "3306"
    networks:
      - default

volumes:
  db-data:

networks:
  default:
    driver: bridge

I’m not sure exactly (A) why nginx isn’t passing the status codes down the pipeline unmodified and (B) how to make it not override what I’ve programmatically set. I’ve read through:

http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files – thinking maybe this is causing an additional redirect that purges the status code after the redirect request.

Which was based on this question: https://serverfault.com/questions/329592/how-does-try-files-work

And prior to that question, this question seemed promising:
https://serverfault.com/questions/793277/nginx-404-handler-in-php-ignores-http-status

Both were equally ineffective in helping me resolve this issue.

Plus this additional question that cropped up in the sidebar while writing this: https://serverfault.com/questions/184573/how-to-make-nginx-reverse-proxy-let-503-error-pages-pass-through-to-client – the problem has persisted even after adding proxy_intercept_errors off; to the location / blocks in app_one.conf and app_two.conf. I’m pretty well stuck at this point. Programmatically it appears sound, so I’m pretty sure the problem is in somewhere in my nginx configurations.

Any guidance would be greatly appreciated. Thank you!

Vuejs Loggin inactivated error on same page

So Im trying to do a login in Vuejs and it woks the only problem is I have a field in my database called activated. It is set to ‘0’ if they are not activated and ‘1’ if they have been activated. I’m using the session to log them in if their password is found in my database. I also a variable called $_SESSION[‘activated’] and set that to the value of activated in the users account. And than assign that to a variable in the Vue’s data attribute. I want it to display a green button that says resend email and a red error that says ‘Please activate your account before logging in. It works but the problem is when they click submit it displays for a second even if their password is right and than quickly logs them in. Any ideas on how to fix this problem.

Heres the code for the vue app

    <?php ob_start();
session_start();
if(isset($_SESSION['activated']) && $_SESSION['activated']==0){
$activated=0;} if(isset($_SESSION['activated']) and $_SESSION['activated']==1){$activated=1;}
if(!isset($_SESSION['activated'])){$activated=0;} 
if(isset($_SESSION['success']) and $_SESSION['success']==1){$success=1;} else {$success=0;}
$indexStyle;
if(basename($_SERVER['PHP_SELF']) == 'index.php') {
  $indexStyle = 'style="background-color:unset !important;"';
}
?>

<header class="compactHeader" <?php echo $indexStyle; ?>>
  <a href="index.php">
    
    
CreativeEngine
</a>
Login
<a class="compactAccountsItem" v-show="success==1" href="logout.php">Logout</a>

Log In

Username

Password

Username or password was incorrect...Try again
= 8 && password.length >= 8 && activated==0 && error==0">Please login to your email and activate your account
</div>
</div> <a href="signup.php">
Sign Up
</a> </div>
Stock
<a href="templates.php">
Templates
</a>
About
</div> </header> var app = new Vue({ el: '#logIn', data: { userName: '', password: '', success:'', error:'', activated: '', link: 'resendsignupemail.php?userName=', showPopUp:'', loginsub: '', response:[], sesusername:'', sesemail:'', sesloggedin:'', sesfirstname:'', seslastname:'', }, created: function() { this.showPopUp=false; this.loginsub=0; }, methods: { popUp: function() { this.showPopUp = !this.showPopUp; }, submit: function() { this.loginsub=1 if(this.userName.length >= 8 && this.password.length >= 8) { var jsonString = JSON.stringify({ userName: this.userName, password: this.password }); $.ajax({ url: "login.php", method: "POST", dataType: "JSON", data: jsonString, success: function(data){ var vueapp= this; vueapp.response=data; vueapp.error=data.error; vueapp.showPopUp=data.showPopUp; if(data.success==1){location.reload();} console.log(data); // this.popUp(); }.bind(this) }); } } } });

Heres the code for login.php the page the ajax call goes to

<?php session_start();
$dbpass='';
  require_once('database.php');
  require_once('functions.php');
  $requestBody = file_get_contents('php://input');
  $requestJSON = json_decode($requestBody);
  $username = $requestJSON->userName;
  $username = mysqli_real_escape_string($mysqli, $username);
  $password = $requestJSON->password;
  $password = mysqli_real_escape_string($mysqli, $password);

  $passwordselect = "select password from user where userName='$username'";
  $passwordresult=mysqli_query($mysqli, $passwordselect);
  $exists=mysqli_num_rows($passwordresult);
  $selectactivated="select activated from user where username='$username' and activated='1'";
  $activatedresult=mysqli_query($mysqli, $selectactivated);
  $activated=mysqli_num_rows($activatedresult);
  if($exists==1 && $activated==1){
  while($row=mysqli_fetch_assoc($passwordresult)){
      $dbpass=$row['password'];
  }   
 $check=crypt($password, $dbpass); if($check===$dbpass){$loggedin=1;}else{$loggedin=0;}
  if($loggedin==true){
  $getUserSQL = "SELECT * FROM user where userName='$username' AND password='$dbpass'";
  $result=mysqli_query($mysqli, $getUserSQL);
  while($row=mysqli_fetch_assoc($result)){
  $data['username'] = $row['userName'];
  $data['braintreeid'] = $row['braintreeId'];
  $data['firstname']= $row['firstName'];
  $data['lastname'] = $row['lastName'];
  $data['email']=$row['email'];
  $data['loggedin'] = $loggedin;
  $data['error'] = 0;
  $data['success']=1;
  $data['showPopUp']=false;
  $_SESSION['activated']=$row['activated'];
  $email = $row['email'];
  $braintreeid = $row['braintreeId'];
  $firstname = $row['firstName'];
  $lastname = $row['lastName'];
  }
      $_SESSION['username'] = $username;
      $_SESSION['firstname'] = $firstname;
      $_SESSION['lastname'] = $lastname;
      $_SESSION['braintreeid'] = $braintreeid;
      $_SESSION['email'] = $email;
      $_SESSION['loggedin']=$loggedin;
      $_SESSION['success']=1;
      $_SESSION['error']=0;

echo json_encode($data);
} else {$data['loggedin']=$loggedin; $data['error']=1; $data['success']=0; $data['showPopUp']=true; $_SESSION['success']=0; $_SESSION['error']=1; $_SESSION['loggedin']=0; echo json_encode($data);}
}
if($exists==0){$data['loggedin']=0; $data['error']=1; $data['success']=0; $data['showPopUp']=true; $_SESSION['success']=0; $_SESSION['error']=1;  $_SESSION['loggedin']=0; echo json_encode($data);}
mysqli_close($mysqli);
?>

attach method for multiple record insertion in pivot table Laravel 5.5?

I want to insert multiple records in pivot table with just one query rather than using for loop and inserting one record at a time.

Consider my pivot table has columns role_id, user_id, active.

user_id and active are arrays and active only consists of value 0 or 1

I tried

$role->users()->attach($users->pluck('id')->toArray(), ['active' => $request->active]);

but this throws an error Array to string conversion

So I tried this

$role->users()->attach($users->pluck('id')->toArray(), ['active' => (int)$request->active]);

Then it worked but inserted all 1’s in active column in the database.

So how can I give an array as argument to attach method both user_id’s and active array to insert it in one go ?

Anyway to put this in a function so repetitive code isn’t used

This is my code for a project I am working on, is there anyway to shorten this code or even put it in a function so it is not this much repetitive code. I’m learning programming, and I was unable to find a solution to fix it. Is it a while loop or something I am meant to use?

$sth=$conn->prepare("SELECT * FROM players WHERE pid = {$steamprofile['steamid']}");
    $sth->execute();
    $result = $sth->fetch();
    if($result['rank'] == 11){
        echo "<button style='background-color: #ad0521; width: 100%; color: white; border: 0px solid black; font-family: myFirstFont; font-size: 18px;' disabled>Godfather</button>";
    }
    if($result['rank'] == 10){
        echo "<button style='background-color: #999900; width: 100%; color: white; border: 0px solid black; font-family: myFirstFont; font-size: 18px;' disabled>Mob Boss</button>";
    }
    if($result['rank'] == 9){
        echo "<button style='background-color: #798488; width: 100%; color: white; border: 0px solid black; font-family: myFirstFont; font-size: 18px;' disabled>Under Boss</button>";
    }
    if($result['rank'] == 8){
        echo "<button style='background-color: #397be5; width: 100%; color: white; border: 0px solid black; font-family: myFirstFont; font-size: 18px;' disabled>Warlord</button>";
    }
    if($result['rank'] == 7){
        echo "<button style='background-color: #6f9de8; width: 100%; color: white; border: 0px solid black; font-family: myFirstFont; font-size: 18px;' disabled>Turf Captain</button>";
    }
    if($result['rank'] == 6){
        echo "<button style='background-color: #c1722c; width: 100%; color: white; border: 0px solid black; font-family: myFirstFont; font-size: 18px;' disabled>Hitman</button>";
    }
    if($result['rank'] == 5){
        echo "<button style='background-color: #ffbf00; width: 100%; color: white; border: 0px solid black; font-family: myFirstFont; font-size: 18px;' disabled>Henchman</button>";
    }
    if($result['rank'] == 4){
        echo "<button style='background-color: #008c5f; width: 100%; color: white; border: 0px solid black; font-family: myFirstFont; font-size: 18px;' disabled>Loan Shark</button>";
    }
    if($result['rank'] == 3){
        echo "<button style='background-color: #12c98c; width: 100%; color: white; border: 0px solid black; font-family: myFirstFont; font-size: 18px;' disabled>Enforcer</button>";
    }
    if($result['rank'] == 2){
        echo "<button style='background-color: #6a0e91; width: 100%; color: white; border: 0px solid black; font-family: myFirstFont; font-size: 18px;' disabled>Butcher</button>";
    }
    if($result['rank'] == 1){
        echo "<button style='background-color: #b94ae8; width: 100%; color: white; border: 0px solid black; font-family: myFirstFont; font-size: 18px;' disabled>Scout</button>";
    }
    if($result['rank'] == 0){
        echo "<button style='background-color: #595959; width: 100%; color: white; border: 0px solid black; font-family: myFirstFont; font-size: 18px;' disabled>Guest</button>";
    }