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;
Related
<?php
class OrdersModel
{
public static function wishlistcreate($item, $user, $username){
$database = DatabaseFactory::getFactory()->getConnection();
$btc = System::bitcoinconnect();
//get the wishlist product, where username and still for sale
$wishlist = $database->prepare("SELECT * FROM products INNER JOIN wishlist ON wishlist.wishlist_product=products.id WHERE wishlist_username=? AND products.enddate > NOW() AND products.quantity > 0 AND products.enabled=1");
$wishlist->execute(array($user));
$product = $wishlist->fetch();
if($product):
$get_user_information = $database->prepare("SELECT * FROM users WHERE username=?");
$get_user_information->execute(array($user));
$user_result = $get_user_information->fetch();
$createorder = $database->prepare("INSERT INTO orders(orders_username,orders_amount,orders_product,orders_firstname, orders_lastname, orders_address1, orders_address2, orders_zipcode, orders_city, orders_country, orders_btcaddress, orders_status,orders_wishlist, orders_wishlist_user) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
//get btc address, check it's valid, then if isset run query below
$createorder->execute(array($username->username, $product->price + $product->shippingcost, $product->wishlist_product, $user_result->firstname, $user_result->lastname, $user_result->address1, $user_result->address2, $user_result->zipcode, $user_result->city, $user_result->country, $btc->getnewaddress(), 0, 1, $user,));
else:
echo 'nahhh'; //dbg
//error, item has ended or item not in users watch list.
endif;
}
I am getting the error:
Fatal error: Cannot redeclare class Bitcoin
Which is a class in a another file, here's is my $btc function:
public static function bitcoinconnect() {
include Config::get('PATH_LIBS')."jsonRPCClient.php";
//connect to bitcoin rpc use https ALWAYS!!
$bitcoin = new Bitcoin("yadda");
return $bitcoin;
}
I am using an mvc so each function counts as a page, but I have used
$btc = System::bitcoinconnect();
in another function/page, how can I go about only declaring the above code for all of that file so I don't get the cannot redeclare class.
public static function bitcoinconnect() {
include_once Config::get('PATH_LIBS')."jsonRPCClient.php";
//connect to bitcoin rpc use https ALWAYS!!
$bitcoin = new Bitcoin("yadda");
return $bitcoin;
}
I am building a custom plugin for my wordpress site.
I made a php file call "checkrank" that obtains data from a custom table named "cranking"
$uid = $GET['id'];
function checkExists($id){
global $wpdb;
$table_name = $wpdb->prefix . 'cranking';
$exists = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table_name WHERE id = %d" ) );
$error = $wpdb->print_error();
if(count($exists) > 0){
echo 'Exists!';
} else {
echo 'Does not exist!';
}
return $error;
}
checkExists($uid);
The code is just to check whether the cranking table has the user with id provided.
The problem is, whenever i run this php file, i get this error :
PHP Fatal error: Call to a member function get_row() on a non-object
Where am I at fault here? i think $wbdp is not initiated.
Your $wpdb::prepare() is missing arguments, you need to add an argument $id if you wrote %d in the query.
Source: http://codex.wordpress.org/Class_Reference/wpdb#Protect_Queries_Against_SQL_Injection_Attacks
$wpdb->prepare( "SELECT * FROM $table_name WHERE id = %d", $id )
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 have tried a few different ways to make this work to no avail.
Basically, I have these 4 lines that are in many functions:
function getID($URL){
//These 3 plus this comment line
$parentQ = "select * from cdi_content where URL=\"$URL\"";
$parentResult = mysql_query($parentQ); // Run the Query
$link = mysql_fetch_assoc($parentResult); // Query Result
...continues...
That basically tells the database to check $URL and if it matches the URL string in the database, it grabs all of the data associated with that URL, and I grab what I need with
$link['ID'];
Which would give me the ID associated with the $URL URL.
The function checks a list of conditionals that either print the 'override' variable ($ID), the default variable ($defaultID) or pulls from the server ($link['ID']), like below. The 'override' is a variable outside of the function that is currently called in by global $ID.
$ID = ''; //Overrides if set
function parseData($URL){
//Initialize Query for Table Data
$parentQ = "select * from cdi_content where URL=\"$URL\"";
$parentResult = mysql_query($parentQ); // Run the Query
return mysql_fetch_assoc($parentResult); // Query Result
};
function getID($URL){
global $ID;
$serverID = parseData($URL);
if(empty($ID)){
if(empty($serverID)){
echo $defaultID;
} else { echo $serverID['ID']; }
}//end of ifs
else
{ echo $ID; }
};
So you you want to parse the data row you would need search criteria $criterion and a field you you want it to return:
function getField($criterion, $returnField){
$parentQ = "select * from cdi_content where URL='".$criterion."' LIMIT 1"; // also make sure you that $criterion is safe to use in a query
$parentResult = mysql_query($parentQ); // Run the Query
if ($parentResult)
{
$row = mysql_fetch_assoc($parentResult);
return $row[$returnField];
}
else
{
return FALSE;
}
}
Now you can call it:
$linkId = getField($url, 'ID');
If I'm understanding you correctly, you're just trying to refactor that function so you don't have to keep on re-writing it. Is that correct?
If so, you can extract a new function like this:
function getLink($URL){
$parentQ = "select * from cdi_content where URL=\"$URL\"";
$parentResult = mysql_query($parentQ); // Run the Query
return mysql_fetch_assoc($parentResult);
}
And then call it like this:
function getID($URL){
$link = getLink($URL);
}
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.