Populate and rank a table using RANK() function using PHP and SQL statements

Viewed 36

I'm working with this MariaDB database:

Server version: 10.3.31-MariaDB-log-cll-lve - MariaDB Server

Protocol version: 10

I would like to update and rank a table whenever users submit a form. This first part of code work properly, inserting the user entries when he submits the form (I check connection on run and I also checked the database and it is filled) . At this point the record has been created. (from //---RANKING PART------------- in the code)

Now I need to rank the table, so I tried to use RANK() function as reported in https://mariadb.com/kb/en/rank/ I tried a lot but it doesn't work

add_action( 'gform_after_submission_13', 'myfunction', 10 , 1); // execute myfunction when user submit form 13


function myfunction($entry){
    
$nome = rgar( $entry, '1' );
$categoria = rgar( $entry, '4' );
$score = rgar( $entry, '2' );
$ig = rgar( $entry, '3' );

    
$servername = "xxxxxxxxxxx";
$username = "xxxxxxx";
$password = "xxxxxxxxxxxxxxxxxx";
$dbname = "xxxxxxxxxxx";
    
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
    
$sql = "INSERT INTO Table1 (nome, categoria, score, ig)
VALUES ('$nome','$categoria','$score','$ig')";

if ($conn->query($sql) === TRUE) {
  echo "New record created successfully";
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}
    
//---RANKING PART-------------
    
$sql2="SELECT 
  RANK() OVER (PARTITION BY categoria ORDER BY score DESC) AS myrank, 
  nome, categoria, score, ig 
FROM Table1 ORDER BY nome, score DESC";

if ($conn->query($sql2) === TRUE) {
  echo "Ranking update";
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
}

When I try to do a testing submission on the top of the browser I read

New record created successfullyError: INSERT INTO Table1 (nome, categoria, score, ig) VALUES ('testname','test category','576','test_ig')

P.S. I don't know if it useful to know that I putted this code in snippet plugin of wordpress (plugin to create a php snippet). I tested the plugin with others code and it works properly.

0 Answers
Related