PHP Doctrine DTO integer id to uuid from ResultSetMapping

I am fetching results from doctrine native query and want to convert the id into uuid using result set mapper,I am using the below code:

$rsm = new ResultSetMapping();
    $rsm->addScalarResult('id', 'id', 'uuid_magic_optimised');
    $rsm->addScalarResult('title', 'title');
    $rsm->addScalarResult('vendor', 'vendor');
    $rsm->addScalarResult('icon_name', 'icon_url');

But getting the following error:

Doctrine  DBAL  Types  ConversionException
Could not convert database value "1" to Doctrine Type uuid_binary_ordered_time

Why can you call a private method on a new instance made inside a public method of the same class type, in PHP?

Why can you call a private method on a new instance made inside a public method of the same class type?

class Foo
{
    private function thePrivateMethod()
    {
        echo 'can not be called publicly?';
    }

    public function thePublicMethod()
    {
        $clone = new Foo;
        $clone->thePrivateMethod();
    }
}

$foo = new Foo();
$foo->thePublicMethod();
$foo->thePrivateMethod();

The above results in the following output when run in PHP 7.3.18

can not be called publicly?

Fatal error:  Uncaught Error: Call to private method Foo::thePrivateMethod() from context

Intuitively, I would expect the first call to Foo::thePrivateMethod() to also cause a fatal error. But I’m not able to find in the documentation that this behaviour would be allowed?

Select all data from database MySQL not working php but the inserting working

First I have the insertion part here it’s getting data from json file then insert then select

  $mysqli  = new mysqli($servername, $username, $password,$db) or die("Connect failed: 
  %sn". $mysqli  -> error);
  echo "Connected successfully";

 $json = file_get_contents("https://raw.githubusercontent.com/SeteMares/full-stack-test/master/feed.json") ;
    $json = json_decode(  $json,true);
    $content= array();
    $TITLE = array();
    $CONTENT = array() ;
    $MEDIA = array() ;
    $SLUG = array() ;
    $categories = array() ;
    foreach ($json as $key => $value){
      
        $TITLE[] = $json[$key]['title'] ;
      
       
        $CONTENT[] = $json[$key]['content'];
        $MEDIA[] = $json[$key]['media'];
        $SLUG[] = $json[$key]['slug'];
        $categories[] = $json[$key]['categories'];
    }
    
    for($s=0;$s<sizeof($TITLE);$s++){

        $url_string =  $CONTENT[$s][0]['content'];
        $res = urldecode($url_string);
        $Cataggory = $categories[$s]['primary']; 
        echo gettype($Cataggory );
        $slug = $SLUG[$s] ;
        echo gettype($slug );

         $sqlquery = "INSERT INTO `jsondata` (`title`, `slug`, `content`, `categories`, `media`) VALUES (  '$TITLE[$s]',   ? ,   ?, ?,  '$TITLE[$s]' )" ;
         $stmt = $mysqli->prepare($sqlquery);
         $stmt->execute(array($slug,$res,$Cataggory));
       
         
    }

when i select the data it doesn’t work it prints

Fatal error: Uncaught Error: Call to undefined method mysqli_stmt::fetchAll() in C:xampphtdocsfirstphpindex.php:68 Stack trace: #0 {main} thrown in C:xampphtdocsfirstphpindex.php on line 68

this the select code for sure all the code in the same file



     $sqlquery3 = "SELECT 'title'   FROM jsondata  " ;
     $sth = $mysqli->prepare($sqlquery3);
     $sth->execute();
  
     $result = $sth->fetchAll();
     print_r($result);
    

Conflict between 2 function using ajax in wordpress

I have written this code here

  add_action('wp_head','pageType');
function pageType(){
  
    if (is_product()) {
            global $post;
            $product = wc_get_product( $post->ID );
            $tipo    = $product->get_type();
            echo $product->get_name();
            echo $product->get_price();
            echo $product->get_regular_price();
            return $product->get_name();
        }else{    
          return "NOTHING";
        }
    }

add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
  check_ajax_referer( 'my-special-string', 'security' );
  $whatever = intval( $_POST['whatever'] );


 $dataOfProduct = pageType();

  $whatever += 10000;
  echo $whatever . '=>>' . $dataOfProduct .' . ' . '<==== d';
  die(); 
}

The code is working fine

Example when pageType is being added to wp_head with add_action(wp_head,'pageType') the is_product is working fine so it is printing

        echo $product->get_name();
        echo $product->get_price();

But in the second method i have an ajax function because i am trying to send data to a tracking script

add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {

Inside this method when i am calling

 $dataOfProduct = pageType();

It is returning “NOTHING”

What can be the problem why its working is_product() function not working on my_action_callback()

What can be the problem

Here $dataOfProduct = pageType(); i want pageType to return the name of the product

THank you

Finding ocuppations via SQL and/or PHP

I am making a student web app. Amongst other tables, I have a table in which students enroll and enrollments are between two dates.

This app uses MySQL 5.6 and PHP 7.2
It has the following fields:

  • IDStudent
  • StartDate
  • EndDate
  • IDCourse

Each course has a maximum capacity in which it cannot be surpassed.

I want to know, given a start date, end date and IDCourse, how many concurrent students are in a course. I get an approxiumate value just counting rows between two dates

SELECT COUNT(*) FROM enrollments
    WHERE IDCourse = ? 
    AND (
      (StartDate BETWEEN "<start date>" AND "<end date>")
      OR
      (EndDate BETWEEN "<start date>" AND "<end date>")
      OR
      (StartDate <= "<start date>" AND EndDate>= "<end date>")
    )

But that doesn’t take account non overlapping ranges. It counts every enrollment.

For example, I have this very simple case:

Want to find how many students are enrolled between 01/01/2021 and 05/01/2021 at a specified course

And I have those 3 enrollments on that course:

  1. 01/01/2021 – 02/01/2021
  2. 03/01/2021 – 04/01/2021
  3. 20/12/2020 – 01/02/2021

I should get 2 count and not 3, because 1 and 2 don’t overlap while 3 overlaps both.
I tried to search online but I didn’t found something similar, maybe I am not using the correct keywords!

Many thanks for your help
Regards

how can i run PHP functions with query to database from javascript [duplicate]

How can i run php functions with query to the database from the level of the javascript function?

</script>
function databaseUpdate() {

}

</script>


<?php
function databaseUpdatePHP () {

    $sqlUpdateVocabulary = "UPDATE users SET number='$number+20' WHERE email='" . $_SESSION['username'] . "'";
    if(mysqli_query($conn, $sqlUpdateVocabulary)){
        echo "updated successfully.";
    } else {
        echo "ERROR";
    }

}
?>

php router passing parameters to call_user_func_array

<?php 
    class Router {
        protected $conn;
        protected $currentController = "";
        protected $currentMethod = "";
        protected $params = [];

        public function __construct(PDO $conn){
            $this->conn = $conn;
        }

        public function dispatch(){
            $url = $this->getUrl();
            if(isset($url[4])){
                switch($url[4]){
                    case "events":
                        $this->currenController = "EventController";
                        $this->currentMethod = "getEvents";
                        break;
                    case "event":
                        $this->params = $url[5];
                        $this->currentController = "EventController";
                        $this->currentMethod = "getEvent";
                        break;

                }
            }
            $this->currentController = new AppControllersEventController($this->conn);
            call_user_func_array([$this->currentController, $this->currentMethod], $this->params);
            $this->currentController->display();
        }

        public function getUrl(){
            $uri = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
            $url = explode("/", $uri);
            return $url;
        }
    }
?>

$url[5] is supposed to be a numeric id for selecting an event or a string namely “?id=1” how can I pass this value to call_user_func_array I’ve seen doing it with preg_match expressions unfortunately I didn’t understand how it works

Download a local file using `<a href= "file://link/to/my/file" ` not working on chrome [duplicate]

The link How can I create a link to a local file on a locally-run web page? doesn’t help me, since the problems are not the same

I have the folowwing html code

<a href = "file://link/to/my/local/file/my file.xltx" target="_blank"> Download my file </a>

written inside index.php file

In IE, it works fine, but when coming to Chrome, it doesn’t work

I want to force Chrome (or any other browser) to download the file using php script only, whithout using chrome extension or configuration

Can any one help me ? Thanks in advance

Remarks

  • I tried curl method, but the problem is that the php script is server side, so the target location will be relative to server not to client
  • When I copy paste file://link/to/my/local/file/my file.xltx the the chrome adress bar, it works fine

Integrating Coldfusion and Pay360

Does anyone have any experience with integrating a Coldfusion website with Pay360? Basically our online shop needs to direct the user to a payment screen on Pay360 using the hosted cashier. The documentation is a bit vague but essentially we have to pass an API username and password, and json string to their request URL and they should return a response with a URL to a payment form. Should be straightforward using cfhttp but I get an error:

{“status”:”FAILED”,”reasonCode”:”exception.request.content”,”reasonMessage”:”Invalid request content: Unexpected character (‘/’ (code 47)): maybe a (non-standard) comment? (not recognized as one since Feature ‘ALLOW_COMMENTS’ not enabled for parser)”}

No one at Pay360 seems to be able to help. I’ve also tried using PHP (having only found one example on bronco.co.uk by doing a Google search) but that doesn’t work for me either.

This is my code. If anyone can give any advice (or has a working CF or PHP script that could point me in the right direction) that would be great, thanks!

<cfset variables.username = "xxxxxx">
<cfset variables.password = "xxxxxx">
<cfset stFields = {
  "session": {
    "preAuthCallback": {
      "url": "http://www.example.com/callback/preAuth?status=SUSPEND",
      "format": "REST_XML"
    },
    "returnUrl": {
      "url": "http://www.example.com/transactionResult?MERCHANTREF=761585761585"
    }
  },
  "transaction": {
    "merchantReference": "761585761585",
    "money": {
      "amount": {
        "fixed": 100
      },
    "currency": "GBP"
    }
  },
  "customer": {
    "identity": {
      "merchantCustomerId": "1111111111111"
    },
    "details": {
      "name": "given1 Family1",
      "address": {
        "line1": "matched",
        "line2": "initialCustomer1AddresssLine2",
        "city": "initalCustomer1City",
        "region": "initalCustomer1Region",
        "postcode": "AVS111",
        "countryCode": "GBR"
      },
      "telephone": "0044111111111",
      "emailAddress": "[email protected]",
      "ipAddress": "1.1.1.1",
      "defaultCurrency": "GBP"
    }
  },
  "financialServices": {
    "dateOfBirth": "19870818",
    "surname": "Smith",
    "accountNumber": "123ABC",
    "postCode": "BS20"
  }
}>   

<cfhttp url="https://api.mite.pay360.com/hosted/rest/sessions/5309398/payments" method="post" username="#variables.username#" password="#variables.password#" result="httpResp" timeout="60">
    <cfhttpparam type="header" name="Content-Type" value="application/json" />
    <!--- failed attempt to pass username and password in the body
<cfhttpparam type="formField" name="username" value="#variables.username#">
    <cfhttpparam type="formField" name="password" value="#variables.password#">--->
    <cfhttpparam type="body" value="#serializeJSON(stFields)#">
</cfhttp>

<cfdump var="#httpResp#"/>

Is there anything wrong with this regex? [closed]

I’m trying to make a regex for National Identification Number for my country.
The format is CF or CM + last 2 digits of birth year + 6 digits + Letter + 2 digits + Letter.
An example is: CF95032102EA1H or CM95032102EA1H

This is my regex using php. When I run it, it returns Ivalid

$nin_regex = '/^(CF|CM)d{2}[0-9]{6}[A-Z]{1}[0-9]{2}[A-Z]{1}$/';

function validate_nin($nin) {
    global $nin_regex;
    return preg_match($nin_regex, $nin);
}

if (validate_nin('CF95032102EA1H')) {
    echo 'Valid NIN';
} else {
    echo 'Invalid NIN';
}

Laravel 2FA email

I am working on 2FA via email in my application , the problem I am facing is whenever I am logging in it automatically gets logged out and send me back to login page although it is sending me an email with correct user email through which I tried to login and it do not reaches to verify page .

here is my login_submit function

public function login_submit(Request $request)
{

    if(Auth::check()){
        return redirect()->route('admin.home')->with('success','Successfully logged in');
    }

    $request->validate([
        'email' => 'required|email',
        'password' => 'required|min:5',
    ]);

    $credentials = $request->only('email', 'password');
    
    
    if (Auth::attempt($credentials)) {
        
        // if(Auth::user()->role->name == 'Customer'){
        //   return redirect()->route('home')->with('success','Successfully logged in');    
        // }
        
        $user = auth()->user();
        
        $user->generateTwoFactorCode();
        $user->notify(new TwoFactorCode());
     
        
        if(auth()->check()) {
            return redirect()->route('verify.index')->with('success','Successfully logged in');
        }
        
    }else{
        
         return back()->with('error','These credentials do not match with our record');
        
    }

}

My User modal which includes both generate code and reset methods

<?php

namespace App;

use IlluminateContractsAuthMustVerifyEmail;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
use IlluminateDatabaseEloquentSoftDeletes;
use AppReview;

class User extends Authenticatable
{
    use Notifiable;
    
    public $table = 'users';
    
     protected $dates = [
        'updated_at',
        'created_at',
        'deleted_at',
        'email_verified_at',
        'two_factor_expires_at',
    ];

    protected $guarded = [];

    /**
     * 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',
    ];
   
    
    
    /**
     * Generate 6 digits 2FA code for the User
     */
    public function generateTwoFactorCode()
    {
        $this->timestamps = false; //Dont update the 'updated_at' field yet
        
        $this->two_factor_code = rand(100000, 999999);
        $this->two_factor_expires_at = now()->addMinutes(10);
        $this->save();
    }

    /**
     * Reset the 2FA code generated earlier
     */
    public function resetTwoFactorCode()
    {
        $this->timestamps = false; //Dont update the 'updated_at' field yet
        
        $this->two_factor_code = null;
        $this->two_factor_expires_at = null;
        $this->save();
    }




}

Here is my verify routes along with middleware

 Route::get('verify/resend', 'AuthTwoFactorController@resend')->name('verify.resend');
 
 Route::resource('verify', 'AuthTwoFactorController')->only(['index', 'store']);

Route::prefix('admin')->middleware(['auth','twofactor','can:access_admin_panel'])->namespace('Admin')->name('admin.')->group(function () {

        Route::get('/home', 'DashboardController@index')->name('home');

}

and two_factor middleware is

<?php

namespace AppHttpMiddleware;

use Closure;

class TwoFactor
{
    /**
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user = auth()->user();

        if(auth()->check() && $user->two_factor_code)
        {
            if($user->two_factor_expires_at<now()) //expired
            {
                $user->resetTwoFactorCode();
                auth()->logout();

                return redirect()->route('admin.login')->with('error','The two factor code has expired. Please login again.');
            }

           
            return redirect()->route('verify.index');
           
        }

        return $next($request);
    }
}

and below is my TwoFactorController :

<?php
        
        namespace AppHttpControllersAuth;
        
        use AppHttpControllersController;
        use AppNotificationsTwoFactorCode;
        use IlluminateHttpRequest;
        
        class TwoFactorController extends Controller
        {
            public function __construct()
            {
                $this->middleware('auth');
            }
        
            public function index() 
            {
               
                return view('auth.twoFactor');
            }
        
            public function store(Request $request)
            {
                $request->validate([
                    'two_factor_code' => 'integer|required',
                ]);
                
        
                $user = auth()->user();
        
                if($request->two_factor_code == $user->two_factor_code)
                {
                    $user->resetTwoFactorCode();
        
                    return redirect()->route('admin.home');
                }
        
                return back()->with('error' , 'The two factor code you have entered does not match');
            }
        
            public function resend()
            {
                $user = auth()->user();
                $user->generateTwoFactorCode();
                $user->notify(new TwoFactorCode());
        
                return back()->with('success','The two factor code has been sent again');
            }
        }
    
    }

Closure / Decorator in PHP?

I want to bind a function to another function to cache its results.
Unfortunately it’s not a class, hence I think I cannot use Closures.

I.e. like a decorator in Python.

I want to do this because I cannot modify the function with patching an API code.

So I have a function which gets called very often which always does one SQL query:

function api_func() {
    global $wpdb;
    // ... do a query without caching ...
    return $wpdb->get_col(...);
}

I want to surround this function by another function cache_func(), so that, whenever api_func() would be called, cache_func() gets called and can once cache the results.

Any ideas?

Thanks

i need to rank student based on their score (Subject Position) and also Overall Position

I have a project on student ranking. The sample school does three terminal exam in a year. I created a table where i stored all student test and exam according to their RegNo, year(session), semester, level and student arm(i.e A,B,C,D…) and all works perfectly.

The problem i’m facing now is the student overall position and subject position. For student subject position, I created a table called subject position where I want to have the position of students based on subject. And for the overall position I created a table that will automatically sum all the student result termly and rank them.

This is my table structure:

DROP TABLE IF EXISTS `subject_position`;

CREATE TABLE IF NOT EXISTS `subject_position` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`regNo` varchar(50) NOT NULL,

`subjectid` varchar(50) NOT NULL,

`armsLevelId` varchar(50) NOT NULL,

`armsId` varchar(50) NOT NULL,

`semesterid` varchar(11) NOT NULL,

`yearid` varchar(50) NOT NULL,

`total` varchar(50) NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=MyISAM AUTO_INCREMENT=73 DEFAULT CHARSET=latin1;

 

--

-- Dumping data for table `subject_position`

--

 

INSERT INTO `subject_position` (`id`, `regNo`, `subjectid`, `armsLevelId`, `armsId`, `semesterid`, `yearid`, `total`) VALUES

(1, '4663', '1', '1', '1', '1', '1', '72'),

(2, '6073', '1', '1', '1', '1', '1', '73'),

(3, '4663', '2', '1', '1', '1', '1', '47'),

(4, '6073', '2', '1', '1', '1', '1', '61'),

(5, '4663', '3', '1', '1', '1', '1', '82'),

(6, '6073', '3', '1', '1', '1', '1', '61'),

(7, '4663', '4', '1', '1', '1', '1', '99'),

(8, '6073', '4', '1', '1', '1', '1', '95'),

(9, '4663', '5', '1', '1', '1', '1', '70'),

(10, '6073', '5', '1', '1', '1', '1', '100'),

(11, '4663', '6', '1', '1', '1', '1', '69'),

(12, '6073', '6', '1', '1', '1', '1', '67'),

(13, '4663', '7', '1', '1', '1', '1', '77'),

(14, '6073', '7', '1', '1', '1', '1', '80'),

(15, '4663', '8', '1', '1', '1', '1', '58'),

(16, '6073', '8', '1', '1', '1', '1', '77'),

(17, '4663', '9', '1', '1', '1', '1', '96'),

(18, '6073', '9', '1', '1', '1', '1', '96'),

(19, '4663', '10', '1', '1', '1', '1', '78'),

(20, '6073', '10', '1', '1', '1', '1', '77'),

(21, '4663', '11', '1', '1', '1', '1', '48'),

(22, '6073', '11', '1', '1', '1', '1', '88'),

(23, '4663', '12', '1', '1', '1', '1', '69'),

(24, '6073', '12', '1', '1', '1', '1', '94'),

(25, '4663', '1', '1', '1', '2', '1', '28'),

(26, '6073', '1', '1', '1', '2', '1', '70'),

(27, '4663', '2', '1', '1', '2', '1', '68'),

(28, '6073', '2', '1', '1', '2', '1', '59'),

(29, '4663', '3', '1', '1', '2', '1', '68'),

(30, '6073', '3', '1', '1', '2', '1', '70'),

(31, '4663', '4', '1', '1', '2', '1', '81'),

(32, '6073', '4', '1', '1', '2', '1', '72'),

(33, '4663', '5', '1', '1', '2', '1', '84'),

(34, '6073', '5', '1', '1', '2', '1', '72'),

(35, '4663', '6', '1', '1', '2', '1', '58'),

(36, '6073', '6', '1', '1', '2', '1', '72'),

(37, '4663', '7', '1', '1', '2', '1', '71'),

(38, '6073', '7', '1', '1', '2', '1', '70'),

(39, '4663', '8', '1', '1', '2', '1', '48'),

(40, '6073', '8', '1', '1', '2', '1', '55'),

(41, '4663', '9', '1', '1', '2', '1', '66'),

(42, '6073', '9', '1', '1', '2', '1', '51'),

(43, '4663', '10', '1', '1', '2', '1', '37'),

(44, '6073', '10', '1', '1', '2', '1', '58'),

(45, '4663', '11', '1', '1', '2', '1', '57'),

(46, '6073', '11', '1', '1', '2', '1', '59'),

(47, '4663', '12', '1', '1', '2', '1', '67'),

(48, '6073', '12', '1', '1', '2', '1', '69'),

(49, '4663', '1', '1', '1', '3', '1', '94'),

(50, '6073', '1', '1', '1', '3', '1', '82'),

(51, '4663', '2', '1', '1', '3', '1', '69'),

(52, '6073', '2', '1', '1', '3', '1', '76'),

(53, '4663', '3', '1', '1', '3', '1', '63'),

(54, '6073', '3', '1', '1', '3', '1', '81'),

(55, '4663', '4', '1', '1', '3', '1', '81'),

(56, '6073', '4', '1', '1', '3', '1', '77'),

(57, '4663', '5', '1', '1', '3', '1', '72'),

(58, '6073', '5', '1', '1', '3', '1', '83'),

(59, '4663', '6', '1', '1', '3', '1', '78'),

(60, '6073', '6', '1', '1', '3', '1', '83'),

(61, '4663', '7', '1', '1', '3', '1', '77'),

(62, '6073', '7', '1', '1', '3', '1', '75'),

(63, '4663', '8', '1', '1', '3', '1', '74'),

(64, '6073', '8', '1', '1', '3', '1', '82'),

(65, '4663', '9', '1', '1', '3', '1', '56'),

(66, '6073', '9', '1', '1', '3', '1', '95'),

(67, '4663', '10', '1', '1', '3', '1', '87'),

(68, '6073', '10', '1', '1', '3', '1', '79'),

(69, '4663', '11', '1', '1', '3', '1', '70'),

(70, '6073', '11', '1', '1', '3', '1', '71'),

(71, '4663', '12', '1', '1', '3', '1', '82'),

(72, '6073', '12', '1', '1', '3', '1', '90');

COMMIT;

 

 

Table name: dummy (This table stores all students scores depending of RegNo, year(session), semester, level and student arm(i.e A,B,C,D…) respectively)

id regNo subjectid  armsLevelId  armsId  semesterid yearid  firstCA  seconCA  exam   total   grade    comment
1   4663       1                   1               1               1             1          9           8             55       72       B2         V.Good
2   6073       1                   1               1               1             1         10          8             55       73       B2          V.Good
3   4663      2                   1               1               1             1          6           8             33       47       D7          Pass
4   6073       2                  1               1               1             1          11          6             44       61       C4           Credit

 

Table name: subject_position (This table stores all students total scores termly depending of RegNo, year(session), semester, level and student arm(i.e A,B,C,D…) respectively)

id regNo subjectid  armsLevelId  armsId  semesterid yearid  total
1   4663       1                     1           1               1               1        72   
2   6073       1                     1           1               1               1        73  
3   4663      2                     1           1               1               1        47  
4   6073      2                     1           1               1               1         61  

..    ....          .                      .            .                .                .         ..

..    ....          .                      .            .                .                .         ..

..    ....          .                      .            .                .                .         ..

71  4663     12                   1            1               3               1         82 

72  6073     12                   1            1               3               1         90

 

Expected Output: for subject_position irrespective of the subject list

Note: Number of student here is two. we can have more than two(2) students

id regNo subjectid  armsLevelId  armsId  semesterid yearid  total  SubjectPos
1   4663       1              1                    1               1             1       72         2
2   6073       1              1                    1               1             1       73         1
3   4663      2              1                    1               1             1       47         2
4   6073      2              1                    1               1             1        61         1

..    ....          .                .                    .                .              .         ..          ..

..    ....          .                .                    .                .              .         ..          ..

..    ....          .                .                    .                .              .         ..          ..

71  4663     12             1                   1               3             1         82        2

72  6073     12             1                   1               3             1         90        1

 

My query

/Where subject id $sub is coming from/

$sql_subject = "select * from dummy where regid='$_GET[name]' and armsLevelId='$_SESSION[level_id]' and armsId='$_SESSION[arms]' and yearid='$_SESSION[session]' group by subjectid";

$result = mysqli_query($con,$sql_subject);

$datas_subject = array();

         while ($row_query=mysqli_fetch_array($result)){

                $RegNo=$row_query["regid"];

                $subject_id=$row_query["subjectid"];

                $level_id=$row_query["armsLevelId"];

                $arms=$row_query["armsId"];

                $semester=$row_query["semesterid"];

                $session=$row_query["yearid"];

                $fca=$row_query["firstCA"];

                $sca=$row_query["secondCA"];

                $exam=$row_query["exam"];

                $total =$row_query["total"];

                $grade =$row_query["grade"];

                $comment =$row_query["comment"];

 

$query_sub=mysqli_query($con,"select * from subject where id='".$subject_id."'");

               while ($row_sub=mysqli_fetch_array($query_sub)){

                           $r_sub = $row_sub["subject_name"];

                }

                         $datas_subject[] = $subject_id;

 }

 

for ($i=0; $i<count($datas_subject); $i++) {

       if(!empty($datas_subject[$i])){

           $sub = $datas_subject[$i];

       echo "Subject ID: ".$sub ."n";  // this printed all the list of subject ids

 

}else{

          //echo "Error Occured";

}

}


$sql = "SELECT * FROM `subject_position` where regNo='$RegNo'  and subjectid='$sub' and armsLevelId='$level_id' and armsId='$arms' and semesterid='$_SESSION[semester]' and yearid='$session' ORDER BY `total` DESC";

 

echo $sql . "n";    // This printed SELECT * FROM `subject_position` where regNo='4663' and subjectid='12' and armsLevelId='1' and armsId='1' and semesterid='1' and yearid='1' ORDER BY `total` DESC

//without looping through the subject Ids

 

$result = mysqli_query($con,$sql);

if( !$result ){

echo 'SQL Query Failed';

}else{

$rank = 0;

$last_score = false;

$rows = 0;

while( $row = mysqli_fetch_array( $result ) ){

$rows++;

     if( $last_score!= $row['total'] ){

           $last_score = $row['total'];

          $rank = $rows;

    }

          echo "rank ".$rank." is ".$row['regNo']." with point ".$row['total'] . "n";

     }