postgresql RETURNING in zf2 table gateway - postgresql

How would one add a RETURNING clause in insert via table gateway ?
INSERT INTO users (name, age) VALUES ('Liszt', 10) RETURNING id;

$dataArray = array('name'=> 'Liszt','age' => 10);
$this->tableGateway->insert($dataArray);
$userId = $this->tableGateway->lastInsertValue;
Another method is :
$userId = $this->tableGateway->getLastInsertValue();

if you want to get last insert id in postgresql when inserting into tablegateway you have to use SequenceFeature.
$myTable = new TableGateway('table_name', $dbAdapter, new Feature\SequenceFeature('primary_key', 'sequence_name'));
$id = $myTable->insert(array(/*your data*/));

Related

I am having trouble with my postgresql query

I have a query in mysql works well, but when I go to postgresql does not update me, I want to know where is my error.
I leave my php file the query update does not work
<?php
require_once "Controllers/conexion.php";
session_start();
$resultado=pg_query("SELECT nextval('user_id_seq') as key");
$row=pg_fetch_array($resultado, 0);
$key=$row['key'];
try {
$resultado = pg_query($conexion,"select * from encuesta_respuesta where id_user = '".$_SESSION['user']."' and id_encuesta = '".$_POST['id_encuesta']."'");
while( $row = pg_fetch_assoc($resultado)){
$data = $row;
}
if ($data['estado']=='F') {
header("Location: Inicio.php");
}
foreach($_POST['pregunta'] as $id_pregunta=>$valor){
$query="insert into encuesta_respuesta_opcion values (".$key.",".$_POST['id_encuesta'].",".$id_pregunta.",".$valor.")";
$resultado = pg_query($conexion,$query);
}
$query="update encuesta_respuesta set estado='F' where id_user=".$_SESSION['user']." and id_encuesta = ".$_POST['id_encuesta'];
$resultado = pg_query($conexion,$query);
$resp['error']=false;
} catch (Exception $e) {
$resp['error']=true;
}
header("Location: Inicio.php");
?>
Directly try to update data in your database, check this query works or not. If it works, then you have to change your query building procedure in your application. For example:
postgres=# create table test (id_user VARCHAR (50) PRIMARY KEY, id_encuesta VARCHAR (50), estado VARCHAR (10));
postgres=# insert into test values ('anower','engg.','A');
postgres=# update test set estado='F' where id_user='anower' and id_encuesta='engg.';
The query should work the same in MySql and postgres.
If you are getting different results during updates then your survey tables arent the same.
Most liked id_user and id_encuesta are autoincrement fields. So they dont necesary have the same values.
Try using a Select to see if they have same survey information.
SELECT *
FROM survey
where id_user=".$_SESSION['user']."
and id_encuesta = ".$_POST['id_encuesta'];

Yii2: How to do a simple join query?

I am learning how to do simple queries using the Yii2 framework. I use PostgreSQL.
I am trying to join two tables and get the data from both tables with a where condition.
The tables are called Admins and Persons.
The join use field called idadm.
The condition is idadm = 33. This works great but the result has data only from the Admins table and I need data from the other table.
Here is my example:
$query = \app\models\Admins::find()
->select('*')
->leftJoin('persons', 'persons.idadm = admins.idadm')
->where(['admins.idadm' => 33])
->with('persons')
->all();
I am following the Yii2 official guide: http://www.yiiframework.com/doc-2.0/guide-db-active-record.html
Update: Here I show the updated code that doesn't solve de problem:
You need to write all column name in select().
$query = \app\models\Admins::find()
->select('admin.*,persons.*') // make sure same column name not there in both table
->leftJoin('persons', 'persons.idadm = admins.idadm')
->where(['admins.idadm' => 33])
->with('persons')
->all();
And also you need to define person table attributes in Admin model.
Second way is get records as array,so you dont need to define attributes in Admin model.
$query = \app\models\Admins::find()
->select('admin.*,persons.*') // make sure same column name not there in both table
->leftJoin('persons', 'persons.idadm = admins.idadm')
->where(['admins.idadm' => 33])
->with('persons')
->asArray()
->all();
Ensure that active record has required relations, e.g. something like follows:
class Admins extends \yii\db\ActiveRecord {
public function table() {
return "admins";
}
public function getPersons()
{
return $this->hasMany(Person::className(), ['idadm' => 'idadm']);
}
}
class Person extends \yii\db\ActiveRecord {
public function table() {
return "persons";
}
}
Then use joinWith to build query:
$query = Admins::find()
->joinWith('persons')
->limit(1);
$result = $query->createCommand()->getSql();
echo $result;
Here is produced query:
SELECT `admins`.* FROM `admins`
LEFT JOIN `person` ON `admins`.`idadm` = `person`.`idadm` LIMIT 1

postgres return last id codeigniter

I'm new with postgres database codeigniter
for return last id in mysql
im using this in my model
public function daftar($data){
$this->db->insert('akun', $data);
return $this->db->insert_id();
}
but I'm confuse how to return las id ($this->db->insert_id) in postgres?
From the CodeIgniter documentation:
If using the PDO driver with PostgreSQL, or using the Interbase driver, this function requires a $name parameter, which specifies the appropriate sequence to check for the insert id.
In your case you need return $this->db->insert_id('akun_id_akun_seq'); if "akun_id_akun_seq" is the name of the respective sequence.
If your INSERT is something like this:
INSERT INTO public."MyTable"
(
"SomethingIdFk",
"Date"
)
VALUES
(
8,
CURRENT_TIMESTAMP
);
And MyTable has a serial like MyTableId as primary key, then in your model you can do this:
$id= $this->db->insert_id('public."MyTable_MyTableId_seq"');
to get the last insert id.
That works for me.
More info you can find in this post.

How can I receive bytea data from PostgreSQL through Zend_Db_Select?

I wrote a website with Zend Framework + Postgres. In PostgreSQL there is this table:
create table images(
id serial,
title TEXT DEFAULT '',
thumbnail bytea NOT NULL,
original bytea NOT NULL,
PRIMARY KEY(id)
);
Where I'm planning to store image data.
But when I try to receive anything from the table (select thumbnail from images where id = $id):
$table = $mapper->getDbTable();
$select = $table->select();
$select->from($table,array('thumbnail'));
$select->where('id = ?',$id);
$res = $table->fetchRow($select);
die(print_r($res['thumbnail']));
I receive something like:
Resource id #12_
but not the containing data.
How could I (using Zend_Db_Select) receive this data, but not a Resource id #129?
Sorry for my bad english ...
if the problem remains, replace this line:
die(print_r($res['thumbnail']));
by this:
die(fpassthru($res['thumbnail']))
$stream = $res['thumbnail'];
#unlink($pathFile);
touch($pathFile);
while (($buffer = (fgets($stream, 8192))) !== false) {
file_put_contents($pathFile, $buffer, FILE_APPEND);
}

Zend_Db query and row count without pulling back everything up front

I've created my select:
$select = $zdb->select()
->from(array("b" => "blogs"),
array("id", "active", "updated_by", "title", "synopsis", "create_date", "body"))
->join(array("u" => "users"),
'b.updated_by = u.id',
array("first_name", "last_name"))
->where("u.blogger = ?", 1)
->where("b.publish_date > ?", '2020-01-01')
->where("b.active = ?", 1)
->group("b.id")
->order("b.publish_date DESC")
->limit(5);
and I want to pull the data back a row at a time:
$stmt = $db->query($select);
while ($asset = $stmt->fetch()) {
// do stuff
}
How can I check to make sure that there are rows, without returning the entire resultset?
Using the select you already have, something like that should help you parse every entry
$rows = $zdb->fetchAll($select);
foreach($rows as $row){
...
}
To get the values you just have to do $row['fieldName'] where fieldName is the name of the field in your database