procedural style and object oriented style - mysqli

I'm kind of confuse why that when I change from procedural style into object-oriented style, the while loop is fine ?
This is the php block on the top of my script:
$object = new mysqli('localhost', 'readmode', 'p#5sW0rd', 'practices');
$sql = 'SELECT * FROM paintings';
$result = $object->query($sql);
if ($object->connect_error) {
$error = $object->connect_error;
} else {
$num_rows = mysqli_num_rows (mysqli_query($object, $sql));
}
This is the php code inside my html:
<?php if (isset($error)) {
echo "<p>$error</p>";
} else { ?>
<pre><?php while ($rowinfo = mysqli_fetch_assoc($result)) {
print_r ($rowinfo);
} ?></pre>
<?php } ?>
When I use $object->query($sql) instead of $result, the loop becomes infinite.
(I'm jumping back and forth with the procedural style and the object-oriented style because I'm practicing with it)

famous for not knowing how to asking questions
Sad but true.
If some of your code is not working, it's better to post this very code instead of writing a long literary explanation.
When you're making it
while ($rowinfo = mysqli_fetch_assoc($object->query($sql)))
it indeed makes an infinite loop, because you are making your SQL query run over and over.
The problem has nothing to do with object syntax, it will remain the same with procedural as well. You are just supposed to use the result in stead of calling query again.
In essence, you have to run your query **only once. **
Which makes your other code snippet wrong as well. It should be
$object = new mysqli('localhost', 'readmode', 'p#5sW0rd', 'practices');
$sql = 'SELECT * FROM paintings';
$result = $object->query($sql);
if ($object->connect_error) {
$error = $object->connect_error;
} else {
$num_rows = mysqli_num_rows($result);
}
otherwise it will run your query twice.

Related

sort json facebook data

i'm trying to figure out how to sort the json data provided by a facebook events feed.
This is the code I've been using
$int_count = 1;
$FBpage = file_get_contents('https://graph.facebook.com/demo/events?access_token=170978966368624|vNXbO1MPwpvP56jU6zWGCyRESQ');
$FBdata = json_decode($FBpage);
foreach ($FBdata->data as $events )
{
$x_sdt = explode("T",$events->start_time);
$x_sd = explode("-",$x_sdt[0]);
if($x_sdt[0] > date("Y-m-d"))
{
$StatusID = explode("_", $events->id);
echo '<ul class="shows">';
echo '<li class="date">';
echo $x_sd[2]."/".$x_sd[1]."/".$x_sd[0];
echo '</li>';
echo '<li class="title">'.maxTruncate($events->name, 62).'</li>';
echo '</ul>';
}
$int_count++;
if($int_count==5){ break; }
}
Can anyone point me in the right direction, so far I beleive i should be using usort(), but when I look at tutorials i've got no idea what the go is. any bombs of wisdom would be greatly appreciated.
Thanks
Frank
With usort, you just have to write your own little comparison function, that gets two of the arrays elements as parameters, compares them by whatever metric you like, and returns a value saying which one is supposed to be considered “greater” than the other.
Have a look at the examples in the PHP manual, it’s really quite easy.
If you still can’t get it to work on your own, then please describe what you tried and on what (example) data structure.

Zend_Translate Strategy for a huge grown web site

since I'm thinking in a good way to handle translation did part of a implementation and going toward a concept that still don't know if it's good and I would like to share it and get the pros and cons of it with someone that think it's a good point to explore.
The architecture is meant to work in a componentized site with translations comming from Actions, Forms, Views, View_Helpers and even Action_Helpers.
The ideis is simple:
Zend_Translate will the got from registry in every component and will receive __FILE__ as parameter. Since it was initialized with 'clear' on bootstrap it will be possible to load just the array file that correspont to this calling compoment. When comes to the missing translations they will be logged to a database (to avoid log duplicates) and/or be added to the corresponding array file in the remaining untranslated languages (as well as have the array file created) with a null value where it's is not set yet.
My guess is that using cache and specializing Translate i can ignore the translations that are set with null (by the addition made before) without log it again (displayin just the key) it will overhead a little bit the firt call for a large untraslated page and then gain performance later as well as maintainability and work ability with the automation of the translation process that would like to supply for the user.
But after that I was figuring out that I could build a array with the missing translations from every component to be save at the request end, and that is my question.
Had you folks had some experience with this that could be helpful to determine what's the best strategy?
bootstrap
protected function _initLocale() {
$translateSession = new Zend_Session_Namespace('translate');
$locale = isset($translateSession->locale) ? $translateSession->locale : 'auto';
try {
$zendLocale = new Zend_Locale($locale);
} catch (Zend_Locale_Exception $e) {
$zendLocale = new Zend_Locale('en_US');
}
Zend_Registry::set('Zend_Locale', $zendLocale);
$translate = new Engine_Translate('customarray', array('clear'));
$logger = Engine_Logger::getLogger();
$translate->setOptions( array('log2db' => $logger ,'log' => $logger, 'logPriority' => Zend_Log::ALERT, 'logUntranslated' => true));
Zend_Registry::set('Zend_Translate', $translate);
}
simple library
function getAvailableTranslationLanguages() {
return array("pt_BR"=>"Português","en_US"=>"Inglês");
}
function setTranslationLanguage($code) {
$translateSession = new Zend_Session_Namespace('translate');
$translateSession->locale = $code;
}
function getTranslator($file) {
$relative = str_replace(APPLICATION_PATH, '', $file);
$code = Zend_Registry::get('Zend_Locale');
$path = APPLICATION_PATH . '\\lang\\' . $code . $relative;
$translator = Zend_Registry::get('Zend_Translate');
try {
$translator->addTranslation($path, $code);
} catch (Exception $e) {
createTranslationFile($path);
}
return $translator;
}
function createTranslationFile($path) {
if(!file_exists(dirname($path)))
mkdir(dirname($path), 0777, true);
$file = fopen($path, 'w');
if($file) {
$stringData = "<?php\n return array(\n );";
fwrite($file, $stringData);
fclose($file);
} else {
$logger = Engine_Logger::getLogger();
$logger->info(Engine_Logger::get_string('ERRO ao abrir arquivo de tradução: ' . $path));
}
}
The use
class App_Views_Helpers_Loginbox extends Zend_View_Helper_Abstract
{
public function loginbox() {
$translate = getTranslator(__FILE__);
Translation resources
If I understand correctly, you want to create new adapter for each action helper/ view helper/ etc. This is IMO wrong and hugely ineffective. I would stick the translations to URLs. Make one common.php for translations used everywhere, module.php for module-specific and page-name.php for page specific translation. Then array_merge them together and create one adapter in Bootstrap. Then cache it (using URL as the cache key) somewhere - prefferably in memory (=memcached, apc). That way you would create the translate adapter from cache very effectively - only load+unserialize. Many translations (for each helper) means many disc accesses, means lower speed and scalability as disc will soon be the bottleneck.

How to add two numbers in sugar crm

I made module addition and in this made three fields amount1_c, amount2_c and total_amount_c to add the two numbers and display the result in the third field. I done coding in the logic looks here is my code
<?
$hook_version = 1;
$hook_array = Array();
$hook_array['before_save'] = Array();
$hook_array['before_save'][] = Array(1,'calculate_field', 'custom/modules/cases/LogicHookMath.php','LogicHookMath', 'calculate_field');
?>
and made one more file logic hook math. here is my code for
<?php
class LogicHookMath {
function calculate_field(&$bean, $event, $arguments) {
$field1 = $bean->amount1_c;
$field2 = $bean->amount2_c;
$field3 = $field1 + $field2;
$bean->amount_total_c = $field3;
}
}
?>
but still i did not get any result. Please help me out for this.
The code looks correct.
Some common "mistakes" when custom logic hooks are not working:
Make sure, the custom logic hook has the correct name (LogicHookMath.php)
Make sure, that the $bean variable is prefixed with &, so the variable is passed as a reference
Make sure the logic_hooks.php and the LogicHookMath.php files are readable by the web server user
The entire custom directory should also be writeable for the web server user
If the above does not help, try logging the progress to the sugarcrm.log using $GLOBALS['log']->info( "Value 3: ". $field3); in the custom logic hook.

zend framework 1.11.5 is choking on search function - mysql db

ZF 1.11.5 is puking all over this search function. i've tried creating the query several different ways, sent the sql statement to my view, copied and pasted the sql statement into phpMyAdmin and successfully retrieved records using the sql that ZF is choking on. i have been getting a coupld of different errors: 1) an odd SQL error about 'ordinality' (from my Googling ... it seems this is a ZF hang up .. maybe?) and 2) Fatal error: Call to undefined method Application_Model_DbTable_Blah::query() in /blah/blah/blah.php on line blah
public function searchAction($page=1)
{
$searchForm = new Application_Model_FormIndexSearch();
$this->view->searchForm = $searchForm;
$this->view->postValid = '<p>Enter keywords to search the course listings</p>';
$searchTerm = trim( $this->_request->getPost('keywords') );
$searchDb = new Application_Model_DbTable_Ceres();
$selectSql = "SELECT * FROM listings WHERE `s_coursedesc` LIKE '%".$searchTerm."%' || `s_title` LIKE '%".$searchTerm."%'";
$selectQuery = $searchDb->query($selectSql);
$searchResults = $selectQuery->fetchAll();
}
here's my model ....
class Application_Model_DbTable_Ceres extends Zend_Db_Table_Abstract
{
protected $_name = 'listings';
function getCourse( $courseId )
{
$courseid = (int)$courseId;
$row = $this->fetchRow('id=?',$courseId);
if (!$row)
throw new Exception('That course id was not found');
return $row->toArray();
}
}
never mind the view file ... that never throws an error. on a side note: i'm seriously considering kicking ZF to the curb and using CodeIgniter instead.
looking forward to reading your thoughts. thanks ( in advance ) for your responses
You're trying to all a method called query() on Zend_Db_Table but no such method exists. Since you have built the SQL already you might find it easier to call the query on the DB adapter directly, so:
$selectSql = "SELECT * FROM listings WHERE `s_coursedesc` LIKE '%".$searchTerm."%' || `s_title` LIKE '%".$searchTerm."%'";
$searchResults = $selectQuery->getAdapter()->fetchAll($selectSql);
but note that this will give you arrays of data in the result instead of objects which you might be expecting. You also need to escape $searchTerm here since you are getting that value directly from POST data.
Alternatively, you could form the query programatically, something like:
$searchTerm = '%'.$searchTerm.'%';
$select = $selectQuery->select();
$select->where('s_coursedesc LIKE ?', $searchTerm)
->orWhere('s_title LIKE ?', $searchTerm);
$searchResults = $searchQuery->fetchAll($select);

How to block SQL injection for this query?

now i have this form post script
<?
if(isset($_POST['baslik'])) {
$sql = "INSERT INTO yazilar (baslik, spot, spot_kisa, spot_resim, spot_resim_isim, icerik, kategori, tiklanma, eklemetarihi)
VALUES
('$_POST[baslik]','$_POST[spot]','$_POST[spot_kisa]','$_POST[spot_resim]','$_POST[spot_resim_isim]','$_POST[icerik]','$_POST[kategori]','$_POST[tiklanma]','$_POST[tarih]')";
$sonuc = mysql_query($sql) or die(mysql_error());
if ($sonuc) {
echo ("<p class='msg done'>Yeni icerik basarili bir sekilde eklendi.</p>");
exit;
}
else {
$error = "<p class='msg warning'>Ekleme basarisiz oldu.</p>";
}
}
?>
how can i ignore sql injections for this query?
Use parametrised queries. Unfortunately these are not supported by the mysql extension in PHP 4, but if you are using PHP 5, you can use the mysqli extension or PDO instead, where they are.
See http://www.php.net/manual/en/mysqli.prepare.php for an example of how this is done.
Using parametrised queries as jammycackes suggests is the way to go, but if you for some reason cannot use them then you can use the mysql-real-escape-string function to block most (all?) dangerous values. The problem is that you must use it on every received value, so you cannot use the shorthand notion you use in your example.