I am testing generator by reference of two ways:
N°1: It works
<?php
$value = 3;
function &gen_reference() {
global $value;
while ($value > 0) {
yield $value;
}
}
foreach (gen_reference() as &$number) {
--$number;
}
echo($value . PHP_EOL); // 0
N°2: It not display than I want.
<?php
class Test
{
public $data = [];
function __construct($data){
$this->data = $data;
}
function &getIterator() {
foreach ($this->data as $key => $value) {
yield $key => $value;
}
}
function printData()
{
foreach ($this->data as $key => $value) {
echo($key . ':' . $value . PHP_EOL);
}
}
}
$data = array('one'=>'Curly', 'two'=>'Larry', 'three'=>'Moe');
$t = new Test($data);
foreach ($t->getIterator() as $key => &$value) {
$value = strtoupper($value); // Does not update $this->data
}
$t->printData();
Display:
one:Curly
two:Larry
three:Moe
I expected:
one:CURLY
two:LARRY
three:MOE
Any correction or suggestion?
Add & to $value in &getIterator function for keep to reference:
function &getIterator() {
foreach ($this->data as $key => &$value) { // Here add & to $value
yield $key => $value;
}
}
Code complete:
class Test
{
public $data = [];
function __construct($data){
$this->data = $data;
}
function &getIterator() {
foreach ($this->data as $key => &$value) { // Here add & to $value
yield $key => $value;
}
}
function printData()
{
foreach ($this->data as $key => $value) {
echo($key . ':' . $value . PHP_EOL);
}
}
}
$data = array('one'=>'Curly', 'two'=>'Larry', 'three'=>'Moe');
$t = new Test($data);
foreach ($t->getIterator() as $key => &$value) {
$value = strtoupper($value); // Does not update $this->data
}
$t->printData();
Related
Hi can someone know this i am beginner in Cakephp i tried to upload multiple images but it wont save.
Controller:
public function add() {
if ($this->request->is('post')) {
//$data = $this->request->getData();
if(!empty($_FILES['photo']['name'])){
$count = count($_FILES['photo']['name']);
for ($i=0; $i < $count; $i++) {
$filename = $_FILES['photo']['name'][$i];
$type = $_FILES['photo']['type'][$i];
$tmp = $_FILES['photo']['tmp_name'][$i];
$error = $_FILES['photo']['error'][$i];
$size = $_FILES['photo']['size'][$i];
$uploadPath = '../uploads/files/';
$file[$i]['user_id'] = $this->Auth->user('id');
$file[$i]['filename'] = $filename;
$file[$i]['file_location'] = $uploadPath;
$file[$i]['file_type'] = $type;
$file[$i]['file_size'] = $size;
$file[$i]['file_status'] = 'Active';
$file[$i]['created'] = date("Y-m-d H:i:s");
$file[$i]['modified'] = date("Y-m-d H:i:s");
}
$table = TableRegistry::get('files');
$entities = $table->newEntities($file);
if($table->saveMany($entities)) {
$this->Flash->success(__('File has been uploaded and inserted successfully.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('Unable to upload file, please try again.'));
}
} else {
$this->Flash->error(__('Please choose a file to upload.'));
}
}
}
but when i tried to debug all good but in saving it wont work! does my code has problem, can someone help me how to fix my add function
View:
echo $this->Form->input('photo[]', ['type' => 'file','multiple' => 'true','label' => 'Upload Multiple Photos']);
You are trying to save one record once using saveMany().
public function add()
{
if ($this->request->is('post')) {
$table = TableRegistry::get('files');
$uploadPath = '../uploads/files/';
if(!empty($_FILES['photo'])){
foreach ($_FILES['photo'] as $EachPhoto) {
$data[] = [
'user_id' => $this->Auth->user('id'),
'filename' => $EachPhoto['name'],
'file_location' => $uploadPath,
'file_type' => $EachPhoto['type'],
'file_size' => $EachPhoto['size'],
'file_status' => 'Active',
'created' => date("Y-m-d H:i:s")
];
}
$entities = $table->newEntities($data);
if($this->Files->saveMany($entitie)) {
$this->Flash->success(__('File has been uploaded and inserted successfully.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('Unable to upload file, please try again.'));
}
} else {
$this->Flash->error(__('Please choose a file to upload.'));
}
}
}
in app\tmp\cache\models there is a file called:
myapp_cake_model_default_mydb_users
The contents are:
1446583948
a:14:{s:2:"id";a:6:{s:4:"type";s:7:"integer";s:4:"null";b:0;s:7:"default";N;s:6:"length";i:11;s:8:"unsigned";b:0;s:3:"key";s:7:"primary";}s:8:"username";a:7:{s:4:"type";s:6:"string";s:4:"null";b:0;s:7:"default";N;s:6:"length";i:255;s:3:"key";s:5:"index";s:7:"collate";s:15:"utf8_general_ci";s:7:"charset";s:4:"utf8";}s:8:"password";a:6:{s:4:"type";s:6:"string";s:4:"null";b:1;s:7:"default";N;s:6:"length";i:255;s:7:"collate";s:15:"utf8_general_ci";s:7:"charset";s:4:"utf8";}s:17:"num_free_listings";a:5:{s:4:"type";s:7:"integer";s:4:"null";b:1;s:7:"default";s:1:"0";s:6:"length";i:2;s:8:"unsigned";b:0;}s:3:"pin";a:6:{s:4:"type";s:6:"string";s:4:"null";b:1;s:7:"default";N;s:6:"length";i:255;s:7:"collate";s:15:"utf8_general_ci";s:7:"charset";s:4:"utf8";}s:7:"is_ldap";a:4:{s:4:"type";s:7:"boolean";s:4:"null";b:0;s:7:"default";N;s:6:"length";i:1;}s:13:"ldap_username";a:6:{s:4:"type";s:6:"string";s:4:"null";b:1;s:7:"default";N;s:6:"length";i:255;s:7:"collate";s:15:"utf8_general_ci";s:7:"charset";s:4:"utf8";}s:8:"fullname";a:6:{s:4:"type";s:6:"string";s:4:"null";b:0;s:7:"default";N;s:6:"length";i:255;s:7:"collate";s:15:"utf8_general_ci";s:7:"charset";s:4:"utf8";}s:8:"group_id";a:5:{s:4:"type";s:7:"integer";s:4:"null";b:0;s:7:"default";s:1:"2";s:6:"length";i:11;s:8:"unsigned";b:0;}s:16:"password_changed";a:4:{s:4:"type";s:4:"date";s:4:"null";b:1;s:7:"default";N;s:6:"length";N;}s:10:"last_login";a:4:{s:4:"type";s:8:"datetime";s:4:"null";b:1;s:7:"default";N;s:6:"length";N;}s:6:"status";a:6:{s:4:"type";s:26:"enum('active','suspended')";s:4:"null";b:0;s:7:"default";s:6:"active";s:6:"length";i:9;s:7:"collate";s:15:"utf8_general_ci";s:7:"charset";s:4:"utf8";}s:7:"created";a:4:{s:4:"type";s:8:"datetime";s:4:"null";b:0;s:7:"default";N;s:6:"length";N;}s:8:"modified";a:4:{s:4:"type";s:8:"datetime";s:4:"null";b:0;s:7:"default";N;s:6:"length";N;}}
Can I convert this (serialized php?) to SQL and recreate my table, if so how? Many thanks in advance.
In PHP create a file:
<?php
class AppSchema extends CakeSchema {
public function before($event = array()) {
return true;
}
public function after($event = array()) {
}
$dir = 'files/';
$files = [
'table_names' => 'myapp_cake_model_default_mydb_tablenames',
];
foreach ($files as $table => $file){
$content = file(realpath( $dir.$file ));
$content = unserialize($content[1]);
$info = null;
foreach ($content as $field => $prop){
$info .= "'$field' => array(";
foreach ($prop as $key => $value){
$info .= "'$key' => ";
if($key == 'null'){
$info .= empty($value)?'false':'true';
}elseif($key == 'default'){
$info .= empty($value)?'null':"'$value'";
}elseif($key == 'unsigned'){
$info .= empty($value)?'false':'true';
}else{
$info .= empty($value)?"''":"'$value'";
}
$info .= ", ";
}
$info .= "),\n";
}
echo "public $".$table." = array(
".$info."'indexes' => array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
),
'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB')
);\n\n";
}
?>
}
Then run it in the browser and you should get some code to paste a the schema.php file. Then use the Cake console to create the tables in the MySQL database.
I have this peace of code in my controller where I want to echo on the screen the JSON result for the data in the model:
public function actionIndex()
{
$searchModel = new TestTableSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
var_dump($dataProvider->getModels());
echo json_encode([
"searchModel" => $searchModel,
"getCount" => $dataProvider->getCount(),
"dataProvider" => $dataProvider->models
]);
}
So $dataProvider actually is not empty and it contains the data (which can be seen from var_dump() command), but the data are not returned as I'm expecting.
Even $dataProvider->getCount() is returning that there are two entries. This is the output that I got: http://prntscr.com/8hcel9.
I'm interested in showing the dataProvider part, where the items in array should not be empty.
You need to convert the object to array
try this way :
use yii\helpers\ArrayHelper;
......
public function actionIndex()
{
$searchModel = new TestTableSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
var_dump($dataProvider->getModels());
echo json_encode([
"searchModel" => $searchModel,
"getCount" => $dataProvider->getCount(),
"dataProvider" => ArrayHelper::toArray($dataProvider->models), // object to Array
]);
}
This has not much to do with Yii. It's just a PHP problem. You can solve it like this (according to this):
echo "<pre>";
echo json_encode([
"searchModel" => json_readable_encode($searchModel),
"getCount" => $dataProvider->getCount(),
"dataProvider" => json_readable_encode($dataProvider->models)
]);
echo "</pre>";
function json_readable_encode($in, $indent = 0, $from_array = false) {
$_myself = __FUNCTION__;
$_escape = function ($str) {
return preg_replace("!([\b\t\n\r\f\"\\'])!", "\\\\\\1", $str);
};
$out = '';
foreach ($in as $key => $value) {
$out .= str_repeat("\t", $indent + 1);
$out .= "\"" . $_escape((string)$key) . "\": ";
if (is_object($value) || is_array($value)) {
$out .= "\n";
$out .= $_myself($value, $indent + 1);
} elseif (is_bool($value)) {
$out .= $value ? 'true' : 'false';
} elseif (is_null($value)) {
$out .= 'null';
} elseif (is_string($value)) {
$out .= "\"" . $_escape($value) . "\"";
} else {
$out .= $value;
}
$out .= ",\n";
}
if (!empty($out)) {
$out = substr($out, 0, -2);
}
$out = str_repeat("\t", $indent) . "{\n" . $out;
$out .= "\n" . str_repeat("\t", $indent) . "}";
return $out;
}
I have table with 'servers' name in my db. So when I want to add there some data with that code it's just ok:
public function action_add()
{
$serverGameId = (int)Arr::get($_POST, 'serverGameId', '');
$newServerName = Arr::get($_POST, 'newServerName', '');
try
{
$server = new Model_Server();
$server->Name = $newServerName;
$server->GameId = $serverGameId;
$server->save();
}
catch(ORM_Validation_Exception $e)
{
echo json_encode(array("success" => false, "errors" => $e->errors('validation')));
return false;
}
$this->request->headers['Content-Type'] = 'application/json';
echo json_encode(array("success" => true, "serverId" => $server->Id));
return true;
}
Here is a model:
class Model_Server extends ORM {
protected $_table_name = 'servers';
public function rules()
{
return array(
'Name' => array(
array('not_empty'),
)
);
}
}
But I have problem when I try to select it from the table:
public function action_servers()
{
$gameId = (int)Arr::get($_POST, 'gameId', '');
if($gameId == -1) return false;
try
{
$servers = ORM::factory('server')
->where('GameId', '=', $gameId)
->find_all();
}
catch(ORM_Validation_Exception $e)
{
echo json_encode(array("success" => false, "errors" => $e->errors('validation')));
return false;
}
$this->request->headers['Content-Type'] = 'application/json';
echo json_encode(array("success" => true, "servers" => $servers, "gameId" => $gameId));
return true;
}
I already try to solve problem with change code inside of try block on:
$servers = DB::select('servers')->where('GameId', '=', $gameId);
Even when I try just get all my servers from db without '->where' it's doesn't work.
Any ideas?
Try print_r($servers); inside try block to see what you get from model.
And $servers is some class with results - use foreach to get result (one by one)
$results = array();
foreach($servers as $row) {
//echo $row->Name;
$results[] = $row->Name;
}
Or
$results = array();
foreach($servers as $row) {
//echo $row->as_array();
$results[] = $row->as_array();
}
I want to add more columns to search in my database, this is my original script.
public function getProductsByName($name, $limit, $start) {
$this->db->limit($limit, $start);
$this->db->order_by("id", "desc");
$this->db->like("name", $name);
$query = $this->db->get('products');
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
This is my modified script to find in 3 columns like.
public function getProductsByName($name, $limit, $start) {
$this->db->limit($limit, $start);
$this->db->order_by("id", "desc");
$array = array('name' => $name, 'code' => $code, 'ean' => $ean);
$this->db->like($array);
$query = $this->db->get('products');
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
What is wrong here?
Any help is appreciated.
For selecting the data as like you says ,you need to tell exactly the varible that you use $code and $ean.
another things is the data[] you are created , there is no need to create an array like this.
you will get the same when you call $query->result();
public function getProductsByName($name, $limit, $start,$code,$ean) {
$this->db->limit($limit, $start);
$this->db->order_by("id", "desc");
$array = array('name' => $name, 'code' => $code, 'ean' => $ean);
$this->db->like($array);
$query = $this->db->get('products');
if ($query->num_rows() > 0) {
return $query->result();
}
return false;
}
hope it will help you