I have searched for this question and found many similar answers like this one
Update a row +1 in CakePHP
and this is what the accepted answer looks like
$this->Widget->updateAll(
array('Widget.numberfield' => 'Widget.numberfield + 1'),
array('Widget.id' => 1)
);
Now iam using this query in cakephp3.
Here is what mine looks like
$Questions=$this->loadModel('Questions');
$Questions->updateAll(
array('questions.trend' => 'questions.trend + 1'),
array('questions.description' => $undashed_title)
);
Every thing is working fine and query's are executing but when i check debugger for sql log, Here's what i found
UPDATE questions SET questions.trend = 'questions.trend + 1' WHERE questions.description = 'What type'
But my value in database is not updating like it should be
(Iam saying this beacuse i also have copied this query on phpmyadmin console and its not working )
I believe the query should look like this
UPDATE questions SET questions.trend = questions.trend+1 WHERE questions.description = 'What Type'
Any help would be appreciated ,Thanks :)
Well, as i said on comments, CakePHP 3 diverge a value from a expression, and the increment thing that you trying to do is a expression, to solve your "problem" you shall dig deep on CakePHP docs, and so you will find this http://book.cakephp.org/3.0/en/orm/saving-data.html#bulk-updates, yeah, right what you want. So, it becomes:
// load your beloved model
$questions = $this->loadModel('Questions');
// create a beauty expression
$expression = new QueryExpression('questions.trend + 1');
// execute a update with the beauty expression
$questions->updateAll(
array('questions.trend' => $expression),
array('questions.description' => $undashed_title)
);
And don't forget to load QueryExpression's namespace with use Cake\Database\Expression\QueryExpression;.
Yes, this is the wrong way to do on CakePHP 3, you shall the CakePHP's ORM, and move the increment thing to the model layer.
Related
I'm trying to use the zend framework update class: http://framework.zend.com/manual/2.2/en/modules/zend.db.sql.html#zend-db-sql-update
to create something like the statement found here:
http://dev.mysql.com/doc/refman/5.0/en/update.html
UPDATE items,month SET items.price=month.price WHERE items.id=month.id;
I've tried passing an array to ->table but it fails on the string conversion.
// UPDATE `Array`
$update->table(['table1', 'table2'])
I've tried creating an escaped string but it ends up double escaped when converted to sql.
// UPDATE ``table1`,`table2``
$update->table("`table1`,`table2`")
I've tried cheating and used implode to use the glue the tables together
// UPDATE `table1``,``table2`
$update->table(implode("`,`", ['table1','table2']))
Does anyone have a clean answer to this issue?
After further research, I don't think it can be done. The reason I say that is because the query you've proposed may be too resource intensive. After looking for an alternate option, I've come across Update one MySQL table with values from another. However, that I'm aware of, there's no join option on an Update object. So at least at this stage, I don't believe it can be done.
Are you trying to write sql like: "update tableOne, tableTwo set ...." !! I do not think it is possible in sql. As this kind of syntex not supported by mySql so do zend. here is zend table method-
public function table($table)
#param string|TableIdentifier $table
parameter is simply string or TableIdentifier. So you have to write two sql in zend
$update->table('table1');
$update->set(array('foo' => 'bar', 'baz' => 'bax'));
.......
........
$update->table('table2');
$update->set(array('foo1' => 'bar', 'baz1' => 'bax'));
Hope it will help you.
Hello fellow StackOverflowers,
As modifications on my website were needed in result of massive growth and suggestions from the public, I needed to modify my database, which I have already done to adjust it to the visitor suggestions. Right, very confusing so I'll just get to the point:
Current query:
$arow=mysql_fetch_assoc(mysql_query("SELECT * FROM animelist WHERE id = '".$_REQUEST['id']."'"));
$placeholders = array(' ', ',', ':');
$replacements = array('-', '', '');
$title=str_replace($placeholders, $replacements,$arow['name']);
$title=preg_replace("/[^a-zA-Z0-9\s-]/", "", $title);
$link=$title."-".$arow['id'];
$link="Stream-".$title."-Episode-".$row1['episodes_id']."-".$row1['language']."-".$row1['id'];
Initially the part -Episode- was only needed to be named/written as '-Episode-', however to user suggestions and I completely agree, it needs to be dynamic aswell. Lets say (using the terms for reference only) at first the website only had Episodes and not Movies, but now also has Movies. So we want this part to be dynamic aswell. For this we use database information, I have made a column 'type' INT(1) in the table 'items' I suggest 0 to be -Episode- and if value under type is 1 then I suggest it to be -Movie-.
Now the question is how do I correctly implement it in the query? I understand more queries need to be made similar to the one from $title or $row1. this is what I have so far, but it is not complete yet, because I don't know how to:
$link="Stream-".$title."-.$type.-".$row1['episodes_id']."-".$row1['language']."-".$row1['id'];
$type=$arow['type']
Now there should be a code, which I am not sure of how to write correctly, which makes the condition that if type = 0 then echo Episode, elseif type = 1 then echo Movie.
I greatly appreciate the time you took to read this through and hope you can help me out.
Edit:
Assume $row1, is fetched from table named 'videos' and not from 'animelist', however the table 'videos' each video has an 'id' but also has an column named 'anime_id', this anime_id is equal to the 'id' in 'animelist', in short videos id is the post, and anime_id is the category.
More queries need to be written now to balance the game, please help me out, I am stuck.
Thanks in advance,
Inder
$type = ($arow['type']==0) ? "Episode" : "Movie";
or
$type = $arow['type'] ? "Episode" : "Movie";
SELECT COUNT(*) FROM `users` where usergroup_id = 4 AND studio_id = 380 AND userstatus_id = 1
On this query I am getting a result of 4 which is my expected output, but when doing this query:
$this->User->find('count',array('conditions'=>array(
'User.studio_id'=>380,
'User.usergroup_id'=>4,
'User.userstatus_id'=>1)))
I am getting a result of 8
What do you think is the problem here? Feels like my 2nd code is wrong.
I am a newbie in cakePHP.
Your help would be greatly appreciated and rewarded!
The query and the CakePHP find('count', ... should produce the same thing. The likely difference (per a few of the comments) is your $recursive level (see CakePHP recursive).
I'm a big fan of just setting:
public $recursive = -1;
in your AppModel - then you don't have to worry about it ever again, as leaving it at -1 is best practice IMO. Then, if you ever want to retrieve additional associated model data, just use CakePHP's Containable.
If you don't want to set it to -1 across the entire site, just set it right before your query:
$this->User->recursive = -1;
$this->User->find('count',array('conditions'=>array(
'User.studio_id'=>380,
'User.usergroup_id'=>4,
'User.userstatus_id'=>1
)));
Site Note: Setting $recursive to ANYTHING other than -1 should be a red flag. It's kind of a cool concept, but in practice, it will cause you many headaches as your site grows. Set it to -1 in the AppModel like suggested above, then forget it even exists.
I have array like this
$conditions = array("Post.title" => "This is a post");
And using $conditions array in this method.
$this->Post->find('first', array('conditions' => $conditions));
I want convert the $conditions array to normal sql query.
I want use
$this->Post->query($converted_query);
instead of
$this->Post->find('first', array('conditions' => $conditions));
$null=null;
echo $this->getDataSource()->generateAssociationQuery($this, NULL, NULL, NULL, NULL, $query_array, false,$null);
To do what you want you could do two things:
1) Combine your $conditions arrays and let CakePHP build your new query so you can simply use $this->Model->find() again.
2) Use this. It's an expansion for the mysql datasource that adds the option to do $this->Model->find('sql', array('conditions' => $conditions)) which will return the SQL-query. This option might cause trouble, because for some find calls (especially when you're fetching associated models) CakePHP uses multiple queryies to fetch the associated models (especially in case of hasMany-associations).
If at all possible, option 1 will probably cause the least trouble. Another problem with going with 2 is that if you're trying to combine two queries with conflicting conditions (like 'name = Hansel' in query 1 and 'name = Gretel' in query 2) you will just find nothing unless you plan on writing extra code to parse the resulting queries and look for conflicts..
Going with 1 will probably be a lot simpler and will probably avoid lots of problems.
I'm just learning PHP and I've searched for a while on this, but I'm afraid I may not know exactly how to ask it, so an explanation will probably work best. Basically I have a group by/count query returning 3 records.
Status Total
0 2
1 3
2 2
On my page I would like to display:
Status Total
Dev 2
Active 3
Arch 2
So I basically just want to assign the values 0, 1 and 2 to a text value. I've tried creating an array, then assigning the return number field equal to the array.
$_status = array(0 => 'Development', 1 => 'Production', 2 => 'Archive');
while($rowStat = mysql_fetch_assoc($resDev))
{
echo "<tr><td>$_status[$rowStat['status']]</td><td>{$rowStat['devprojects']}</td></tr>";
};
Any help is much appreciated.
Thanks.
as you can see here http://php.net/mysql_fetch_assoc the field names are case sensitive
from what I see in your table sample the field is called "Status"
and you are using "status"
you can try changing
$rowStat['status']
to
$rowStat['Status']
Edit:
the initial version of the answer only focused on what's the problem (and suggested pdo)
I only want to add that I agree to two other optinions found here:
the one added via comment to this answer by giorgio: you should only use lowercase names for your database fields; also you should consider using the table name as a prefix (product_id instead or id, user_password instead of password) for two main reasons: to avoid colisions when you fetch results using a join and to avoit collisions with mysql reserved words (as id, password and status are)
the other one, suggested by Crashspeeder by a comment to the question: you definitely should develop with error reporting on and disable it on live servers
I don't really like using the 0, 1, 2 to represent a named value (unless you have a relational) table in your DB... but using your setup, why not just use:
while($rowStat = mysql_fetch_assoc($resDev)){
switch($rowStat['Status']){
case 0:
echo "<tr><td>Development</td><td>{$rowStat['devprojects']}</td></tr>";
break;
case 1:
echo "<tr><td>Production</td><td>{$rowStat['devprojects']}</td></tr>";
break;
case 2:
echo "<tr><td>Archive</td><td>{$rowStat['devprojects']}</td></tr>";
break;
}
};
EDIT
Some people really are looking for copy-paste answers so here's an updated answer because Sgt. Crashspeeder of the Massively Anal Society got her knickers in a twist.
Create a lookup array to reference against the status Ids:
$statusArray[0] = 'Development;
$statusArray[1] = 'Production;
$statusArray[2] = 'Archive;
Then when you're running your mysql_fetch_assoc() loop, you can reference the statusArray lookup like so:
while($rowStat = mysql_fetch_assoc($resDev)){
echo "<tr><td>{$statusArray[$rowStat['Status']]}</td><td>{$rowStat['devprojects']}</td></tr>";
}