Сall a function inside a request MySQL PHP

Viewed 35

Task: The id field - from 1 to 1,000,000, fill in the field value according to the following algorithm: For id = 1 value = 7. The next identifier value is calculated as the sum of the square digits from the previous identifier value, increased by 1.

function InsertData(){

    global $MySQL;
    global $SumSquares;
    
    $MySQL->query("INSERT INTO `your_table` (`id`, `val`) VALUES (1, 7);");

    for($id = 2, $value = $id; $id != 1000000; $id++, $value--){
        $MySQL->query("INSERT INTO `your_table` (`id`, `val`) VALUES ($id, $SumSquares($value));");
    }

    $MySQL->close();
}

sum of digits of a square function

function SumSquares($number, $exp = 2) {
    if($number === 1 or $number === 0) return 1;

    $sum = 0;

    $squareNum = pow($number, $exp);

    while($squareNum > 0) {
        $sum += ($squareNum % 10);
        $squareNum /= 10;
    }
    return $sum;
}

I have several questions, the first is how to call the function correctly inside the request? Second: the problem says “fill in the value field according to the following algorithm: For id = 1 value = 7, I solved it like this

$MySQL->query("INSERT INTO` your_table` (ʻid`,` val`) VALUES (1, 7);");

is this acceptable or rude?

1 Answers

You can do it by creating a variable ($value) to hold the value, then using that in your SQL statement:

$value = SumSquares($value);
$MySQL->query("INSERT INTO `your_table` (`id`, `val`) VALUES ($id, $value);");
Related