Unable To Access PHP Global Variable - php

I am trying to pull global variable $nsfw but it shows nothing at all. If I echo it inside function, it works. But outside, it fails even when defined as global. Kindly help me out here.
<?php
if(!function_exists('do_example_work'))
{
function do_example_work()
{
global $nsfw;
include("includes/dbconnect.php");
// Create connection
$conn = new mysqli($DBHOST, $DBUSER, $DBPASS, $DBNAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT fieldname FROM table WHERE name='$anything'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if ($row["fieldname"] == 1) {
// do somethin
$nsfw = 25;
exit();
} else {
echo "enjoy";
}
}
} else {
echo "0 results";
}
}
echo $nsfw;
};
?>

There are arguments for and against Globals. You can search Stack and the internet and read about:
Globals are bad in many ways, and should be avoided where possible
Globals are not bad, and can be fine/safe to use if you know what you are
doing
The manual:
http://php.net/manual/en/functions.user-defined.php
You seem to be over complicating things with this basic user defined function.
OUT
If you want to get data out of a function, just use the return statement
function do_example_work() {
// Do some stuff here
$nsfw = 25;
return $nsfw; // Return where needed, in conditional statement or end of function
}
// Will echo "25"
echo do_example_work();
IN
FYI:
To get data into the function from outside, just pass the data into your function from the outside as an argument:
function do_example_work($nsfw) {
/** The var "$nsfw" will have whatever data you pass in through the function call
* You can use it as required - check if $nsfw == something
* Or it might be database login details (urgh)
*/
echo $nsfw." - And words from in the function";
}
// Will echo "Pass in argument - And words from in the function"
do_example_work("Pass in argument");

The keyword global in front of a variable name means that the variable is defined somewhere outside the function, and now I want to use that variable. It does not generate a global variable. So you need to define the variable outside the function, and then you can use that variable inside a function using the global keyword in front of it.
In your code I cannot see you defining the variable outside the function. You are just echoing it out at the bottom of your code.

Any specific reason for keeping global variable inside method ?? Move it outside method and it should work for u.
Or
Try GLOBALS as shown below.
function doit() { $GLOBALS['val'] = 'bar'; } doit(); echo $val;
Gives the output as :
bar
Or
<?php
foo();
bar();
function foo() { global $jabberwocky; $jabberwocky="test data<br>"; bar(); } function bar() { global $jabberwocky; echo $jabberwocky; } ?>

Related

PHP variables in function argument is not working

I've retried solving this, by using a condition and a default attribute as recommended.
User-generated data is declared before to $Variable_1:
<?php
$Variable_1 = 'abc123!' //The user inputs the data
if ($booleanvalue == true) { // User selects if they've put data
name($user_data, $Variable_0 = $Variable_1 );
}
//Then the function will use the user's data from $Variable_1
function name($user_data, $Variable_0 = null) {
//Other code...
}
$Variable_2 = name($user_data);
$data['variable_2'] = $Variable_2;
?>
Is it possible to have $Variable_0 pre-declared and then put as an argument?
you have a few mistakes in your code. and I don't think that you can use a function named name.
you could do it this way for example:
<?php
$Variable_1 = 'abc123!';
function test($data) {
global $Variable_1;
//Other calculations...
return $Variable_1 . $data;
}
$testdata = "huhu";
$Variable_2 = test($testdata);
$data['variable_2'] = $Variable_2;
echo $data['variable_2'];
?>
I agree with the comment by El_Vanja, but you can access a global variable through the magic $GLOBALS array anywhere.
<?php
// what you might actually want
function name($variable = 'abc123!')
{
// if no value is passed into the function the default value 'abc123!' is used
}
$variable = 'abc123!';
// what you could do
function name2($variable)
{
// $variable can be any value
// $globalVariable is 'abc123!';
$globalVariable = $GLOBALS['variable'];
}
I'd also like to point out that currently you have no way of controlling what type of data is passed to the function. You might consider adding types.
<?php
<?php
// string means the variable passed to the function has to be a ... well string
function name(string $variable = 'abc123!'): void
{
// void means the function doesn't return any values
}
name(array()); // this throws a TypeError

PHP: $_POST variables unexistant into functions

I am bringing some info trough $_POST, but when I try to make use of this info into any function, console emerges an error about Undefined Variable (in this example, $ms_img brings an error, as well as $con -the connection query declared on conexionbbdd.php- and any othe variable inside functions.
EDIT: Neither passing as arguments works, it emerges one error per argument as this:
Warning: Missing argument 1 for checkCost(), called in C:\wamp\www...\actions\msg_newMessage.php on line 96 and defined in C:\wamp\www...\actions\msg_newMessage.php on line 17
function checkCost($con,$ms_img,$id){...}
CODE:
<?php
session_start();
include("../conexionbbdd.php");
include("../conexionapi.php");
$id = $_SESSION['id'];
$inclass = $_SESSION['inclass'];
if($_SESSION['estado'] == 'activo'){
$ms_content = $_POST['ms_content'];
$ms_img = $_POST['ms_img'];
$ms_prefix = $_POST['ms_prefix'];
$ms_phone = $_POST['ms_phone'];
function checkCost(){
$totalCost = 0;
if ($ms_img!=""){
$totalCost=2;
}
else{
$totalCost=1;
}
$checkCredits=mysqli_query($con,"SELECT us_credits FROM ws_users WHERE us_id=$id");
}
function sendMessage(){
//WHATEVER
}
if($inclass==='1'){
checkCost();
}
else{
sendMessage();
}
}else{
header('location:../login.php');
}
?>
You can have access to superglobal variables like $_POST in any function. But global variables such as $con that should be initialized in an including file is not accessable in a function. You can pass it as parameter. And do not use the global keyword to inject global vars into a funciton. In long term this can result very confusing code. So you could do:
function checkCost($con){
$ms_content = $_POST['ms_content'];
$ms_img = $_POST['ms_img'];
$ms_prefix = $_POST['ms_prefix'];
$ms_phone = $_POST['ms_phone'];
$totalCost = 0;
if ($ms_img!=""){
$totalCost=2;
}
else{
$totalCost=1;
}
$checkCredits=mysqli_query($con,"SELECT us_credits FROM ws_users WHERE us_id=$id");
}
But its still very procedural. I recommend you to start to read OOP.

PHP, DB connection in Function. Is Separate Connection Mandatory?

I am using in my PHP file a function which is defines inside the PHP file. He structure of the code is like below
//--- db connection
$dbconn = pg_connect(...
// function definition
function myfunction(){
$f_stmt = '.....'
$f_result = pg_query_params($dbconn,$f_stmt, ....
$val = pg_fetch_result($f_result, 'COL_VAL');
return $val;
}
//---- general logic
$stmt = '....'
$result = pg_query_params($dbconn,$stmt, ....
while ($row = pg_fetch_assoc($result)) {
echo myfunction()
}
When I am trying to use the same connection in the function $dbconn like tje sample above I am receiving a connection error. When I create a new connection $dbconn2 inside the function for its own usage it works. If this is the solution isn't it bad for the performance? or is there a proper way?
make your connection variable $dbconn to global variable ,
function myfunction(){
global $dbconn;
$f_stmt = '.....'
$f_result = pg_query_params($dbconn,$f_stmt, ....
$val = pg_fetch_result($f_result, 'COL_VAL');
return $val;
}

PHP SQL Function

Can someone please tell me why my function is not working?
function myappsbdo($sqlquery, $tabname)
{
try
{
$pdo = new PDO("mysql:host=127.0.0.1;port=3306;dbname=myapps","root","");
}
catch (PDOException $e)
{
echo "Problème de connexion";
exit();
}
$sql = $sqlquery;
$result = $pdo->query($sql);
$tabname = $result->fetchALL(PDO::FETCH_NUM);
}
I do a var_dump of the variable I chose for my $tabname and it's an empty array. There is suppose to have my db data in it...
Thanks!
EDIT: this is how I call it.
myappsbdo("SELECT * FROM categorie", $tab1);
The function argument $tabname was passed by value, therefore your subsequent assignment to that variable changes only the value of the function-scoped variable $tabname and not of the calling-scoped variable $tab1.
You want to pass by reference instead:
function myappsbdo($sqlquery, &$tabname) {
// ^---- notice the ampersand character
// etc.
$tabname = $result->fetchALL(PDO::FETCH_NUM);
}
Or, alternatively, return the resultset:
function myappsbdo($sqlquery) {
// etc.
return $result->fetchALL(PDO::FETCH_NUM);
}
$tab1 = myappsbdp('SELECT * FROM categorie');
Note that you probably ought to make your PDO object static, so that the database connection can be reused in successive function calls.

How to create an instance of a class in another class

I might be missing something here, I'm not sure. A Google search didn't really help either.
What I'm wanting to do is call the databaseServer class and use its methods within my userControl class. Here is my lib_class.php file:
<?php
include('definitions.php');
class databaseServer {
var $con;
var $db;
var $close;
var $qry;
var $sql;
function connect($host,$user,$pw,$db) {
$this->con = mysql_connect($host,$user,$pw);
if (!$this->con) {
die('Could not connect: ' . mysql_error());
}
else {
echo "Database Connected";
}
$this->selectDb($db);
}
function selectDb($database) {
$this->db = mysql_select_db($database,$this->con);
if (!$this->db) {
echo "Could not Select database";
}
else {
echo "Database Selected";
}
}
function disconnect() {
$this->close = mysql_close($this->con);
if ($this->close) {
echo "Disconnected";
}
}
function query($test) {
if (!mysql_query($test)) {
die("Error: " . mysql_error());
}
}
} // databaseServer
class cookie {
var $expireTime;
function set($name,$value,$expiry) {
$this->expireTime = time()+60*60*24*$expiry;
setcookie($name,$value,$expireTime);
}
function delete($name) {
setcookie($name,"",time()-3600);
}
function check($name) {
if (isset($_COOKIE["$name"]))
echo "Cookie Set";
else
echo "Cookie failed";
}
} //cookie
class userControl {
public function __construct(databaseServer $server) {
$this->server = new databaseServer();
}
function createUser($uname,$pword) {
$this->server->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$result = $this->server->query("SELECT * FROM user_list WHERE uname='" . $this->server->real_escape_string($uname) . "'");
if ($this->result->num_rows() === 0) {
if ($this->server->query("INSERT INTO user_list (uname, pword)
VALUES ('" . $this->server->real_escape_string($uname) . "','" . $this->server->real_escape_string($pword) . "')") {
echo "User Added Successfully!";
}
else {
echo "Error Adding User!";
}
}
else {
echo "User Already Exists!";
}
} // createUser
} // userControl
?>
However, this isn't working and I can't see why. My databaseServer and cookie classes work fine when I omit the userControl class from the file, so I know the error must be in that class somewhere. OOP is something I'm trying to learn and I keep stumbling.
The echoes in the databaseServer class are there only for me to test it. I am implementing the classes in an index.php file as follows:
<?php
include('definitions.php');
include('class_lib.php');
$bmazed = new databaseServer();
$bmazed->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$sql = "INSERT INTO blah
VALUES ('testing 92')";
$bmazed->query($sql);
$bmazed->disconnect();
// $control = new userControl();
// $uname = "Test1";
// $pword = "test1";
// $control->createUser($uname,$pword);
echo "<br />";
echo "<br />";
?>
Lines have been commented out for testing purposes, so I don't have to keep re-writing code.
I really have no idea where the problem lies, I've checked syntax and everything seems fine.
You cannot assign class or instance properties that depend on runtime information when you declare the classes. See the chapter on Class Properties in the PHP Manual.
Change the class to read:
class userControl
{
protected $_server;
public function __construct ()
{
$this->_server = new databaseServer();
}
}
Also, to access class/instance members, you have to to use the $this keyword, e.g.
$this->_server->connect();
On a sidenote, while composition is fine, aggregation is better. It helps your code staying maintainable and loosely coupled, which means it will be much easier to replace components, for instance when writing UnitTests. So consider changing the constructor to use Dependency Injection.
Initialize $server in the constructor:
class userControl {
private $server;
function __construct() {
$this->server = new databaseServer();
}
function createUser($uname,$pword) {
$this->server->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$result = $this->server->query("SELECT * FROM user_list WHERE uname='" . $this->server->real_escape_string($uname) . "'");
if ($this->result->num_rows() === 0) {
if ($this->server->query("INSERT INTO user_list (uname, pword) VALUES ( '" . $this->server->real_escape_string($uname) . "','" . $this->server->real_escape_string($pword) . "')") {
echo "User added Succesfully";
}
else {
echo "Error Adding User";
}
else {
echo "User already exists";
}
}
}
For one, $server won't be accessible from within createUser() because it's in a different scope. PHP scope works a bit differently than one would expect from a C-style language.
Try either passing the $server to createUser(), or initializing the server in createUser(), in which case you should probably have a getServer() function so that you're not initializing it needlessly.
The third option is by far the worst, which is doing "global $server" at the top, inside the function. But it's very bad practice. You have been warned.
Last but not least, you should probably look for COUNT(*) than * in the SQL query, because otherwise you're selecting all the users. :)
If you want further information on PHP's scope, see here (highly recommended):
http://php.net/manual/en/language.variables.scope.php
Hope it helps!
The syntactical stuff certainly was a problem. But even more fundamentally wrong with my code was the fact that the databaseServer->query method doesn't return a value. Making it return a value fixed the problem.
I think, sometimes, it's not possible to see the wood for the trees. :)

Categories