How to change specific symbol of YII cactiverecord model's attribute ?
Dont understand why it doesnt work:
echo $model->attr; // aaa
$model->attr[1] = 'b';
echo $model->attr; // aaa
Use substr_replace function:
echo $model->attr; // aaa
$model->attr = substr_replace($model->attr, 'b', 1, 1);
echo $model->attr; // aba
http://www.php.net/manual/en/function.substr-replace.php
Also you can use this approach:
$newValue = $model->attr[1] = 'b';
$model->attr = $newValue;
echo $model->attr; // aba
Your example does not work because actually $this->AttributeName execute CActiveRecord::getAttribute('AttributeName') method and not affect original value.
Related
I changed my mysqli connection to PDO statment so i have to much error on my page this is the my code pls help us
.
.
.
if ($fn && $ln && $e && $p) { // If everything's OK...
// Make sure the email address is available:
//$q = "SELECT user_id FROM users WHERE email='$e'";
$q = $dbc->query("SELECT user_id FROM users WHERE email='$e'");
$q->execute(array($e));
$r = $q->fetchAll(PDO::FETCH_ASSOC);
//$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
if (mysqli_num_rows($r) == 0) { // Available.
// Create the activation code:
$a = md5(uniqid(rand(), true));
Here is your code converted to PDO.
// Make sure the email address is available:
$q = $dbc->query("SELECT user_id FROM users WHERE email=?");
$q->execute(array($e));
$r = $q->fetchColumn();
if (!$r) { // Available.
// Create the activation code:
$a = md5(uniqid(rand(), true));
Three things has been corrected
You have to always use a placeholder tp represent a variable in the query.
To get a single value from the result, fetchColumn have to be used instead of fetchAll
No need for the manual reporting, as PDO can report its errors automatically, if confugired properly, as described in this tutorial I wrote
i have a table (facility) in which field names are swimming_pool, restaurant, WiFi, library etc.
if a particular house having only two of those facilities available, i give those available field names value 1 and if not 0.
I want to retrieve all the field names with value 1 and echo each field with value 1 with an alternate name.
here is what i want to achieve
$st = $db->prepare(select * from facility where house_id = ?);
$st->execute(array($_GET['house_id']));
$row = $st->fetch();
from above i have to select all fields with value 1. And for all those fields with value one i have to echo name (for example: if swimming_pool value is 1 i have to echo Swimming Pool, if it is 0 then check for the next column)
i hope you understood my goal.
I hope I solved your question? I didn't test it yet, so if there might be a problem, do a comment.
<?php
/*
* Sample Link: web.com/index.php?house_id=1&search=1,0,0,1
*/
/*
* Sample Fields:
* swimming_pool, restaurant, wifi, library
*/
//Explode the $_GET['search'] to create an array
$fields_to_search = explode(",",$_GET['search']);
//Manually set the fields
$db_fields = [
'swimming_pool',
'restaurant',
'wifi',
'library'
];
$fields_to_be_selected = "";
//Create a counter as basis to store if the Link is 1 or 0, then pass it to $db_fields[]
$counter = 0;
foreach($fields_to_search as $field) {
//Check if $field is 1
if($field == 1) {
//Then pass it to $table_to_be_selected and add a COMMA
$fields_to_be_selected .= $db_fields[$counter].",";
}
$counter++;
}
//Remove the last COMMA
$fields_to_be_selected = substr($fields_to_be_selected,0,-1);
/*
* LASTLY DO THE prepare()
*/
$query = sprintf("SELECT %s FROM `facility` WHERE `house_id` = ?",$fields_to_be_selected);
$stmt = $db->prepare($query);
$stmt->execute(array($_GET['house_id']));
$rows = $stmt->fetchAll();
//It will only print the selected fields
print_r($rows);
?>
Following function works. But I wanna use "statement" and "like" together. If I comment out the line with constraint1 and try with:
$constraint1 = $query->statement("SELECT * FROM pages WHERE title LIKE '" . $text . "%'");
...the query doesn't work.
I got an error:
1: PHP Catchable Fatal Error: Argument 1 passed to TYPO3\CMS\Extbase\Persistence\Generic\Qom\QueryObjectModelFactory::_or() must implement interface TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface, instance of TYPO3\CMS\Extbase\Persistence\Generic\Query given, called in [...] on line 439 and defined in [...]\typo3\sysext\extbase\Classes\Persistence\Generic\Qom\QueryObjectModelFactory.php line 122
Function:
/**
* Test
*
* #param string $text
* #return Objects
*/
public function findWordsByText($text) {
$query = $this->createQuery();
$query->getQuerySettings()->setRespectStoragePage(FALSE);
$query->getQuerySettings()->setReturnRawQueryResult(TRUE);
$constraint1 = $query->like('title', $text . '%');
// $constraint1 = $query->statement("SELECT * FROM pages WHERE title LIKE '" . $text . "%'");
$constraint2 = $query->like('title', 'new');
$constraint = array($constraint1, $constraint2);
$query->matching(
$query->logicalOr($constraint)
);
$records = $query->execute();
return $records;
}
If I change follwing lines:
$query->matching(
$query->logicalOr($constraint)
);
To - logicalAnd:
$query->matching(
$query->logicalAnd($constraint)
);
...the query is empty.
I don't see your problem. You want to return all records that either contain the term $text in the title field or have 'new' in the title field. So just use a simple logicalOr query:
/**
* Test
*
* #param string $text
* #return Objects
*/
public function findWordsByText($text) {
$query = $this->createQuery();
$query->getQuerySettings()->setRespectStoragePage(FALSE);
$query->getQuerySettings()->setReturnRawQueryResult(TRUE);
$query->matching(
$query->logicalOr(
$query->like('title', '%' . $text . '%'),
$query->like('title', 'new')
)
);
return $query->execute();
}
$query->statement() is for raw SQL queries and cannot be combined with createQuery.
By the way, if $text comes from a POST or GET input, don't forget to sanitize the input.
I know that if statement gives a result as a Boolean.
<?php
if (isset($_GET['subj'])) {
$sel_subj = $_GET['subj'];
$sel_page = "";
?>
Can i use $sel_subj or $sel_page outside if statement ? The second question in the case of while loop ? Can i use a variable outside it or its considered as in the local scope ?
while ($page = mysql_fetch_array($page_set)) {
echo "<li";
if ($page["id"] == $sel_page) { echo " class=\"selected\""; }
echo "><a href=\"content.php?page=" . urlencode($page["id"]) .
"\">{$page["menu_name"]}</a></li>";
}
Basically yes, any variables defined inside an if or while will be available in the scope that the if or while exists in (as they are defined in a conditional though they might not have been set so you would receive an undefined warning)
so
function foo(){
$i=0
while($i==0){
$i=1;
$a=1;
}
echo $a;
//$a is available here although it might be undefined as the condition may not have been met
}
echo $a //$a is not available here
You should ideally declare the variable first.
I have three const in controller:
const TEST1 = 1;
const TEST2 = 2;
const TEST3 = 3;
How I can call these values in view as a dropDown?
If you will get messy with all constants you have in diferent models, you can use code snippet I wrote to manage them. Please see Managing constants easily (yii wiki article)
I will copy just function and one example, but for full wiki and details please go visit link above.
Put this method in parent class or your model class directly:
class ActiveRecord extends CActiveRecord {
const TEST_1 = 1;
const TEST_2 = 2;
const TEST_3 = 3;
/*
Get class constants by token.
If you set constants with same prefix, like:
TEST_1
TEST_2
TEST_3
, you can get it by calling
Class::getConstants('TEST_');
*/
public static function getConstants($token,$objectClass) {
$tokenLen = strlen($token);
$reflection = new ReflectionClass($objectClass); //php built-in
$allConstants = $reflection->getConstants(); //constants as array
$tokenConstants = array();
foreach($allConstants as $name => $val) {
if ( substr($name,0,$tokenLen) != $token ) continue;
$tokenConstants[ $val ] = $val;
}
return $tokenConstants;
}
}
And after that you can use this method to get specific constants (from one group) in array:
self::getConstants('TEST_',__CLASS__); //inside same class
ActiveRecord::getConstants('TEST_','ActiveRecord'); //outside, somewhere else in view or controller
For dropdown it would be looking as (if MyModel have parent ActiveRecord)
echo CHtml::dropDownList('name','selected',
MyModel::getConstants('TEST_','MyModel'),
array(// for htmlOptions
)
);
Now you can forget to edit all places in code if you adding new constant. It will automaticaly added to all your dropdowns or whatever.
Simple, just use:
$this::TEST1;
In dropdownList:
echo CHtml::dropDownList('name','selected',
array($this::TEST1=>'Test1',$this::TEST2=>'Test2',$this::TEST3=>'Test3'),
array(// for htmlOptions
)
);