How to use ParseObject update field? - php

How to use Extend to update the field?
Example SQL: UPDATE Empresa SET categorias = 'cat_01' WHERE id_user = 'dlkj83d'
$query = new ParseQuery('Empresa');
$query->equalTo("users", Session::get('user'));
$query->add("categorias", 'cat_01'); <- ERROR
$query->save();
Test
$query = new ParseQuery('Empresa');
$query->equalTo("users", Session::get('user'));
$empresa = new ParseObject($query);
$empresa->add('categorias', array('cat_01'));
$empresa->save();
Does not work.
:(

There is no such ParseQuery::add() function. You are trying to cobble an UPDATE into a SELECT... you have to first find() the resulting ParseObjects and iterate through each one:
$query = new ParseQuery('Empresa');
$query->equalTo('users', Session::get('user'));
$results = $query->find(); // Returns an array of ParseObjects
foreach ($results as $res) {
$res->add('categorias', 'cat_01');
$res->save(); // Make sure you write Exception handling for this in the future
}
There is also a ParseObject::set and setArray function that will achieve the same thing, as add may be getting deprecated.

Perfect.
$query = new ParseQuery('Restaurante');
$query->equalTo("users", Session::get('user'));
$results = $query->first();
$results->add('categorias', array('cat_02'));
$results->save();
I still have some difficulties regarding the method NoSQL. Knowing that the reasoning is different.
Thank you for your attention.
You are part of the development team?

Related

get all objects from parse class using php

I'm using this PHP code to get objects from class.
I've got 100000 objects.
I want to get all the objects in a single query.
I'm using the following code.
$query = new ParseQuery("news_master");
$results = $query->find();
You can remove limit to get all data, please try following code :-
$query = new ParseQuery("news_master");
$query->equalTo("All",true);
results = $query->find();
As of 2018 and Parse Community PHP SDK and server you can use the each function, which provides a callback and can iterate over all data. Note this cannot be used in conjunction with skip, sort, limit. See Docs
An example of a query from their TEST suite would look like this.
$query = new ParseQuery('Object');
$query->lessThanOrEqualTo('x', $count);
$values = [];
$query->each(
function ($obj) use (&$values) {
$values[] = $obj->get('x');
},
10
);
$valuesLength = count($values);
the value of 10 is what batch size you want. If your database table is locked down and requires master key then you can do the following.
$query = new ParseQuery('Object');
$query->lessThanOrEqualTo('x', $count);
$values = [];
$query->each(
function ($obj) use (&$values) {
$values[] = $obj->get('x');
},
true, 10 // notice the value of true
);
$valuesLength = count($values);
The reason I'm adding to this old comment is because if you search getting more than 1000 records from parse no good link comes up and this is usually the first one.
Cheers to anyone that stumbles across this!

CodeIgniter Select Statement with Where clause

Hi I'm new to CodeIgniter and I just want to know How will I query from my MySql Db, a Select Statement with a where clause, I know it can be searched from the net but whenever I try something I get errors, It's really frustrating. The string in the Where clause will be coming from a User Input. Thanks guys!
You can do as Mehedi-PSTU stated, however it seems as though you're a little new to this, so here's some extra information:
I'll copy Mehedi-PSTU for the most part here.
$this->get->where('column_name', $equals_this_variable);
$query = $this->db->get('table_name');
This will store the query object in the variable $query.
if you wanted to convert that to a usable array, you just perform to following.
$results = $query->result_array();
Or you can loop through it like this:
foreach($query->result_array() as $result){
// Perform some task here.
}
A better or even full understanding can probably come from:
http://ellislab.com/codeigniter/user-guide/database/active_record.html
Try something like this
$this->db->where('db_attr', $var);
return $this->db->get('table');
Try this one.
$id = 'your id';
$this->db->select("*");
$this->db->from("table_name");
$this->db->where('id','$id');
$query = $this->db->get();
return $query->result_array();
In Codeigniter with Method Chaining Style :-
$data['getData'] = $this->db->get_where('table_name',array('column_name'=>$var))->result_array();

This result is a forward only result set, calling rewind() after moving forward is not supported - Zend

In Zend app, I use Zend\Db\TableGateway and Zend\Db\Sql to retrieve data data from MySQL database as below.
Model -
public function getCandidateEduQualifications($id)
{
$id = (int) $id;
$rowset = $this->tableGateway->select(function (Sql\Select $select) use ($id)
{
$select->where
->AND->NEST->equalTo('candidate_id', $id)
->AND->equalTo('qualification_category', 'Educational');
});
return $rowset;
}
View -
I just iterate $rowset and echo in view. But it gives error when try to echo two or more times. Single iteration works.
This result is a forward only result set, calling rewind() after
moving forward is not supported
I can solve it by loading it to another array in view. But is it the best way ? Is there any other way to handle this ?
$records = array();
foreach ($edu_qualifications as $result) {
$records[] = $result;
}
EDIT -
$resultSet->buffer(); solved the problem.
You receive this Exception because this is expected behavior. Zend uses PDO to obtain its Zend\Db\ResultSet\Resultset which is returned by Zend\Db\TableGateway\TableGateway. PDO result sets use a forward-only cursor by default, meaning you can only loop through the set once.
For more information about cursors check Wikipedia and this article.
As the Zend\Db\ResultSet\Resultset implements the PHP Iterator you can extract an array of the set using the Zend\Db\ResultSet\Resultset:toArray() method or using the iterator_to_array() function. Do be careful though about using this function on potentially large datasets! One of the best things about cursors is precisely that they avoid bringing in everything in one go, in case the data set is too large, so there are times when you won't want to put it all into an array at once.
Sure, It looks like when we use Mysql and want to iterate $resultSet, this error will happen, b/c Mysqli only does
forward-moving result sets (Refer to this post: ZF2 DB Result position forwarded?)
I came across this problem too. But when add following line, it solved:
$resultSet->buffer();
but in this mentioned post, it suggest use following line. I just wonder why, and what's difference of them:
$resultSet->getDataSource()->buffer();
This worked for me.
public function fetchAll()
{
$select = $this->tableGateway->getSql()->select();
$resultSet = $this->tableGateway->selectWith($select);
$resultSet->buffer();
$resultSet->next();
return $resultSet;
}
$sql = new Zend\Db\Sql($your_adapter);
$select = $sql->select('your_table_name');
$statement = $sql->prepareStatementForSqlObject($select);
$results = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($results);
$result = $resultSet->toArray();

How to fetch results one by one in Doctrine 1.2?

How can I make something similar to classic PHP PDO
while ($obj = $stmt->fetch()) {...}
in Doctrine 1.2.
I've tried
while ($obj = $query->fetchOne()) {...}
but it returns always only the first object found.
Is there any way I could implement this behaviour?
Doesn't really matter my query. It's a plain simple one (note that I am in the *Table class of the model)
$query = $this->createQuery('a');
While working on a migration command in symfony2 I discovered that $query->executes(); fetches the complete result set into RAM before returning it.
This is not a problem with a small amount of data, but with bigger results your process might run OutOfMemory.
To solve the problem you can iterate through the results "one by one" with this statement:
$query->iterate();
I thing its similare to this PDO statement: while ($obj = $stmt->fetch()) {...}
A more complete example might look like this:
$em = $this->getContainer()->get('doctrine');
$iterator = $em->getRepository('AcmeBundle:Entity')
->createQueryBuilder('e')
->getQuery()->iterate();
foreach($iterator as $item){
$item = $item[0];
// Your logic here:
$item->getId();
....
}
Found this in the doctrine documentation.
Have you tried:
while ($obj = $query->execute()) {...}
And if you want to fetch an array instead of objects:
while ($obj = $query->execute(array(), Doctrine_Core::HYDRATE_ARRAY)) {...}
If you got the connection, do it like this:
$stmt = $conn->query($queryString);
while ($obj = $stmt->fetch()) {...}
With fetchOne() you will only get one entry at all.
Use the hydrate mode Doctrine_Core::HYDRATE_ON_DEMAND
$q = Doctrine_Query::create()
->select('...')
->from('...');
// Returns instance of Doctrine_Collection_OnDemand
$result = $q->execute(array(), Doctrine_Core::HYDRATE_ON_DEMAND);
foreach ($result as $obj)
{
// do something with your object
}
More information : Data Hydrators — Doctrine 1.2.4 documentation

Select ignores where clause using Zend_Db_Select

$table = new Zend_Db_Table(array('name'=>'rules'));
$select = $table->select();
$select->setTable($table);
$select->setIntegrityCheck(false);
$select = $select
->from(array('ru'=>'rules'),array('ru.*'))
->join(array('ro'=>'roles'),'ro.id=ru.role_id',array('role_id'=>'ro.id'))
->join(array('g'=>'groups'),'ro.group_id=g.id',array('group_id'=>'g.id'))
->join(array('ug'=>'user_groups'),"ug.group_id=g.id",array('user_group_id'=>'ug.id'))
->where("ug.user_id={$userId}")
->where("ru.resource='{$resource}'")
->where("ru.privilege='{$privilege}'");
echo "select: ".$select->__toString();
$row = $table->fetchAll();
I have the preceding code,but when I try fetchAll() it returns all rows in the table, ignoring the where clause, when I use fetchRow() it returns the first row it finds, ignoring the where clause, I printed the SQL statement and run it separately and it executes correctly
any clue ?
This is how you would create a db select object correctly
$db = Zend_Db::factory( ...options... );
$select = new Zend_Db_Select($db);
Or you use the database adapter's select() method
$db = Zend_Db::factory( ...options... );
$select = $db->select();
And you can add clauses
// Build this query:
// SELECT *
// FROM "table1"
// JOIN "table2"
// ON "table1".column1 = "table2".column1
// WHERE column2 = 'foo'
$select = $db->select()
->from('table1')
->joinUsing('table2', 'column1')
->where('column2 = ?', 'foo');
Have a look at the Zend_Db Reference Guide for more information
#ArtWorkAD is right in a certain way. But in your case you're not just using a Zend_Db_Select. You tried to extend a Zend_Db_Select obtained from a Zend_Db_Table (well, you should try to handle a Singleton pattern with Zend_Db_Table but this is another problem). Your current problem (if we except the fact you are certainly reading documentation too fast) is that this line was correct:
$select->setIntegrityCheck(false);
It make your 'select-from-a-zend-db-table' not anymore restricted to the Active Record Mode, and available for extra joins.
But just after that you make a:
$select = new Zend_Db_Select($table);
This is the complete creation of a new object, that you put into your variable. Nothing is kept from previous variable value. You could add a $select=null; just before it would be the same. So this is just canceling the 3 previous lines.
In quite the same confusion mode this line:
$select->setTable($table);
Is not necessary as you're already taking the select from a Zend_Db_Table so the table is already there.
EDIT
And your last and bigger error is:
$table->fetchAll()
You do not use your built $select but your $table, so effectively everything done in your $select is ignored :-) . Fecthing from the $select shoudl give you better results
This should work. Just tested it.
$table = new Zend_Db_Table('rules');
$select = $table->getAdapter()->select();
$select->from(array('ru' => 'rules'), array('ru.*'))
->join(array('ro'=>'roles'), 'ro.id = ru.role_id', array('role_id'=>'ro.id'))
->join(array('g'=>'groups'), 'ro.group_id = g.id', array('group_id'=>'g.id'))
->join(array('ug'=>'user_groups'),"ug.group_id=g.id",array('user_group_id'=>'ug.id'))
->where('ug.user_id = ?', $userId)
->where('ru.resource = ?', $resource)
->where("ru.privilege = ?", $privilege);
echo (string)$select;

Categories