Tuesday 28 August 2018

Mysqli queries does not return results in function

I have several php functions which serve different purposes. Each of them is executing a specified mysqli query yet only the first query returns results.

Here is my code
function setAsNonWorkingProxy(){

    GLOBAL $mysqli, $proxy;

    $port = explode(":",$proxy)[1];
    $proxy = explode(":",$proxy)[0];

    if ($sql2 = $mysqli->prepare("UPDATE proxies SET failed=failed+1 WHERE ip=? AND port=?")) {

        $sql2->bind_param("si",$proxy, $port);

        $sql2->execute();

        $sql2->close();

    }
}

function markProxyAsUsed(){

    GLOBAL $mysqli, $proxy;

    $port = explode(":",$proxy)[1];
    $proxy = explode(":",$proxy)[0];

    if ($sql3 = $mysqli->prepare("UPDATE proxies SET tried=tried+1 WHERE ip=? AND port=?")) {

        $sql3->bind_param("si",$proxy, $port);

        $sql3->execute();

        $sql3->close();
    }
}

setAsNonWorkingProxy();
markProxyAsUsed();

When I do this, only the first function that is called, executes the query inside. The second function is called and the query executed without any errors yet nothing happens. I am using UDPDATE queries inside both functions.
If I change the order of the functions:
markProxyAsUsed();
setAsNonWorkingProxy();

Again, only the first one works. Why is this happening?

The problem is that you are bringing the global scope variable in your function. Then using explode on the $proxy and the result is stored back into $proxy(remember thats the same global var) what happens is that the second function called is now working with the modified $proxy variable. It doesn't even matter if you call the same function two times, it will fail the second time.
function markProxyAsUsed(){

    GLOBAL $mysqli, $proxy; //You are bringing global scope vars in here

    // If $proxy is something like '222.222.222.222:8080' on your first call
    // On the second call will be only '222.222.222.222' and your logic will be broken
    $port = explode(":",$proxy)[1];
    $proxy = explode(":",$proxy)[0]; //Here is where you are messing it
    //Quickfix
    $ip = explode(":", $proxy)[0]; // then use $ip in your query

    //Proper fix would be to declare the function as so function markProxyAsUsed($proxy)
    //and pass it when you call the function.

0 comments:

Post a Comment