I am trying to create a function in PHP that accepts two arguments, one being the SQL for a mysqli query and the other being the name I would like to be set as the variable name for the resulting array. Here it is so far:
<?php
function dbSelect($sql,$name) {
include "connect.php";
if($results = $db->query($sql)) {
if($results->num_rows) {
while($row = $results->fetch_object()) {
${$name}[] = $row;
}
$results->free();
}
}
return ${$name};
}
Within the referenced connect.php file is this code
$db = new mysqli('127.0.0.1', 'admin', 'PASSWORD', 'DB_NAME');
However it does not seem to work in its current state. I do not get any errors when calling the function "dbSelect($sql, 'test');" however when I try to reference the supposedly created variable (in this case, $test) I get an undefined error.
Any suggestions or tips on how to fix this?
Thanks in advance.
The ${$name} variable you're assigning to has local scope. That is, the variable disappears as this function returns. Using a variable-variable doesn't make that variable global.
I would recommend you just name the array anything inside your function, and then return the array. Then you can assign its return value to your desired variable instead of passing the variable name.
$test = dbSelect($sql);
You could try to declare global ${$name} inside the function to write to a variable of global scope, but IMHO it's not worth it. It's a better habit to avoid writing functions that have weird side effects on global variables. Keep it simple, just return the results.
The variable variable ${$name} has no practical use in this function. The function returns an array with no variable name. You name it when you assign the function return:
$whatEverYouWant = dbSelect('some sql');
function dbSelect($sql) {
include "connect.php";
if($results = $db->query($sql)) {
if($results->num_rows) {
while($row = $results->fetch_object()) {
$array[] = $row;
}
$results->free();
return $array;
}
}
return false;
}
Return false or maybe an empty array() if there are no results or an error.
Related
I'm refactoring all the codes given to me and I saw in the code that the're so many repeated variables that is using with other methods
which is this
$tag_id = json_decode($_POST['tag_id']);
$tag_name = json_decode($_POST['tag_name']);
$pname = json_decode($_POST['pname']);
$icode = json_decode($_POST['icode']);
$bname = json_decode($_POST['bname']);
$client = json_decode($_POST['client']);
$package = json_decode($_POST['package']);
$reference = json_decode($_POST['reference']);
$prodcat = json_decode($_POST['prodcat']);
$physical_array = json_decode($_POST['physical_array']);
$chemical_array = json_decode($_POST['chemical_array']);
$physpec_array = json_decode($_POST['physpec_array']);
$micro_array = json_decode($_POST['micro_array']);
$microspec_array = json_decode($_POST['microspec_array']);
$prod_type = json_decode($_POST['prod_type']);
$create_physical_id_array = json_decode($_POST['create_physical_id_array']);
$create_chemical_id_array = json_decode($_POST['create_chemical_id_array']);
$create_micro_id_array = json_decode($_POST['create_micro_id_array']);
my question is how can i just use put it in one method and i'll just call it to other methods instead of repeating that code.
thank you
You can't call it from other methods. Because the variables defined to that method are local. Instead you can define the variables as member variables of that class and access from any method or even from outside class depending upon the access specifier.
protected $a=2;
public function method1()
{
echo $this->a;
}
public function method2()
{
echo $this->a;
}
Put it in an array
$post_array = [];
foreach($_POST as $key => $value)
{
$post_array[$key] = json_decode($value);
}
return $post_array;
and then call it like this
$post_array['create_micro_id_array'];
Since it appears you are very much aware of the variable names you want to use... I'll suggest PHP Variable variables
To do this, you can loop through your $_POST and process the value while using the key as variable name.
foreach($_POST as $key => $value)
{
$$key = json_decode($value);
}
At the end of the day, these 4 lines would generate all that... However i'm not so sure of how friendly it may appear to someone else looking at the code. Give it a shot.
You may try extract function.
extract($_POST);
I am clearing the concept of call-by-reference.Can anyone please explain the code lines below shown as an example of call-by-reference?
<?php
function test(){
$result = 10;
return $result;
}
function reference_test(&$result){
return $result;
}
reference_test($result);
?>
You have two problems.
$result is never set and the test function is never called.
You do a pass by reference on the wrong function. A pass by reference is to change the variable inside and outside the function.
Here is the solution, changed the function a bit to show you the difference. You don't need to return the variable you changed by reference.
// Pass by ref: because you want the value of $result to change in your normal code.
// $nochange is pass by value so it will only change inside the function.
function test(&$result, $nochange){
$result = 10;
$nochange = 10;
}
// Just returns result
function reference_test($result){
return $result;
}
$result = 0; // Set value to 0
$nochange = 0;
test($result, $nochange); // $result will be 10 because you pass it by reference in this function
// $nochange wont have changed because you pass it by value.
echo reference_test($result); // echo's 10
echo reference_test($nochange); // echo's 0
I know, eval is called 'evil' and it's seems to be the worst way for everything, but...
How to return complete result of eval outside of function? It is just hypotetic question, I've found easy better solution for me.
In database (want execute):
$var1 = "yes";
$var2 = "no";
include('file.php');
function:
function executeScriptData($id) {
$data = anydbhandler("SELECT `data` FROM `data` WHERE ID = $id");
if(trim($data['data']) != "") {
echo $data['data']; // echo data from database
return eval($data['data']);
}
}
calling function:
executeScriptData(someID);
echo $var1; // nothing happened :(, no result
Make sure the evalling happens in the scope you want it to (now $var1 is only available within the method executeScriptData()).
Possible solution:
function executeScriptData($id) {
$data = dbhandler("SELECT `data` FROM `data` WHERE ID = $id");
if(trim($data['data']) != "") {
return $data['data'];
}
}
$data = executeScriptData(SOMEID);
eval($data);
echo $var1;
This is impossible via return value as the docs are telling you:
http://php.net/manual/en/function.eval.php
Returnvalues:
eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned. If there is a parse error in the evaluated code, eval() returns FALSE and execution of the following code continues normally. It is not possible to catch a parse error in eval() using set_error_handler().
The return you are using there is in a subscope of eval, in an extra function. This scope cannot make your evaluation end. Otherwise eval() would not be able to define functions within its contents because every occurence of "return" would screw the code execution passed to eval().
All you can do is make a var global within your eval'ed code and overwrite it in context.
$a = true;
$myVar = "abc";
eval('global $a; global $myVar; if($a == true) { $myVar = "def"; } ');
echo $myVar;
I'm having troubles with variables inside functions and being able to read them in a index.php. Let's say I have this function (functions.php):
function firstFunction(){
$id = '1234';
secondFunction($id);
}
function secondFunction($idnumber){
if( $idnumber = 1234 ){
$name = "James"; //should say "james".
}
and in the index.php have something like that:
include(functions.php)
<?php
firstFunction();
echo $name;
?>
does anyone know a possible way to do this?, i need to be a able to read from a variable inside a function that is in another function.
Also when calling a function inside a function allow this to read a variable from the first function.
Thanks.
Variables created inside a function are local to it, you can't read their contents outside of it (because all function-local variables get deleted after the function finished running).
The improper way would be to make the $name variable global in the second function.
A better way to do it would be to use function return values: secondFunction returns $name, and firstFunction returns whatever it gets from calling secondFunction($id).
Oh, and by the way, you have another logical error in your secondFunction: Your if test will not behave like you probably intended because you are using a variable value assignment operator (=) instead of comparison (==) which always succeeds returns the assigned value that evaluates to a "true" value in most (but not all) cases.
This is very bad practice - using globals. The answer you need is:
global $name;
You need to put it above the row:
$name = "James"; //should say "james".
You declare $name inside second function, so it only exists there (that is it's "Scope").
To use it's value you need the functions to return it:
function secondFunction($idnumber){
if ( $idnumber == 1234 ){
$name = "James"; //should say "james".
}
else {
$name = "";
}
return $name;
}
function firstFunction(){
$id = 1234;
return secondFunction($id);
}
and in the index.php have something like that:
<?php
include 'functions.php';
$name = firstFunction();
echo $name;
?>
You can't call a variable like that it is out of scope what you need to do is as follows
function firstFunction(){
$id = '1234';
return secondFunction($id);
}
function secondFunction($idnumber){
if( $idnumber == 1234 ){
return "James";
}
}
Then in your index do this
<?php
include(functions.php);
echo firstFunction();
?>
A variable that is out of scope can not be accessed for example if you defined a variable inside a if statement is would only be able to be used in that statement and it is the same with the functions and variables that are inside. Thought I needed to explain my answer more.
Try this...
index.php
<?php
// Includes
include("functions.php");
// Create a variable to store the output of your function
$returned_name = firstFunction();
// Echo the variable
echo "Name: " . $returned_name;
?>
functions.php
<?php
// Function 1
function firstFunction() {
$id = "1234";
return secondFunction($id);
}
// Function 2
function secondFunction($idnumber) {
if ($idnumber == "1234") {
$name = "James";
} else if ($idnumber == "5678") {
$name = "Brian";
}
return $name;
}
?>
How can I place a variable inside a function when it is run in order to preg_match the right information. Here is my existing code:
$username = "test";
function is_txt($file) {
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9]{2}_'.$username.'.tar.gz/', $file) > 0;
}
What I am attempting to do is pull the $username variable from outside the function and allow it to be seen within it so I can pull the right matches in my while loop. While the previous comes back blank, if i do the following it works:
$username = "test";
function is_txt($file) {
$username = "test";
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9]{2}_'.$username.'.tar.gz/', $file) > 0;
}
Modify the function to take the $username variable as a parameter:
function is_txt($file, $u) {
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9]{2}_'.$u.'.tar.gz/', $file) > 0;
}
Then call it like:
$username = "test";
is_txt($file, $username);
Alternatively, you can use the global keyword to make the variable visible from the function. This is sometimes useful, but shouldn't be used all over the place. See the variable scope manual entry for more info.
You need to import the var with global:
function is_txt($file) {
global $username;
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9] {2}_'.$username.'.tar.gz/', $file) > 0;
}
But passing the value in as a parameter as explained by Jonah is a better solution in most cases.