Codeigniter db like not working in array - mysql

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

Related

Generator by reference

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();

array saving cakephp 3 savemany

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.'));
}
}
}

How can I restore a MySQL database from CakePHP model cache?

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.

Kohana 3.2 select issue

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();
}

mysql_num_rows() error

I am displaying an editable table in drupal with the following code
function _MYMODULE_sql_to_table($sql) {
$html = "";
// execute sql
$resource = db_query($sql);
// fetch database results in an array
$results = array();
while ($row = db_fetch_array($resource)) {
$results[] = $row;
$id = $row['id'];
$email = $row['email'];
$comment = $row['comment'];
// drupal_set_message('Email: '.$email. ' comment: '.$comment. ' id: '.$id);
}
// ensure results exist
if (!count($results)) {
$html .= "Sorry, no results could be found.";
return $html;
}
// create an array to contain all table rows
$rows = array();
// get a list of column headers
$columnNames = array_keys($results[0]);
// loop through results and create table rows
foreach ($results as $key => $data) {
// create row data
$row = array(
'edit' => l(t('Edit'),"admin/content/test/".$data['id']."/ContactUs", $options=array()),);
// loop through column names
foreach ($columnNames as $c) {
$row[] = array(
'data' => $data[$c],
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
// add row to rows array
$rows[] = $row;
}
// loop through column names and create headers
$header = array();
foreach ($columnNames as $c) {
$header[] = array(
'data' => $c,
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
// generate table html
$html .= theme('table', $header, $rows);
return $html;
}
// then you can call it in your code...
function _MYMODULE_some_page_callback() {
$html = "";
$sql = "select * from {contact3}";
$html .= _MYMODULE_sql_to_table($sql);
return $html;
}
However, I keep getting the mysql_num_rows() error as
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource. What is causing it?
Which version of Drupal are you using?
try db_affected_rows()
or db_num_rows()