How to display a row count result in twig file - mysql

I am fetching a row count inside a repository and that query is returning an array as a result. How do i fetch the number count and display the result in my twig file?
This is the query fetching row count:
public function getTrailCount(){
$sql = "SELECT count(`id`) FROM `article` where `publish`='1' AND `catForFilter` like '%trail%' ";
$stmt = $this->connection->prepare($sql);
$stmt->execute();
$trailCount = $stmt->fetchAll(PDO::FETCH_ASSOC);
//$trailCount->getSingleScalarResult();
//echo '<pre>'; print_r($trailCount); exit;
return $trailCount;
}
In controller i am trying to fetch it like this, i know its a wrong procedure though:
foreach($trailCount as $trail){
$data['trailCount'] = $trail->count; //throughing an error
}
How to mend this code, any help is much appreciated. Thanks

In that case, using PDO::FETCH_NUM would be much simpler:
$trailCount = $stmt->fetchAll(PDO::FETCH_ASSOC);
...
foreach($trailCount as $trail){
$data['trailCount'] = $trail[0]; // Using "0" instead of named key
}
But if you still really want to use FETCH_ASSOC you would need:
$sql = "SELECT count(`id`) as cnt FROM `article ...... "
.....
foreach($trailCount as $trail){
$data['trailCount'] = $trail['cnt'];
}
Notice that I'm not using ->cnt but ['cnt'] since data returned from PDO is not object-based but array-bases instead.
Hope this helps a bit...
EDIT:
Given the lack of Twig part, I can only assume what you're trying to do:
/**
* #Route("/foo")
* #Template()
*/
public function fooAction(){
...
... The code above
...
return array('data' => $data);
}
And then, in your twig:
{{ data.trailCount }}

I got the solution with some help of Jovan Perovic, i did like this:
The query Part:
public function getTrailCount(){
$sql = "SELECT count(`id`) as cnt FROM `article` where `publish`='1' AND `catForFilter` like '%trail%' ";
$stmt = $this->connection->prepare($sql);
$stmt->execute();
$trailCount = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $trailCount[0]['cnt']; //instead of an array i passed the single value
}
in controller:
$trailCount = $clicknblog->getTrailCount();
return $this->render('AdventureBiddingBundle:Organiser:editProfileOrganiser.html.twig', array(
'trails' => $trailCount
));
in twig file i displayed the value directly:
<p>{{ trails }}</p>
Hope this helps to someone with same problem

Related

Unique Profile Slug with PHP and PDO

I am using a class to generate a string name profile to slug and next use an SQL command to tell me whats the unique value to use in insert command, the problem is the command isn't working properly, sometimes it is possible to return a value which already exist...
Thats the class I am using to generate the slug: (composer require channaveer/slug)
And this the example code:
use Channaveer\Slug\Slug;
$string = "john doe";
$slug = Slug::create($string);
$profile_count_stmt = $pdo->prepare("
SELECT
COUNT(`id`) slug_count
FROM
`advogados_e_escritorios`
WHERE
`slug_perfil` LIKE :slug
");
$profile_count_stmt->execute([
":slug" => "%".$slug."%"
]);
$profile_count = $profile_count_stmt->fetchObject();
if ($profile_count && $profile_count->slug_count > 0) {
$profile_increment = $profile_count->slug_count + 1;
$slug = $slug . '-' . $profile_increment;
}
echo 'Your unique slug: '. $slug;
// Your unique slug: john-doe-5
This is the content of the table when the script run:
Do you know how can I improve the select command to prevent it to return existing slugs from DB?
Ok finally found a solution... Heres the code for who wants to generate unique profile slugs using PHP - PDO and MySQL
$string = "John Doe";
$string = mb_strtolower(preg_replace('/\s+/', '-', $string));
$slug = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
$pdo = Conectar();
$sql = "
SELECT slug_perfil
FROM advogados_e_escritorios
WHERE slug_perfil
LIKE '$slug%'
";
$statement = $pdo->prepare($sql);
if($statement->execute())
{
$total_row = $statement->rowCount();
if($total_row > 0)
{
$result = $statement->fetchAll();
foreach($result as $row)
{
$data[] = $row['slug_perfil'];
}
if(in_array($slug, $data))
{
$count = 0;
while( in_array( ($slug . '-' . ++$count ), $data) );
$slug = $slug . '-' . $count;
}
}
}
echo $slug;
//john-doe-1
You should check if the slug exists or not from your database. If it already exists then you can append some random string like the following
$slug = Slug::create($string);
$slugExists = "DB query to check if the slug exists in your database then you may return the count of rows";
//If the count of rows is more than 0, then add some random string
if($slugExists) {
/** NOTE: you can use primary key - id to append after the slug, but that has to be done after you create the user record. This will help you to achieve the concurrency problem as #YourCommenSense was stating. */
$slug = $slug.time(); //time() function will return time in number of seconds
}
//DB query to insert into database
I have followed the same for my blog articles (StackCoder) too. Even LinkedIn follows the same fashion.
Following is screenshot from LinkedIn URL

codeigniter 3 $query = $this->db->query($queri_str); return 0 result

Good morning,
I have a problem with mysql and coeigniter 3.
if I request data with
$ query = $ this-> db-> query ($ queri_str);
it does not give me results.
if I enter the query on phpmyadmin it shows me two results.
$ queri_str = 'SELECT * FROM `my_table` WHERE` id_mytable2` = "'. $ id_name. '"';
The database tables were created with mysql workbench and automatically the reference to the main table with a 1: n ratio was added
Try this query
$this->db->select('*');
$this->db->where('id', '58e5j0m5bqrs7hk8suokko28hj7ni0v6');
$result = $this->db->get('ci_sessions')->result_array();
print_r($result);
Try this solution, you want to do a normal select,I don't know the query your wrote but
public fucntion get_data($id){
$this->db->select('*');
$this->db->from('your_table');
$this->db->where('id','=' ,'$id');
$query = $this->db->get();
$data = $query->result_array();
return $data;
}
the problem is back.
I'll explain.
function myfunction($id_myname) {
$this->db->select('*');
$this->db->where('id_myname', $id_myname);
//$query = $this->db->get('my_table');
$query = $this->db->get('my_table');
//print_r($query);
//var_dump($query);
if ( !$query ){
$error = $this->db->error(); // Has keys 'code' and 'message'
}
return $query->result();
}
when I call this function an empty value comes back to me.
While if I enter the value of the query in phpmyadmin I find two values

Zend Framework - join query

I build a function
public function getBannedByLogin($commentId)
{
$sql = $this->getDbAdapter()->select()
->from(array('comments' => 'comments'), array())
->join(array('users' => 'qengine_users'),
'comments.bannedBy = users.userId',
array())
->where('commentId = ?', $commentId)
;
$row = $this->fetchRow($sql);
return $row['login'];
}
And there are problems, that does'nt work! :D
Let's I explain you. Column 'bannedBy' from comments returns id of user, who give a ban. I need to join this with table users to load a login field. Where i have mistakes?
I assume the code works in the sense of not throwing an exception. If so, your code is OK, you just specifically tell Zend_Db not to select any columns.
public function getBannedByLogin($commentId)
{
$sql = $this->getDbAdapter()->select()
->from(array('comments' => 'comments'))
->join(array('users' => 'qengine_users'),
'comments.bannedBy = users.userId')
->where('commentId = ?', $commentId)
;
$row = $this->fetchRow($sql);
return $row['login'];
}
The last argument to from() and join() functions is an array of columns you wish to select. If you pass in an empty array, no columns are selected. No argument = select everything. You can, of course, specify only the columns you need too.

How to write SQL query using Doctrine 2's NativeQuery with joins?

I want to write a query that involves the use of 'UNION' (which is not supported by DQL) therefore I am trying to write a MySQL query using Doctrine 2's NativeQuery. I have been using Doctrine's documentation.
So far my code consists of:
$rsm = new ResultSetMapping();
$rsm->addEntityResult('\Entities\Query', 'q');
$rsm->addFieldResult('q', 'id', 'id');
$rsm->addFieldResult('q', 'title', 'title');
$rsm->addFieldResult('q', 'deadline', 'deadline');
$query = $this->_em->createNativeQuery('SELECT query.id, query.title, query.deadline FROM query', $rsm);
$aQuery = $query->getResult();
$aQuery = $query->getResult();
foreach($aQuery as $o){
echo '<p>';
echo 'id: '.$o->getId().'<br/>';
echo 'title: '.$o->getTitle().'<br/>';
echo 'deadline: '.$o->getDeadline()->getTimestamp().'<br/>';
echo '</p>';die;
}
This returns the expected results. However, I run into problems when I try to introduce a second table/entity in the query:
$rsm->addJoinedEntityResult('\Entities\Status', 's', 'q', 'status');
$rsm->addFieldResult('s', 'id', 'id', '\Entities\Status');
Those lines throw a: Notice: Undefined index: id message.I can't figure out why this is.
The query table has a 'status_id' column, which is a foreign key referring to the 'id' column of the 'status' table. In the query entity class I have mapped the status property as follows:
/**
* #var Status
*
* #ManyToOne(targetEntity="Status")
* #JoinColumns({
* #JoinColumn(name="status_id", referencedColumnName="id")
* })
*/
private $status;
Along with relevant get and set methods.
I have spent quite some time on trying to figure this out. Appreciate it if someone could shed some light on this.
You may write your query in any repository like below then you will get expected ans. In This way you use any SQL function of MySQL
public function yourFunction()
{
$em = $this->getEntityManager()->getConnection();
$sql = "YOUR DESIRE SQL"; // like SELECT * FROM users
try {
return $em->query($sql)->fetchAll();
} catch (\Doctrine\ORM\NoResultException $e) {
return null;
}
}

PHP PDO succinct mySQL SELECT object

Using PDO I have built a succinct object for retrieving rows from a database as a PHP object with the first column value being the name and the second column value being the desired value.
$sql = "SELECT * FROM `site`"; $site = array();
foreach($sodb->query($sql) as $sitefield){
$site[$sitefield['name']] = $sitefield['value'];
}
I now want to apply it to a function with 2 parameters, the first containing the table and the second containing any where clauses to then produce the same result.
function select($table,$condition){
$sql = "SELECT * FROM `$table`";
if($condition){
$sql .= " WHERE $condition";
}
foreach($sodb->query($sql) as $field){
return $table[$field['name']] = $field['value'];
}
}
The idea that this could be called something like this:
<?php select("options","class = 'apples'");?>
and then be used on page in the same format as the first method.
<?php echo $option['green'];?>
Giving me the value of the column named value that is in the same row as the value called 'green' in the column named field.
The problem of course is that the function will not return the foreach data like that. That is that this bit:
foreach($sodb->query($sql) as $field){
return $table[$field['name']] = $field['value'];
}
cannot return data like that.
Is there a way to make it?
Well, this:
$sql = "SELECT * FROM `site`"; $site = array();
foreach($sodb->query($sql) as $sitefield){
$site[$sitefield['name']] = $sitefield['value'];
}
Can easily become this:
$sql = "SELECT * FROM `site`";
$site = array();
foreach( $sodb->query($sql) as $row )
{
$site[] = $row;
}
print_r($site);
// or, where 0 is the index you want, etc.
echo $site[0]['name'];
So, you should be able to get a map of all of your columns into the multidimensional array $site.
Also, don't forget to sanitize your inputs before you dump them right into that query. One of the benefits of PDO is using placeholders to protect yourself from malicious users.