i have this code in actions.class.php
public function executeListmatches(sfWebRequest $request)
{
$form_values = $request->getParameter('match_form', array());
global $gender_id2 = $form_values['gender2'];
global $age1 = $form_values['age1'];
$age2 = $form_values['age2'];
$province_id = $form_values['id'];
echo "in list matches ".$gender_id2." ".$age1." ".$age2." ".$province_id;
$this->pager = $this->setupPager();
$this->matching_rows = RcProfileTablePeer::getAllBySelection($gender_id2,$age1,$age2,$province_id);
return sfView::SUCCESS;
}
and then
protected function setupPager()
{
echo "in pager ".$gender_id2." ".$age1." ".$age2." ".$province_id;
$pager = new sfPropelPager('RcProfileTable', 10);
$pager->setCriteria(RcProfileTablePeer::getAllBySelection($GLOBALS['gender_id2'],$GLOBALS['age1'],$GLOBALS['age2'],$province_id));
$pager->setPage($this->getRequestParameter('page', 1));
$pager->init();
return $pager;
}
when i use the global keyword i get and error:
PHP Parse error: syntax error, unexpected '=', expecting ',' or ';' in actions.class.php on line 41
when i use $GLOBALS['gender_id2'] the value is null
i need to setup a pager because i need to list all rows that matches my selection criteria
in RcProfileTablePeer i have:
static public function getAllBySelection($gender2,$age1,$age2,$province_id)
{
echo $gender2." ".$age1." ".$age2." ".$province_id;
$criteria = new Criteria();
$criteria->add(RcProfileTablePeer::GENDER_ID,$gender2, Criteria::EQUAL);
$criteria->add(RcProfileTablePeer::AGE,$age1,Criteria::GREATER_EQUAL);
$criteria->addAnd(RcProfileTablePeer::AGE,$age2,Criteria::LESS_EQUAL);
if ($province_id <> 10)
$criteria->addAnd(RcProfileTablePeer::PROVINCE_ID,$province_id, Criteria::EQUAL);
return self::doSelect($criteria);
}
please help, i dont know how else i must do this.
thank you
There just is a parse error in your code. The PHP interpreter tells you this. You can't declare a global variable, and assign it in one statement.
global $gender_id2 = $form_values['gender2'];
must be
global $gender_id2;
$gender_id2 = $form_values['gender2'];
Other than that, as OZ_ already stated, don't use globals.
Related
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
I have a problem with functions. I create functions to send e-mails. I'm trying to create function, for example: I call function with variable ($product_id), and depends on this product id, I would like to send e-mails.
<?php
$product_id = 2000;
echo select_users_to_send($product_id);
function get_product_type($id_product){
// Define product group
global $wpdb;
$sql = "SELECT n_products.Product_Group
FROM tsales_funnel_mrecord
LEFT JOIN n_products on tsales_funnel_mrecord.Product_type = n_products.Product_Code
WHERE ID = $id_product";
$type_product = $wpdb->get_var($sql);
return $type_product;
}
function select_users_to_send($type = get_product_type($product_id)){
return $type.' user';
}
?>
I wrote this code, but it didn't works for me. Shows error:
Parse error: syntax error, unexpected '(', expecting ')'
Maybe there need to use classes? But I didn't understand how to write classes.
try this
function select_users_to_send($product_id){
$type = get_product_type($product_id)
return $type.' user';
}
Try this:
This code solved the error "Parse error: syntax error, unexpected '(',
expecting ')'"
<?php
$product_id = 2000;
echo select_users_to_send($product_id);
function get_product_type($id_product){
// Define product group
global $wpdb;
$sql = "SELECT n_products.Product_Group
FROM tsales_funnel_mrecord
LEFT JOIN n_products on tsales_funnel_mrecord.Product_type = n_products.Product_Code
WHERE ID = $id_product";
$type_product = $wpdb->get_var($sql);
return $type_product;
}
// getting output from the function
$type = get_product_type($product_id);
// passing the $type var
function select_users_to_send($type){
return $type.' user';
}
?>
You can create class like this. But You can solved your issue using first answer, This is only example for your knowledge for classes
select_user.php
class select_user{
# Start function get_product_type
function get_product_type($id_product){
// Define product group
global $wpdb;
$sql = "SELECT n_products.Product_Group
FROM tsales_funnel_mrecord
LEFT JOIN n_products on tsales_funnel_mrecord.Product_type = n_products.Product_Code
WHERE ID = $id_product";
$type_product = $wpdb->get_var($sql);
return $type_product;
}
# Start function select_users_to_send
function select_users_to_send($product_id){
$type = get_product_type($product_id);
return $type.' user';
}
}# End Class
Now create PHP file for call to class
# include class file path
include ('select_user.php');
# create class object
$user_create = new select_user();
# Call methord of class class_name
$product_id = 2000;
$return_val = $user_create->select_users_to_send($product_id);
echo $return_val;
I want to modularize functions, but this is not working...
class Review {
public function show_report($db, $id){
// Query the DB on $id
$x = $this->get_survey($db, 1);
$y = $this->get_survey($db, 2);
// Use x and y to build a report
return $a_report;
}
private function get_survey($db, $n){
// Query the DB for a certain survey number
if($n == 1){
// Perform some logic
} else {
// Perform some other logic
}
return $a_survey;
}
};
Using the class like this..
<?php
include_once('api/Review.class.php');
$r = new Review();
?>
<p>
<?php
echo Review::show_report($db, $id);
?>
</p>
PHP throws this:
Fatal error: Using $this when not in object context in Review.class.php
Thanks for the help!
Your design pattern is good, you just have a syntax error. You have missed the $ sign on your method calls in show_report(), it should look like this:
public function show_report($db, $id){
// Query the DB on $id
$x = $this->get_survey($db, 1);
$y = $this->get_survey($db, 2);
// Use x and y to build a report
return $a_report;
}
Also, the semicolon at the end of the class is unnecessary.
Finally, as another person mentioned, you need to call show_report with parameters, like this:
echo $r->show_report($db, $id);
Inside your function show_report($db, $id) is the this pointer without the prefixing $ sign which causes the syntax error. Additionally in the second part the function isn't called with parameters.
The function has to look like that:
public function show_report($db, $id){
// Query the DB on $id
$x = $this->get_survey($db, 1);
$y = $this->get_survey($db, 2);
// Use x and y to build a report
return $a_report;
}
echo $r->show_report;
In this example, you are attempting to call the function with no arguments. If this is really what you are doing, that would be at least one problem.
Instead, call the function with arguments:
echo $r->show_report('foo', 1);
Thank you all. I fixed all the syntax errors, thanks to https://stackoverflow.com/a/19258788/1004107. This is the root of the issue I do believe:
<?php
include_once('api/Review.class.php');
$r = new Review();
?>
<p>
<?php
echo Review::show_report($db, $id);
?>
</p>
Should be...
<?php
include_once('api/Review.class.php');
$r = new Review();
?>
<p>
<?php
echo $r->show_report($db, $id);
?>
</p>
And this is do to static context? Please comment.
I have the following code on my site:
$statusMessageSQL = "SElECT * FROM statusmessages";
$statusMessagePrepare = $db->prepare($statusMessageSQL);
$statusMessagePrepare->execute();
$statusMessageResult = $statusMessagePrepare->fetchAll();
foreach($statusMessageResult as $row){
$row['username']=$db->getUsername($db->getUserNameById($row['posterID']));
$results[] = $row;
$smarty->assign('results', $results);
}
It works without any problems, but now I wanted to put most of this in my database class to work more object oriented. But I have some problems returning the array. I have done this
$statusMessage = $db->getStatusMessages();
var_dump($statusMessage);
The function:
function getStatusMessage(){
$statusMessageSQL = "SElECT * FROM statusmessages";
$statusMessagePrepare = $db->prepare($statusMessageSQL);
$statusMessagePrepare->execute();
$statusMessageResult = $statusMessagePrepare->fetchAll();
foreach($statusMessageResult as $row){
$row['username']=$db->getUsername($db->getUserNameById($row['posterID']));
$results[] = $row;
}
return $results;
}
But this just tells me, that my array is null. so there have to be an problem with my returning. How do I do it correctly?
My database entries are statusID, posterID, statusMessage, dateTime, sumRating and sumVotes.
And what do I do if I want to also return an entry of another table? Like, I have the givenName and familyName of the poster (posterID) on another table. How do I also return this data?
Okay I got it. First of all, I made the mistake, that I - as #slugonamission said - that I made a spelling mistake in the function name. Then, I changed my forloop in the home.php from
$statusMessage = $db->getStatusMessage();
for($i = 0; $i < sizeof($statusMessage); $i++){
$smarty->assign('results', $statusMessage[$i]);
}
to this, because the [$i] at the end made the forloop only use the last entry of the database and from that only the first letter.
$statusMessage = $db->getStatusMessage();
for($i = 0; $i < sizeof($statusMessage); $i++){
$smarty->assign('results', $statusMessage);
}
Now what I'm working on is how to get data from other tables, too.
function getStatusMessage(){
global $db; // this is what you actually need to make function work
$sql = "SElECT s.*, username FROM statusmessages s JOIN users u ON posterID.=u.id";
$stm = $db->prepare($sql);
$stm->execute();
return $stm->fetchAll();
}
note that you have to use JOIN to get associated info
You have to parse your $db variable to your function:
function my_function() {
global $db;
// some code
}
or to use it like this:
class myClass {
private $db;
public function __construct() {
$this->db = new MySQLi("host","user","pass","db");
}
public function my_function() {
$my_db_query = $this->db->query('query');
}
}
I searched forever trying to find an answer, but was ultimately stumped. I've been writing code to allow multiple bots to connect to a chat box. I wrote all the main code and checked it over to make sure it was all okay. Then when I got to calling the function needed to make it work, it gave me an error saying:
Notice: Undefined variable: ip in C:\wamp\www\BotRaid.php on line 40
And also an error saying:
Fatal Error: Cannot access empty property in C:\wamp\www\BotRaid.php
on line 40
( Also a screenshot here: http://prntscr.com/ckz55 )
<?php
date_default_timezone_set("UCT");
declare(ticks=1);
set_time_limit(0);
class BotRaid
{
public $ip="174.36.242.26";
public $port=10038;
public $soc = null;
public $packet = array();
##############################
# You can edit below this #
##############################
public $roomid="155470742";
public $userid = "606657406";
public $k = "2485599605";
public $name="";
public $avatar=;
public $homepage="";
##############################
# Stop editing #
##############################
public function retry()
{
$this->connect($this->$ip,$this->$port); //Line 40, where I'm getting the error now.
$this->join($this->$roomid);
while($this->read()!="DIED");
}
public function connect($ip, $port)
{
if($this->$soc!=null) socket_close($this->$soc);
$soc = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
if(!$this->$soc)$this->port();
if(!socket_connect($this->$soc,$this->$ip,$this->$port))$this->port();
}
public function port()
{
$this->$port++;
if($this->$port>10038) $this->$port=10038;
$this->retry();
}
public function join($roomid)
{
$this->send('<y m="1" />');
$this->read();
$this->send('<j2 q="1" y="'.$this->$packet['y']['i'].'" k="'.$this->$k.'" k3="0" z="12" p="0" c"'.$roomid.'" f="0" u="'.$this->$userid.'" d0="0" n="'.$this->$name.'" a="'.$this->$avatar.'" h="'.$this->$homepage.'" v="0" />');
$this->port();
$this->$roomid;
}
public function send($msg)
{
echo "\n Successfully connected.";
socket_write($this->$soc, $this->$msg."\0", strlen($this->$msg)+1);
}
public function read($parse=true)
{
$res = rtrim(socket_read($this->$soc, 4096));
echo "\nSuccessfully connected.";
if(strpos(strtolower($res), "Failed"))$this->port();
if(!$res) return "DIED";
$this->lastPacket = $res;
if($res{strlen($res)-1}!='>') {$res.=$this->read(false);}
if($parse)$this->parse($res);
return $res;
}
public function parse($packer)
{
$packet=str_replace('+','#più#',str_replace(' ="',' #=#"',$packet));
if(substr_count($packet,'>')>1) $packet = explode('/>',$packet);
foreach((Array)$packet as $p) {
$p = trim($p);
if(strlen($p)<5) return;
$type = trim(strtolower(substr($p,1,strpos($p.' ',' '))));
$p = trim(str_replace("<$type",'',str_replace('/>','',$p)));
parse_str(str_replace('"','',str_replace('" ','&',str_replace('="','=',str_replace('&','__38',$p)))),$this->packet[$type]);
foreach($this->packet[$type] as $k=>$v) {
$this->packet[$type][$k] = str_replace('#più#','+',str_replace('#=#','=',str_replace('__38','&',$v)));
}
}
}
}
$bot = new BotRaid; //This is where I had the error originally
$bot->retry();
?>
Line 40 is below the "Stop Editing" line. Anyone have any suggestions? Or perhaps need me to clear some things up?
You are accessing the properties of the class incorrectly.
The line:
$this->connect($this->$ip,$this->$port);
Should be:
$this->connect($this->ip, $this->port);
Since there was no local variable called $ip, your expression was evaluating to $this-> when trying to access the property since PHP lets you access properties and functions using variables.
For example, this would work:
$ip = 'ip';
$theIp = $this->$ip; // evaluates to $this->ip
// or a function call
$method = 'someFunction';
$value = $this->$method(); // evaluates to $this->someFunction();
You will have to change all the occurrences of $this->$foo with $this->foo since you used that notation throughout the class.
As noted in the comment by #Aatch, see the docs on variable variables for further explanation. But that is what you were running into accidentally.