Here is my class :
class ProfileLink {
function profileLink(PDO $pdo, $string, $i=0)
{
if ($i!=0) {
$link = $string . '-' . $i;
} else {
$link = $string;
}
$req = $pdo->prepare('SELECT link FROM users WHERE link = ?');
$req->execute(array($link));
$nb = $req->rowCount();
$req->closeCursor();
if ($nb > 0) {
$i++;
return profileLink($pdo, $string, $i);
} else {
return $link;
}
}
}
When I call the profileLink function from the class, it doesn't work, but if I call it outside the class, everything is ok. It might be a problem with the PDO, what do you think ?
require_once ('lib/profileLink.class.php');
$profileLink = new ProfileLink();
$link = $profileLink->profileLink($pdo, $string);
I would store the instance of PDO as a class property so that it can be easily accessed within the class. Note that my example uses slightly different syntax (modern PHP).
class ProfileLink {
protected $pdo;
public function __construct(PDO $pdo) {
$this->pdo = $pdo;
}
public function profileLink($string, $i=0)
{
if ($i!=0) {
$link = $string . '-' . $i;
} else {
$link = $string;
}
$req = $this->pdo->prepare('SELECT link FROM users WHERE link = ?');
$req->execute(array($link));
$nb = $req->rowCount();
$req->closeCursor();
if ($nb > 0) {
$i++;
return profileLink($string, $i);
} else {
return $link;
}
}
}
$profileLink = new ProfileLink($pdo);
2 Things:
here
return profileLink($pdo, $string, $i);
you are missing a $this, because it's no regular function but a class method:
return $this->profileLink($pdo, $string, $i);
And second, your method has the same name as the class (except of the first capital letter), and thus seems to be interpreted as constructor. I have just tested this:
class Test {
function test() {
echo "test";
}
}
$t = new Test();
And it outputs "test".
So you should rename your method to getLink or something similar.
Related
I tied it myself but it does not work for me. How to properly change for example this old code to be compatible with php 7.x?
class DbSimple_Generic
{
function& connect($dsn)
{
// Load database driver and create its instance.
$parsed = DbSimple_Generic::parseDSN($dsn);
if (!$parsed) {
$dummy = null;
return $dummy;
}
$class = 'DbSimple_'.ucfirst($parsed['scheme']);
if (!class_exists($class)) {
$file = str_replace('_', '/', $class) . ".php";
if ($f = #fopen($file, "r", true)) {
fclose($f);
require_once($file);
} else {
$base = basename($file);
$dir = dirname(__FILE__);
if (#is_file($path = "$dir/$base")) {
require_once($path);
} else {
trigger_error("Error loading database driver: no file $file in include_path; no file $base in $dir", E_USER_ERROR);
return null;
}
}
}
$object =& new $class($parsed);
if (isset($parsed['ident_prefix'])) {
$object->setIdentPrefix($parsed['ident_prefix']);
}
class DbSimple_Mysql_Blob extends DbSimple_Generic_Blob
{
var $blobdata = null;
var $curSeek = 0;
function DbSimple_Mysql_Blob(&$database, $blobdata=null)
{
$this->blobdata = $blobdata;
$this->curSeek = 0;
}
function read($len)
{
$p = $this->curSeek;
$this->curSeek = min($this->curSeek + $len, strlen($this->blobdata));
return substr($this->blobdata, $this->curSeek, $len);
}
function write($data)
{
$this->blobdata .= $data;
}
function close()
{
return $this->blobdata;
}
function length()
{
return strlen($this->blobdata);
}
}
function& _performNewBlob($blobid=null)
{
$obj =& new DbSimple_Mysql_Blob($this, $blobid);
return $obj;
}
I tried to use every possible way to make this work like this:
$object = new $class($parsed);
$object->method();
Becase it seems for PHP 7.x is this the most problematic part:
$object =& new $class($parsed);
But thisdid not work. I tried to find it on some PHP documentation but no luck so far. So how to properly rewrite this? Thank you
Using this on Ubuntu Server 64bit 16.04+ with Apache and mysql.
Probably it is a better idea to understand that function and rewrite in a cleaner way but please find below my changes, hopefully it helps.
class DbSimple_Generic
{
function connect($dsn)
{
// Load database driver and create its instance.
$parsed = DbSimple_Generic::parseDSN($dsn);
if (!$parsed) {
$dummy = null;
return $dummy;
}
$class = 'DbSimple_'.ucfirst($parsed['scheme']);
if (!class_exists($class)) {
$file = str_replace('_', '/', $class) . ".php";
if ($f = #fopen($file, "r", true)) {
fclose($f);
require_once($file);
} else {
$base = basename($file);
$dir = dirname(__FILE__);
if (#is_file($path = "$dir/$base")) {
require_once($path);
} else {
trigger_error("Error loading database driver: no file $file in include_path; no file $base in $dir", E_USER_ERROR);
return null;
}
}
}
$object = new $class($parsed);
if (isset($parsed['ident_prefix'])) {
$object->setIdentPrefix($parsed['ident_prefix']);
}
}
public static function parseDSN($dsn){ // public or private depends on what you intend to do
// implementation here...
}
public function setIdentPrefix($identPrefix){
// implementation here...
}
}
class DbSimple_Mysql_Blob extends DbSimple_Generic_Blob
{
var $blobdata = null;
var $curSeek = 0;
function __construct($blobdata=null) // use __construct for class constructor
{
$this->blobdata = $blobdata;
$this->curSeek = 0;
}
function read($len)
{
$p = $this->curSeek;
$this->curSeek = min($this->curSeek + $len, strlen($this->blobdata));
return substr($this->blobdata, $this->curSeek, $len);
}
function write($data)
{
$this->blobdata .= $data;
}
function close()
{
return $this->blobdata;
}
function length()
{
return strlen($this->blobdata);
}
}
function _performNewBlob($blobid=null)
{
$obj = new DbSimple_Mysql_Blob($blobid); // no need to use &
return $obj;
}
Just don't ever use =& operator. It's been useless since PHP 5.0 and removed in PHP 7.0:
http://php.net/manual/en/migration70.incompatible.php#migration70.incompatible.other.new-by-ref
You will find more things on that page that no longer work in PHP 7.
I am calling functions with ajax POST and then trying to access objects in class, but for some reason i am getting an NULL after calling an class function
Here is my code
include_once dirname(__FILE__).'/../db/_mysql.php';
include_once dirname(__FILE__).'/../class/door.php';
$db = new _mysql();
if (isset($_POST['door'])) {
if ($_POST['door'] == 'get-default') {
$doors = array();
for ($i = 0; $i < $_POST['amount']; $i++) {
array_push($doors, array(
'door-id' => $i,
'panel-colors' => 'valkoinen'
)
);
}
order_door::setDoors($doors);
}
if ($_POST['door'] == 'get-doors') {
print_r(order_door::getDoors());
$doors = order_door::getDoors();
if ((int) $_POST['total-count'] > count($doors)) {
echo $_POST['total-count'] . '>' . count($doors);
} else if ((int) $_POST['total-count'] < count($doors)) {
echo $_POST['total-count'] . '<' . count($doors);
}
}
}
class order_door {
private static $doors;
public static function getDoors() {
return self::$doors;
}
public static function setDoors($array) {
if (count($array) == 0) {
self::$doors = array();
} else {
self::$doors = $array;
print_r(self::getDoors());
}
}
}
in second ajax call i am trying to access to get-doors
in POST get-doors print_r(order_door::getDoors()); is not printing anything. Any ideas?
Actually this is what must happen , you didn't have any data in
private static $doors;
So you set it in one ajax request and call it in another will reset it to default.
To fix this behavior you have to save this data to SESSION for example .
I'm having an issue with a bit of my code; it was working fine until I added a single new function, now it's not working at all--it's sending "Catchable Fatal Error: Object of class story could not be converted to string". I've removed the function from the class, and still am getting that error.
<?php
class story extends StarMap
{
function __construct($X, $Y, $db)
{
$this->X = $X;
$this->Y = $Y;
$this->db = $db;
parent::__construct($this->X, $this->Y, $this->db);
#echo $this->AddStoryElement();
}
function AddStoryElement()
{
#$array = $this->selectStoryArray();
$array = array('1');
$top = mt_rand(0, 95);
$left = mt_rand(0, 95);
$html = "\n <div class='star' style='top:{$top}%; left:'{$left}%;' href='#' id='{$array[0]}'>";
$html .= "<img src='assets/stars/unknown.png' width='25' height='25'>";
$html .= "</div>";
return $html;
}
function selectStoryArray()
{
$sql = "SELECT story_id, story_type, story_content, story_url FROM storymaptopdown";
$que = $this->db->query($sql);
try {
$que->execute();
while($row = $que->fetch(PDO::FETCH_BOTH))
{
return $row;
}
}catch(PDOException $e) {}
}
}
?>
This is where the class is called
require_once('lib/bootstrap.php');
echo '<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>'.
'<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>'.
'<script src="js/hoverintent.js" type="text/javascript"></script>'.
'<script src="js/jquery.tooltip.js" type="text/javascript"></script>'.
'<script src="js/js.js" type="text/javascript"></script>'.
$map = new story($_GET['X'], $_GET['Y'], $db);
return true;
You are concatenating the result of the $map = new story() line to the previous string (the one starting with the echo). You probably meant to put a ; there not an ..
Or if you did wanted to concatenate it, define the magic __toString() method on your class.
It seems I've hit a wall here and could use some help
Would like to pass a MySql variable to a Joomla Module
Im using Yootheme's Widget-kit to display tweets from a search term. Works great and all but you need to enter the twitter search term in the Module back end.
Instead I would like to use a variable ( already used on the page) and pass that variable to the Twitter module so it can display the tweets I want
Here are some lines of PHP with the variable I'd like to use
$document->setTitle(JText::sprintf('COVERAGE_DATA_PLACE', $this->country->country_name, $this->city->city_name));
$text = JString::str_ireplace('%city_name%',$this->city->city_name,$text);
$this->setBreadcrumbs(array('country','city'));
Is there any way to take the "City" variable and send it to the 'word" field found in the twitter module?
Here is the Code for the twitter module
<?php
Class: TwitterWidgetkitHelper
Twitter helper class
*/
class TwitterWidgetkitHelper extends WidgetkitHelper {
/* type */
public $type;
/* options */
public $options;
/*
Function: Constructor
Class Constructor.
*/
public function __construct($widgetkit) {
parent::__construct($widgetkit);
// init vars
$this->type = strtolower(str_replace('WidgetkitHelper', '', get_class($this)));
$this->options = $this['system']->options;
// create cache
$cache = $this['path']->path('cache:');
if ($cache && !file_exists($cache.'/twitter')) {
mkdir($cache.'/twitter', 0777, true);
}
// register path
$this['path']->register(dirname(__FILE__), $this->type);
}
/*
Function: site
Site init actions
Returns:
Void
*/
public function site() {
// add translations
foreach (array('LESS_THAN_A_MINUTE_AGO', 'ABOUT_A_MINUTE_AGO', 'X_MINUTES_AGO', 'ABOUT_AN_HOUR_AGO', 'X_HOURS_AGO', 'ONE_DAY_AGO', 'X_DAYS_AGO') as $key) {
$translations[$key] = $this['system']->__($key);
}
// add stylesheets/javascripts
$this['asset']->addFile('css', 'twitter:styles/style.css');
$this['asset']->addFile('js', 'twitter:twitter.js');
$this['asset']->addString('js', sprintf('jQuery.trans.addDic(%s);', json_encode($translations)));
// rtl
if ($this['system']->options->get('direction') == 'rtl') {
$this['asset']->addFile('css', 'twitter:styles/rtl.css');
}
}
/*
Function: render
Render widget on site
Returns:
String
*/
public function render($options) {
if ($tweets = $this->_getTweets($options)) {
// get options
extract($options);
return $this['template']->render("twitter:styles/$style/template", compact('tweets', 'show_image', 'show_author', 'show_date', 'image_size'));
}
return 'No tweets found.';
}
/*
Function: _getURL
Create Twitter Query URL
Returns:
String
*/
protected function _getURL($options) {
// get options
extract($options);
// clean options
foreach (array('from_user', 'to_user', 'ref_user', 'word', 'nots', 'hashtag') as $var) {
$$var = preg_replace('/[##]/', '', preg_replace('/\s+/', ' ', trim($$var)));
}
// build query
$query = array();
if ($from_user) {
$query[] = 'from:'.str_replace(' ', ' OR from:', $from_user);
}
if ($to_user) {
$query[] = 'to:'.str_replace(' ', ' OR to:', $to_user);
}
if ($ref_user) {
$query[] = '#'.str_replace(' ', ' #', $ref_user);
}
if ($word) {
$query[] = $word;
}
if ($nots) {
$query[] = '-'.str_replace(' ', ' -', $nots);
}
if ($hashtag) {
$query[] = '#'.str_replace(' ', ' #', $hashtag);
}
$limit = min($limit ? intval($limit) : 5, 100);
// build timeline url
if ($from_user && !strpos($from_user, ' ') && count($query) == 1) {
$url = 'http://twitter.com/statuses/user_timeline/'.strtolower($from_user).'.json';
if ($limit > 15) {
$url .= '?count='.$limit;
}
return $url;
}
// build search url
if (count($query)) {
$url = 'http://search.twitter.com/search.json?q='.urlencode(implode(' ', $query));
if ($limit > 15) {
$url .= '&rpp='.$limit;
}
return $url;
}
return null;
}
/*
Function: _getTweets
Get Tweet Object Array
Returns:
Array
*/
protected function _getTweets($options) {
// init vars
$tweets = array();
// query twitter
if ($url = $this->_getURL($options)) {
if ($path = $this['path']->path('cache:twitter')) {
$file = rtrim($path, '/').sprintf('/twitter-%s.php', md5($url));
// is cached ?
if (file_exists($file)) {
$response = file_get_contents($file);
}
// refresh cache ?
if (!file_exists($file) || (time() - filemtime($file)) > 300) {
// send query
$request = $this['http']->get($url);
if (isset($request['status']['code']) && $request['status']['code'] == 200) {
$response = $request['body'];
file_put_contents($file, $response);
}
}
}
}
// create tweets
if (isset($response)) {
$response = json_decode($response, true);
if (is_array($response)) {
if (isset($response['results'])) {
foreach ($response['results'] as $res) {
$tweet = new WidgetkitTweet();
$tweet->user = $res['from_user'];
$tweet->name = $res['from_user'];
$tweet->image = $res['profile_image_url'];
$tweet->text = $res['text'];
$tweet->created_at = $res['created_at'];
$tweets[] = $tweet;
}
} else {
foreach ($response as $res) {
$tweet = new WidgetkitTweet();
$tweet->user = $res['user']['screen_name'];
$tweet->name = $res['user']['name'];
$tweet->image = $res['user']['profile_image_url'];
$tweet->text = $res['text'];
$tweet->created_at = $res['created_at'];
$tweets[] = $tweet;
}
}
}
}
return array_slice($tweets, 0, $options['limit'] ? intval($options['limit']) : 5);
}
}
class WidgetkitTweet {
public $user;
public $name;
public $image;
public $text;
public $created_at;
public function getLink() {
return 'http://twitter.com/'.$this->user;
}
public function getText() {
// format text
$text = preg_replace('#(https?://([-\w\.]+)+(/([\w/_\.]*(\?\S+)?(#\S+)?)?)?)#', '$1', $this->text);
$text = preg_replace('/#(\w+)/', '#$1', $text);
$text = preg_replace('/\s+#(\w+)/', ' #$1', $text);
return $text;
}
}
// bind events
$widgetkit = Widgetkit::getInstance();
$widgetkit['event']->bind('site', array($widgetkit['twitter'], 'site'));
I believe you can do what you want with this:
http://www.j-plant.com/joomla-extensions/free-extensions/26-module-plant.html
This plugin supports module parameters overriding. Use the next code
for overriding parameters:
[moduleplant id="77" <param_name_1>="<param_value_1>" <param_name_N>="<param_value_N>"]
replace and with the necessary parameter name and value.
You can override as many parameters as you want.
Available module parameters can be found in module XML manifest
file. A manifest file is usually located in the next path:
modules/<module_type>/<module_type>.xml
I'm trying to do this:
class database {
function editProvider($post)
{
$sql = "UPDATE tbl SET ";
foreach($post as $key => $val):
if($key != "providerId")
{
$val = formValidate($val);
$sqlE[] = "`$key`='$val'";
}
endforeach;
$sqlE = implode(",", $sqlE);
$where = ' WHERE `id` = \''.$post['id'].'\'';
$sql = $sql . $sqlE . $where;
$query = mysql_query($sql);
if($query){
return true;
}
}
//
}//end class
And then use this function * INSIDE of another class *:
function formValidate($string){
$string = trim($string);
$string = mysql_real_escape_string($string);
return $string;
}
//
.. on $val. Why doesn't this work? if I write in a field of the form, it's not escaping anything at all. How can that be?
* UPDATE *
handler.php:
if(isset($_GET['do'])){
if($_GET['do'] == "addLogin")
{
$addLogin = $db->addLogin($_POST);
}
if($_GET['do'] == "addProvider")
{
$addProvider = $db->addProvider($_POST);
}
if($_GET['do'] == "editProfile")
{
$editProfile = $db->editProfile($_POST);
}
if($_GET['do'] == "editProvider")
{
$editProvider = $db->editProvider($_POST);
}
}
//end if isset get do
** The editProvider function works fine except for this :-) **
You need to instantiate that validate class and than once instantiated you will need to call that function in that class with your value parameters.
Inside your editProvider you can have:
$validator = new validate();
$val = $validator->formValidate($val);
If the above doesn't work, try the following:
$val = mysql_real_escape_string(trim($val));
and see if it works, if it does it has to do with the correct function not being called.
Not sure why you are so bent on using $this vs a static implementation. IMO, a static call makes this code much easier. If you really want access to $this->formValidatString() from your database class, you will have to do class database extends MyOtherClass.
Here is how easy it would be to do a static call:
class database {
public function editProvider($post)
{
$sql = "UPDATE tbl SET ";
foreach($post as $key => $val):
if($key != "providerId")
{
$val = MyOtherClass::formValidate($val);
$sqlE[] = "`$key`='$val'";
}
endforeach;
$sqlE = implode(",", $sqlE);
$where = ' WHERE `id` = \''.$post['id'].'\'';
$sql = $sql . $sqlE . $where;
$query = mysql_query($sql);
if($query){
return true;
}
}
}//end class
class MyOtherClass
{
public static function formValidate($string) {
if (strlen($string) < 1) {
throw new Exception('Invalid $string ' . $string . ');
}
$string = trim($string);
$string = mysql_real_escape_string($string);
return $string;
}
}
You don't need to have an instance for this purpose. Just do validate::formValidate($val);.