Th3lmuu90
Th3lmuu90

Reputation: 1717

mysqli queries not returning results inside 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?

Upvotes: 0

Views: 120

Answers (2)

bulforce
bulforce

Reputation: 1071

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.

Upvotes: 1

Alfred_P
Alfred_P

Reputation: 792

It happens because you edit the proxy variable inside your function. The first function you run changes the proxy variable from xxxx:yy to xxxx

The second time you execute the function your $port variable will be empty and the where clause in your sql statement will not find it.

Upvotes: 1

Related Questions