I want to add a value to my table if it is not already there. I cant use UNIQUE as there will be multiple lines with the same value. I've tried below but $result returns bool(true). How can I do that?
$ishashinDB = $db->prepare('SELECT COUNT(*) FROM mytable WHERE hash = :hash;');
$ishashinDB->bindValue(':hash', $Ihash);
$result = $ishashinDB->execute();
var_dump($result);
if ($result == 0) {
$addhash = $db -> prepare("INSERT INTO mytable (hash) VALUES (:hash)");
$addhash -> bindParam(':hash', $Ihash, PDO::PARAM_STR);
$addhash -> execute();
}
Use this below execute:
$result = $ishashinDB->setFetchMode(PDO::FETCH_ASSOC);
Related
How to count current week publish node by specific user in drupal for specific content-type ?
Something like this should work:
// select the number of nodes that is of a specific content type and
// were created this week by the named user
function <theme>_post_count($user_name, $content_type) {
$query = "SELECT COUNT(*) node_count FROM {node} n
INNER JOIN {users} u ON u.name = :user_name && u.uid = n.uid
WHERE n.type = :content_type &&
WEEK(FROM_UNIXTIME(n.created)) = WEEK(CURRENT_TIMESTAMP())";
$result = db_query($query,
array(
':user_name' => $user_name,
':content_type' => $content_type
))->fetch();
return $result->node_count;
}
You could easily modify the above query to take a uid instead of a user name and so on.
You would then call this function like this:
print 'Articles added by admin during this week: '.<theme>_post_count('admin', 'article');
my problem it's quite simple.
I'm trying to make a script for dump information from one table in firebird to another in SQLite.
I'm able to do all the process but what I'm not able to do is to create a persistent sqlite database. I launch this script on my computer (Ubuntu 13.04) in "/var/www/PabloLab/experiments" and I don't know where creates the file or if it's created.
The full script:
/*
* Preparing SQLite db
*/
$dbname = 'langs.sqlite';
$my_table = 'LANG';
$db = new SQLite3($dbname, 0666);
$query = "CREATE TABLE $my_table (ID INTEGER NOT NULL,
TXT VARCHAR,
LANG_ID NUMERIC NOT NULL)";
$success = $db->exec($query);
$stmt = "SELECT r.ID, r.TXT, r.LANG_ID
FROM VLANG r
WHERE r.ID in (1,3)";
$sql = EF_sql_connection($stmt, MY_FIREBIRD_DB); //It works perfect, no problem here.
while ($lang_info = ibase_fetch_assoc($sql)) {
$lang = utf8_encode($lang_info["TXT"]);
$id = utf8_encode($lang_info["ID"]);
$lang_id = utf8_encode($lang_info["LANG_ID"]);
$stmt_sqlite = "INSERT INTO $my_table VALUES ($id, '$lang', $lang_id)";
$success = $db->exec($stmt_sqlite);
}
$result = $db->query("SELECT * FROM $my_table");
while($row = $result->fetchArray()){
$id = $row["ID"];
$txt = $row["TXT"];
$lang_id = $row["LANG_ID"];
echo "$id - $txt - $lang_id<br>";
}
Thanks for your help and your time.
Regards.
(Just copying my comment that solved #reverendocabron's problem for easy reference.)
The $flags argument is expected to be SQLITE3_OPEN_READONLY, SQLITE3_OPEN_READWRITE and/or SQLITE3_OPEN_CREATE (whose values are really 1, 2 and 4 respectively) while you give it a Unix-style 0666 argument. In your case, I guess what you're looking for is really SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE which happens to be the default. Try removing
it.
i try to get AVG value in doctrine, in my Repositoru i do this:
public function getFotoSpecifica($idFoto) {
$q = $this->createQueryBuilder('f');
$q->leftJoin("f.foto_votata", 'v');
$q->where('f.id =:idFoto');
$q->andWhere('(f.foto_privata IS NULL OR f.foto_privata != 1)');
$q->andWhere('(f.foto_eliminata IS NULL OR f.foto_eliminata != 1)');
$q->expr()->avg('v.punteggio', true);
$q->setParameter('idFoto', $idFoto);
$dql = $q->getQuery();
$results = $dql->getArrayResult();
return $results;
}
but i don't find any value avg, i see all my object...i try to use createQuery in my controller but i have many errors like: Error: Invalid PathExpression. Must be a StateFieldPathExpression. ( this is a foreign key)
mySql query is:
SELECT profilo_id, proprietario_id, round(AVG( punteggio ),2) as avg_rate, SUM(punteggio) as score, foto_id, count(*) as numero_votanti
FROM prof_voto_foto
WHERE foto_id = ?
Assuming the variable name for the foreign key is named $foto and the entity is ProfVotoFoto
In your controller you can do something like this.
$em = $this->getDoctrine()->getManager();
$q=$em->createQuery("
SELECT profilo_id, proprietario_id, round(AVG( punteggio ),2) as avg_rate,
SUM(punteggio) as score, foto_id, count(*) as numero_votanti
FROM YourBundleName:ProfVotoFoto f
WHERE f.foto = :idFoto
")
->setPArameter('idFoto',$idFoto);
$averageResult = $q->getSingleResult();
You are forget to add a select statement to query. Also possible requires to add group by.
->addSelect('AVG(v.punteggio) as punteggio_avg')
I'm trying to convert this SQL into either DQL or whatever the query builder variant would look like.
select *
from project_release r
where (select s.title as status_name
from release_status_log l
left join release_status s
on l.release_status_id = s.id
where l.release_id = r.id
order by l.created_at desc
limit 1
) not in ('Complete', 'Closed')
;
From inside the repository class for the Release entity, I've tried this
return $this->getEntityManager()->createQuery("
select r.*
from MyBundle:Release r
where (select s.title
from MyBundle:ReleaseStatusLog l
join l.status s
where l.release = r
order by l.createdAt desc
limit 1
) IN ('Complete','Closed')
order by r.release_date ASC
limit 10
")->getArrayResult();
Which gives the error
[Syntax Error] line 0, col 265: Error: Expected
Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got 'limit'
Which is referring to the limit 1 in the subquery.
So then I tried this
return $this
->createQueryBuilder('r')
->select('r.*')
->where("(select s.title
from MyBundle:ReleaseStatusLog l
join l.status s
where l.release = r
order by l.created_at desc
limit 1
) $inClause ('Complete', 'Closed')
")
->setMaxResults( $limit )
->orderBy('release_date', 'ASC')
->getQuery()
->getArrayResult()
;
Which gives the same error. How can I execute a subquery limited to 1 row per row in the parent query?
Symfony 2.0.15
Doctrine 2.1.7
PHP 5.3.3
MySQL 5.1.52
I have a solution for this now. I ended up falling back on the native query system with the result set mapping from the entity in questions.
It's not a great solution, but it works and until I see another solution, it's the only option with this type of WHERE clause.
Here's what my finder method looks like now
/**
* Finds Releases by their current status
*
* #param array $statuses White-list of status names
* #param boolean $blackList Treat $statuses as a black-list
* #param integer $limit Limit the number of results returned
* #param string $order Sort order, ASC or DESC
*
* #throws \InvalidArgumentException
*
* #return array <Release>
*/
public function findByCurrentStatus( array $statuses, $blackList=false, $limit=null, $order='ASC' )
{
if ( empty( $statuses ) )
{
throw new \InvalidArgumentException( "Must provide at least one status" );
}
$inClause = $blackList ? 'not in' : 'in';
$rsm = new ResultSetMappingBuilder($this->getEntityManager());
$rsm->addRootEntityFromClassMetadata('MyBundle:Release', 'r');
$SQL = "
select *
from project_release r
where (select s.title as status_name
from release_status_log l
left join release_status s
on l.release_status_id = s.id
where l.release_id = r.id
order by l.created_at desc
limit 1
) $inClause ('" . implode( "','", $statuses ) . "')
order by r.release_date $order
";
if ( $limit )
{
$SQL .= " limit $limit";
}
return $this
->getEntityManager()
->createNativeQuery( $SQL, $rsm )
->getResult()
;
}
I kind of loathed going back to building a query as a string, but oh well. Oh, and for you eagle-eyes, $statuses does not come from user data, so no SQL injection vulnerabilities here ;)
In addition to your Native SQL solution, you can create two queries using DQL within a single repository method.
Some adjustment may be required but you could try this:
public function findCompletedReleases()
{
$em = $this->getEntityManager();
$dqlSubQuery = <<<SQL
SELECT
s.title status_name
FROM
Acme\MyBundle\Entity\ReleaseStatus s,
Acme\MyBundle\Entity\ReleaseStatusLog l,
Acme\MyBundle\Entity\Release r
WHERE
l.release = r.id AND
l.status = s.id
ORDER BY l.createdAt DESC
SQL;
$statusName = $em->createQuery($dqlSubQuery)
->setMaxResults(1)
->getSingleScalarResult();
$dql = <<<SQL
SELECT
r
FROM
Acme\MyBundle\Entity\Release r
WHERE
:status_name IN ('Complete','Closed')
ORDER BY r.release_date ASC
SQL;
$q = $em->createQuery($dql)
->setParameters(array('status_name' => $statusName))
->setMaxResults(10);
return $q->getArrayResult();
}
I'm trying to run this query on Propel 1.6 with symfony 1.4.20.
I want to bind 2 parameters onto this subquery but its not working.
$paginas = PaginaQuery::create()
->where("pagina.id not in (select id from cliente_artista where cliente_artista.cliente_id = ? and cliente_artista.culture = ?)"
,array('XXX', 'en')
)
->limit(5)
->find();
This gives me the error:
Cannot determine the column to bind to the parameter in clause
I also found this post but there is no answer (https://groups.google.com/forum/?fromgroups=#!topic/propel-users/2Ge8EsTgoBg)
Instead of using placeholders. You may use $id and $culture:
//first, get an array of the id's
//define your vars
$id = $your_id_param;
$culture = 'en';
$cliente_artistas = ClienteArtistaQuery::create()
->select('id')
->distinct()
->filterByClienteId($id)
->filterByCulture($culture)
->find();
$paginas = PaginaQuery::create()
->where("pagina.id NOT IN ?", $cliente_artistas)
->limit(5)
->find();
If this has to be done in one query, recommend using raw sql and binding the parameters into the PDO statement (but then you lose the convenience of PropelObjectCollections):
public function getResultSet($id, $culture) {
$id = $id_param;
$culture = $culture_param;
$sql = <<<ENDSQL
SELECT * from pagina
WHERE id NOT IN (SELECT distinct id
FROM cliente_artista
WHERE cliente_id = ?
AND culture = ?
)
LIMIT 5
ENDSQL;
$connection = Propel::getConnection();
$statement = $connection->prepare($sql);
$statement->bindValue(1, $id);
$statement->bindValue(2, $culture);
$statement->execute();
$resultset = $statement->fetchAll(PDO::FETCH_ASSOC); // or whatever you need
if (! count($resultset) >= 1) {
// Handle empty resultset
}
return $resultset;
}
You could also write some query methods to use propel orm query methods. Ofcourse, the propel api is beneficial reference. There are several ways to do this. I have indicated one method here which should work for you.
EDIT:
Here's an idea on doing this as one query [since useSelectQuery() requires 'relation' name], this idea assumes tables are not related but that id's are:
$paginas = PaginaQuery::create()
->addJoin(PaginaPeer::ID, ClienteArtistaPeer::CLIENTE_ID, Criteria::LEFT_JOIN)
->where("ClienteArtista.Id <> ?", $id)
->where("ClienteArtista.Culture <> ?", $culture)
->select(array('your','pagina','column','array'))
->limit(5)
->find();