I am trying to use phalcons query language(PHQL) to remove items from a database, i have used the GET method obtain the id of the item clicked on.. The id is embedded
Controller:
public function deleteSkillsAction(){
$id=$_GET["id"]
$phql = "DELETE FROM Skills WHERE id =:id:";
$manager->executeQuery(
$phql,
array(
'id' => $id
)
);
}
Getting the following error message, and query is not going through:
Notice: Undefined variable: manager in C:\xampp\htdocs\Blueware\app\controller\skillsController.php on line 15
Fatal error: Call to a member function executeQuery() on a non-object in C:\xampp\htdocs\Blueware\app\controller\skillsController.php on line 15
Try
first initialize the $manager variable, as per documentation,
$manager = $this->modelsManager;
$manager->executeQuery(
$phql,
array(
'id' => $id
)
);
or
call is as
$this->modelsManager->executeQuery(
$phql,
array(
'id' => $id
)
);
Related
I get an error saying "Trying to get property 'name' of non-object" when I tried to click on next page using pagination.
Here is my Controller:
$websites = Website::all();
$menu = Menu::with('categories')->whereHas('categories', function ($query) {
$query->where('slug', request()->category);
})->paginate(8);
$categories = Category::all();
$categoryName = $categories->where('slug', request()->category)->first()->name;
return view('shopmenu')->with([
'menu' => $menu,
'categories' => $categories,
'categoryName' => $categoryName,
'websites' => $websites,
]);
The error is in this code:
$categoryName = $categories->where('slug', request()->category)->first()->name;
How do I solve this?
You need to put check if you are getting any record then try to access name.
$categoryName = $categories->where('slug', request()->category)->first();
if ($categoryName) {
$categoryName = $categoryName->name;
}
Basically due to chaining when you get null in this query $categories->where('slug', request()->category)->first() and you try to access name property on null you get this error.
I am trying to learn opencart structure, and trying to create a new column under the table product. The new column is "test"
Then I try to retrieve the data under this page index.php?route=checkout/cart (replace price with test column)
catalog\controller\checkout\cart.php
...
$this->data['products'][] = array(
'key' => $product['key'],
'thumb' => $image,
'name' => $product['name'],
'model' => $product['model'],
'option' => $option_data,
'quantity' => $product['quantity'],
'stock' => $product['stock'] ? true : !(!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning')),
'reward' => ($product['reward'] ? sprintf($this->language->get('text_points'), $product['reward']) : ''),
'price' => $product['test'], //<-- new column
'total' => $total,
'href' => $this->url->link('product/product', 'product_id=' . $product['product_id']),
'remove' => $this->url->link('checkout/cart', 'remove=' . $product['key'])
);
The problem is I'm not getting any output, and I'm not sure how to work with the model. Which query/function is related with this page ?
The problem is that the $products that are available at cart.php controller are retrieved from the session where they have been stored in previously set structure, so there is no test index and You should get a Notice: undefined index 'test' in .... The $products are retrieved by
foreach ($this->cart->getProducts() as $product) {
//...
}
See /system/library/cart.php and method getProducts() to understand what I am speaking about.
If You would like to use this at catalog/controller/product/category.php or catalog/controller/product/product.php controllers, the code You are trying will work.
If You replace the price within all product lists and product detail, these controllers:
product/
category.php
manufacturer_info.php
product.php
search.php
special.php
module/
bestseller.php
featured.php
latest.php
special.php
with Your value, the final price within cart would be Your test value.
I need to insert multioptions to a dropdown list, options taken from a table from my database.
I created the elements like:
$this->add(array(
'name' => 'company',
'type' => 'Zend\Form\Element\Select',
//'multiOptions'=> $options,
'options' => array(
'label' => 'Company',
),
'attributes' => array(
'style' => "float:right;",
),
));
I want to choose from a dropdown list some values that are in a table in my database. For example I have the entity Contacts and I need to choose for the contact a company that is in a table named companies in the database.
After reading on zend framework's site, I tried using this code:
$params = array(
'driver'=>'Pdo_Mysql',
'host'=>'localhost',
'username'=>'root',
'password'=>'',
'dbname' =>'myDataBase'
);
$db = new \Zend\Db\Adapter\Adapter($params);
$sql= new Sql($db);
$select = $sql->select();
$select ->from('companies')
->columns(array('id','company_name'))
->order(" 'company_name' ASC");
I also read on some other sites that I could use a function:
$options = $sql->fetchPairs('SELECT id, name FROM country ORDER BY name ASC');
but it seems it doesn't exist anymore in Zend Framework 2.
Please guys, give me a hand. If the code isn't good and you have a better idea, please tell me.
Thanks in advance!
This is just a quick and dirty answer, but i guess it can get you started.
Create a ServiceFactory, this should be done in a separate factory class instead of a closure, but i still use a closure - faster to write ;)
Get the config from the ServiceLocator so you have access to the DB-Params
Create your default SQL Stuff to retriefe the value_options
Populate the value_options using the setValueOptions($valueOptions) function of your given form-element
Module.php getServiceConfig()
return array(
'factories' => array(
'my-form-factory' => function($serviceLocator) {
$form = new My\Form();
$config = $serviceLocator->get('config');
$db = new \Zend\Db\Auth\Adapter\Adapter($config['dbParams']); //or whatever you named the array key
$sql = //do your SQL Stuff
// This is a fake array, it should be your $sql result in the given format
$result = array('value' => 'label', 'value2' => 'label2');
$form->get('elementToPopulate')->setValueOptions($result);
return $form;
}
)
);
SomeController.php someAction()
$form = $this->getServiceLocator()->get('my-form-factory');
return new ViewModel(array(
'form' => $form
));
I hope this gets you started
you have to add that field validation on controller for setting value in it.
$select = $db->select()->where("state_code = ?",$arr["state_code"]);
$resultSet = $cityObj->fetchAll($select);
$cityArr = $resultSet->toArray();
$city_ar = array();
foreach($cityArr as $city){
$city_ar[$city['id']] = $city['company'];
}
$form->company->setMultiOptions($city_ar);
$form->company->setValue($val["company"]);
by using this code drop down of country have the value that are in resultset array ($resultSet).
I am using the framework cakePHP for my application. I programmed it on localhost with xampp and try to upload it on my website now. It worked without any problems on localhost. Now there is only this one page, which does not work on the new server. The other sites (which use the database connection too) work alright.
For this one site the following message appears:
Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'add' at line 1
SQL Query: add
The function add() looks like this.
public function add() {
//$this->create();
$word_id = $this->Word->getWord_id();
$save = $this->save(array('word_id' => $word_id, 'text' => $this->getText($word_id), 'mistake' => 0));
return $save['Game']['id'];
}
On localhost I used MySQL-Client-Version: mysqlnd 5.0.8-dev - 20102224 - $Revision: 310735 $ and PHP Version 5.3.8.
On the server I use MySQL-Client-Version: 5.1.62 and PHP Version 5.3.17.
Thank you very much for helping!
Edit:
The model 'Game':
class Game extends AppModel {
public $name = 'Game';
public $belongsTo = 'Word';
public $searchedWord = '';
public function addGame() { // Create new game
$word_id = $this->Word->getWord_id();
$save = $this->save(array('word_id' => $word_id, 'text' => $this->getText($word_id), 'mistake' => 0));
return $save['Game']['id']; // Build the hangman
}
}
When I debug $this->Game, the output is:
object(AppModel) {
useDbConfig => 'default'
useTable => 'games'
id => null
data => array()
schemaName => null
table => 'games'
primaryKey => 'id'
validate => array()
validationErrors => array()
validationDomain => null
name => 'Game'
alias => 'Game'
tableToModel => array(
'games' => 'Game'
)
cacheQueries => false
belongsTo => array()
hasOne => array()
hasMany => array()
hasAndBelongsToMany => array()
actsAs => null
Behaviors => object(BehaviorCollection) {
modelName => 'Game'
defaultPriority => (int) 10
}
whitelist => array()
cacheSources => true
findQueryType => null
recursive => (int) 1
order => null
virtualFields => array()
__backAssociation => array()
__backInnerAssociation => array()
__backOriginalAssociation => array()
__backContainableAssociation => array()
findMethods => array(
'all' => true,
'first' => true,
'count' => true,
'neighbors' => true,
'list' => true,
'threaded' => true
)
}
usually, if this error happens, you don't have the model instance, but an app model instance you work on. the app model instance doesnt have the add() method and directly queries the db with add().
so make sure your model is properly included. since you didnt show us the code how you call the method (and how you make the model available to the controller) I cannot offer any concrete advice, though.
if you manually include it:
$this->ModelName = ClassRegistry::init('ModelName');
add is a reserved word in MySQL and you're probably using it in a SQL query without "escape".
Check if you have any field named add in your database.
I just had this error and I felt pretty stupid. I'm sure this has been solved a long time ago, but in case anyone else comes across it...
Using your example I'll show basically what I also stupidly did in my Controller and how it caused the same type of error you had:
public function index($gameid = null, $letter = null) {
if ($gameid == null) {
// New game
$gameid = $this->Game->addGame();
}
}
Since you already have the instance (controller class) and you're not calling the Model method of addGame here, but the Controller's method, you simply remove the Game-> from your one-line command.
$gameid = $this->addGame();
Simple and easy oversight. That said, if you moved the addGame method to your Model class, it probably would have worked as expected. :)
hi im having little trouble at inserting date from drupal to mysql
here the code that i'm trying
.....
$form['kotak']['tgl'] = array(
'#type' => 'date',
'#title' => t('Tanggal'),
);
.....
function awal_form_submit($form,&$form_state){
global $user;
$entry = array(
'tanggal' => $form_state['values']['tgl'],
);
$tabel = 'jp_1';
$return = insert_form($entry,$tabel);
}
.....
function insert_form($entry,$tabel){
$return_value = NULL;
try {
$return_value = db_insert($tabel)
->fields($entry)
->execute();
}
.....
everytime i'm submit, error code like this
db_insert failed. Message = SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1, query= INSERT INTO {jp_1} (tanggal) VALUES (:db_insert_placeholder_0_month, :db_insert_placeholder_0_day, :db_insert_placeholder_0_year)
any suggestion or correction?
From the mysql error it looks like the table you created has required fields (a columns Null property is set to 0, which means that there must be a value for tha column for every row you want to insert)
Check whether there are any columns which have null set to 0.
From your example I can't see what you're trying to achieve, but in many cases it's not necessary to write into db tables manually (using db_insert()) as you can get the same result easier by creating a content type (node type) which handles a lot of functionality for you.
I hope that helps, Martin
i'm finally managed to find the answer, all i need is download "Date" module and activate its "Date API". Here the code
.....
$datex = '2005-1-1';
$format = 'Y-m-d';
$form['kotak']['tgl'] = array(
'#type' => 'date_select',
'#default_value' => $datex,
'#date_format' => $format,
'#date_year_range' => '-10:+30',
'#title' => t('Tanggal'),
);
.....
function awal_form_submit($form,&$form_state){
global $user;
$entry = array(
'tanggal' => $form_state['values']['tgl'],
);
$tabel = 'jp_1';
$return = insert_form($entry,$tabel);
}
.....
function insert_form($entry,$tabel){
$return_value = NULL;
try {
$return_value = db_insert($tabel)
->fields($entry)
->execute();
}
.....
and now i have no problem delivering to mysql.
Hope that will help other drupal newbie developer like me. Thanks :D