Jump to content

call a function from a function and update mysql db


vanquish12

Recommended Posts

Is it possible to call a function from another function and update a mysql database using the 2nd function?

 

So if I have 1 function which selects data from a database and puts it into an array,

I then need the 2nd function to do some stuff and insert the results to another table. Can the insert statement be in the 2nd function or does it have to be a seperate statement?


function function1(){


$sql = "SELECT a, b, c, d FROM someTable";
$result = mysqli_query($conn, $sql) or die(mysql_error());

if(mysqli_num_rows($result) > 0) {
//output data
while($row = mysqli_fetch_array($result)) {

$row = array_map("function2", $row['a'], $row['b'], $row['c']);

}
}

mysqli_close($conn);

}



function function2($a, $b, $c)
{
$table = "some table";

$fsock = fsockopen($a, $b, $c);

if (!$fsock) {
$res= 0;
return $res;
} else {
$res= 1;
return $res;
}
}

 

Edit: array_map would process the values one index at a time.

 

Have you tried calling the function directly?

$row = function2($row['a'], $row['b'], $row['c']);

The second argument for array_map needs to be an array. More information can be found here:

http://php.net/manual/en/function.array-map.php

 

You could try passing $row as is:

$row = array_map("function2", $row);

Of course, you would need to modify function2 to accept a single argument.

thanks, can I also include an mysql insert statement in the 2nd function so it would look like:

function function2($a, $b, $c)
{
    $table = "some table";

    $fsock = fsockopen($a, $b, $c);

    if (!$fsock) {
        $res= 0;
        return $res;
    } else {
        $res= 1;
        return $res;
    }
mysqli_query($conn, "INSERT INTO $table (a, b) VALUES ('" . $a . "', '" . $b. "') or die(mysqli_error($conn));

}

Adding on to cyberRobot's reply you will need run the query before the use of  return $res;  otherwise the query will never execute. This is because the return statement will terminate the function where it is called, anything after it will never be reachable.

 

For more information please read

http://php.net/manual/en/functions.returning-values.php

http://php.net/return

thanks guys I'll give it a try, one more thing, my database connection details are in another file called mysql.php. I've added require("mysql.php"); to the top of the file however the $conn variable (which is set in the mysql.php file) is not being picked up by the function. Is there any way to pass this variable into the function or do I need to provide the connection details in every function which has to do something with the database?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.