Best way to verify if a script is allowed to run

Currently I have several PHP scripts which are run on a cron job ever 1 minute. When the scripts are run, they connect to a MySQL database and perform 3 or 4 querys to see if they are actually allowed to run.

For example…

// Check to see if script is enabled
$query = "SELECT * FROM config WHERE (config_name = 'AddFavourite' AND config_value = 1) or (config_name = 'CheckFavourite' AND config_value = 1) LIMIT 1";
$result = mysqli_query($sql_connect, $query);
if (mysqli_num_rows($result) == 0) {
    echo "<p>Execution of this script is currently disabled</p>\n";
    $end_time = microtime(true);
    echo "<p><strong>Completed with execution time: " . round(($end_time - $start_time), 3) . " seconds</strong></p>\n";
    die();
}

Then I perform a very similar query to see if the script is allowed to run on this given minute of the day.
And then another similar query to see if the script has been run too many times already.

I take the run unless stopped approach rather than embedded IFs within IFs
Before I spend hours updating the code to PDO, Is this the best way of doing this?

Waiting for someone to say don’t use * (I’ve just spotted that)

Makes sense to have a function for this too right???

// Function to check if a script is enabled
function CheckScriptEnabled($pdo, $FileName)
{
    $sql  = "SELECT 1 FROM config WHERE configname = ? AND configvalue = 1 LIMIT 1";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$FileName]);
    return $stmt->rowCount();
}
1 Like

There are no variables used in your query. thus, you can avoid prepare and execute and use query() method instead:

$query = "SELECT 1 FROM config WHERE (config_name = 'AddFavourite' AND config_value = 1) or (config_name = 'CheckFavourite' AND config_value = 1) LIMIT 1";
$stmt = $pdo->query($query);
if ($stmt->fetchColumn()) {
    echo "<p>Execution of this script is currently disabled</p>\n";
    $end_time = microtime(true);
    echo "<p><strong>Completed with execution time: " . round(($end_time - $start_time), 3) . " seconds</strong></p>\n";
    die();
}
1 Like

That’s assuming you only plan on running the query once.

The main purpose of prepare is when you are going to run it multiple times it does as much of the database access as it can once and minimizes what needs to be done for each execute.

The gain doesn’t worth the hasse.

But if he plans to run the same query during the same script execution, then yes he can use one pepare and multiple execute(). The problem is that you seldom can find such a case. Thus it’s a bit an exaggerration to call it “the main purpose”.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.