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');
}
?>
1 Answer 1
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.
-
I do need OOP, that's for sure. But it is still a bit confusing for me. Thank you for your explanation, worked.Biomehanika– Biomehanika2015年09月11日 10:55:11 +00:00Commented Sep 11, 2015 at 10:55
global
.glob
to inject global vars into a funciton. In long term this can result very confusing code.