I want to display the last ID from a column called id_client, I'm using ZendFramework.
This is how i write my query in php:
$select = $this->getDbTable()->select('ID_CLIENT');
$select->order('ID_CLIENT DESC');
$result = $this->getDbTable()->fetchAll($select);
$result = $result[0];
var_dump($result);
The problem is that it returns a select * and I do not understand why knowing that I specify that I had to select only id_client :
Anyone as an idea?
I think this is ZF 1.x. Column selection is done in "from" method. Your query should be something like this:
// $db should be a Zend_Db instance
$select = $db->select()
->from(
array('alias' => 'table_name'),
array('ID_CLIENT')
);
$select->order('ID_CLIENT DESC');
$result = $this->getDbTable()->fetchAll($select);
$result = $result[0];
var_dump($result);
Good ol' Zend Framework 1.
If I understand it right, you are trying to retrieve only the id_client of the last row of that table.
If so, you have to sort the results by id_client in descending order and then retrieve the first line with the method current(). Don't forget that the result is an object (Zend_Db_Table_Row) and it has to be accessed properly.
$select = $this->getDbTable();
$select->from('TABLE_NAME'); // Not really necessary
$select->columns('ID_CLIENT');
$select->order('ID_CLIENT DESC');
$result = $this->getDbTable()->fetchAll($select)->current();
$lastIdClient = $result->id_client;
Related
looking at the php function bellow i have this scenario: there is more then one IdUserfollow each id have to be passed on result2 and all the retrieved values have to be combined and returned to Xcode
function viewhome($IdUser){
$result1 = query("SELECT * FROM follows WHERE IdUser = '%s' ", $IdUser);
$IUser = $result['result'][0]['IdUserfollow'];
$result2 = query("SELECT * FROM photos WHERE IdUser = '%s' ORDER BY IdPhoto DESC LIMIT 50", $IUser);
print json_encode($result2);
}
how can i do that.
i sow this problem Using a Loop Inside a Function which was similar to mine but still I'm confused. considering that my return will be using JSON and also i don't know how to set the loop limit from the first query result. is it possible that i will have to do two functions, the first one will return the number of repetition and the second one will only have the loop and return the result? if yes then how can i combine two results - or whatever the value of the repetition is- and send it back using json
any help would be appreciated.
You may collect all retrieving data from second query to result array like this:
function viewhome($IdUser){
$result1 = query("SELECT * FROM follows WHERE IdUser = '%s' ", $IdUser);
$IUser = $result['result'][0]['IdUserfollow'];
$result = array();
foreach ( $result['result'] as $data ) {
$result[] = query("SELECT * FROM photos WHERE IdUser = '%s' ORDER BY IdPhoto DESC LIMIT 50", $data['idUserfollow']);
}
print json_encode($result); // all the results for each IdUserfollow from first query
}
But all the same, I advice you not to send several queries to DB, but build only one query, wich solve you problem.
OK so I am looking for a neat and short way to count the number of rows from a SELECT query using Doctrine DBAL.
I know that I could SELECT COUNT(*) but then I need to sort through the array when I fetch results. Alternatively, it's been suggested to look in to getScalarResult(). But I can't seem to find any documentation about this, other than in DQL (which is a different project).
So what is the neatest way to do this? I guess it's because I'm used to the great MySQLI attribute num_rows!
Another way to do this with Doctrine DBAL is to get the count as a field and return the column
$sql = "SELECT count(*) AS Total FROM myTable WHERE myId = :myId";
$stmt = $conn->prepare($sql);
$stmt->bindValue('myId', $myId, PDO::PARAM_INT);
$stmt->execute();
$count = $stmt->fetchColumn(0);
Actually I thought I had looked really hard, but I just came across this Count Records Returned MySQL Doctrine
So the way to do it is via the rowCount() method.
Example:
$num_rows = $conn->executeQuery("SELECT * FROM users")->rowCount();
I enjoy to use the query builder. An example:
$queryBuilder = $connection->createQueryBuilder();
$queryBuilder->select('COUNT(*)');
$queryBuilder->from("the_table");
$queryBuilder->where('some_column = :theValue');
$queryBuilder->setParameter('theValue', $someValue);
return (int) $queryBuilder->execute()->fetchColumn();
Here is an updated version of #DonkeyKong answer for Doctrine DBAL >= 2.13:
$sql = "SELECT count(*) AS Total FROM myTable WHERE myId = :myId";
$stmt = $conn->prepare($sql);
$stmt->bindValue('myId', $myId, PDO::PARAM_INT);
$result = $stmt->executeQuery();
$count = $result->fetchOne();
I want to get the maximum id of row data. In my table first column is id then firstname and etc.
this is the sql command I used to get the max(id) of row data.
<?PHP $maxid=$this->db->query("SELECT MAX(id) FROM `emplyee_personal_details`");
print_r( $maxid) ;?>
but it prints bunch of data as it is a array. But I need only the maximam id of row data for validation before data inserting and updating.
How to get the maxid. I use codeigniter framework.
Try this:
$maxid = $this->db->query('SELECT MAX(id) AS `maxid` FROM `emplyee_personal_details`')->row()->maxid;
UPDATE
This will work even if your table is empty (unlike my example above):
$maxid = 0;
$row = $this->db->query('SELECT MAX(id) AS `maxid` FROM `emplyee_personal_details`')->row();
if ($row) {
$maxid = $row->maxid;
}
The problem with using a raw query like "SELECT MAX(id) ..." is it is not abstract and may not work for every SQL engine. I think the active record way to do it is like this:
$this->db->select_max('id');
$query = $this->db->get('emplyee_personal_details');
// Produces: SELECT MAX(id) as age FROM emplyee_personal_details
See: http://ellislab.com/codeigniter/user-guide/database/active_record.html
SELECT id FROM table ORDER BY id DESC LIMIT 1
That will get you the highest id value, and when I read this, "it prints bunch of data as it is a array" I get the sense that what you really want is a part of that array. DB queries always return complex structures like arrays or objects. So if you wanted just the scalar value (the number as an integer) you might use something like this:
$maxid = (int)$maxid['id'];
or like this (if you have an object):
$maxid = (int)$maxid->id;
HTH, ~Ray
Try this,hope it helps,
return $this->db->select_max('id')
->get('your_table_name')
->row()->id;
public function getMaxCategoryId() {
$query = $this->db->query("SELECT category_id+1 AS maxid FROM " . DB_PREFIX . "category ORDER BY category_id DESC LIMIT 1");
return $query->row['maxid'];
}
error undefined index maxid
<?php`$qry = "select max(ID)+1 As ID from records";`
$result = $con->query($qry);
$row = $result->fetch_assoc();`echo "New ID To Enter = ".$row["ID"];?>
After Connection Just Write This Code It Will Work
How can I using KohanaPHP framework and database module get mysql table structure?
I've tried this:
$query = DB::query(NULL, 'DESCRIBE table_name');
$result = $query->execute();
But it only returns number of columns in table, and foreach loop failed.
Is there any other way to get table structure or how can I update code above to works properly?
Try this:
$query = DB::query(NULL, 'SHOW FULL COLUMNS FROM table_name');
$result = $query->execute();
EDIT
You need to specify the type of query of DB::query() will just return the number of affected rows.
$query = DB::query(Database::SELECT, 'SHOW FULL COLUMNS FROM table_name');
$result = $query->execute();
This will give you the result you expect.
Thanks for previous replies
I am execution "select Name from table_name where id=1"; . i saw some tutorials for getting data from the database, they mentioned $DB = new Zend_Db_Adapter_Pdo_Mysql($params);
DB->setFetchMode(Zend_Db::FETCH_OBJ); and the result will getting through $result = $DB->fetchAssoc($sql); This $result is an array format, i want to get only name instead of getting all the data from the database. I am new to this topic. if i made any mistake pls do correct.
try this:
$result = $DB->fetchOne("SELECT name FROM table_name WHERE id=1");
This code will execute your query through doctrine getServiceLocator(). With the help of createQueryBuilder(), you can write your query directly into zend-framework2, and with setParameter, any desired condition would be set easily.
$entityManager = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
$qb = $entityManager->createQueryBuilder();
$qb->select(array(
'TableName.columnName as columnName '
))
->from('ProjectName\Entity\TableName', 'TableName')
->where('TableName.TableId = :Info')
->setParameter('Info', $id);
$var= $qb->getQuery()->getScalarResult();
The $var variable holds the value for which, you wanted the comparison to be made with, and holds only the single values of your interest.