How can I receive bytea data from PostgreSQL through Zend_Db_Select? - zend-framework

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);
}

Related

Insert UUID to PostgreSQL table using PDO

I am using UUID's in PostgreSQL as Primary Key for my tables. I am trying to insert the UUID using PDO and prepared statement. However, I am not able to bind the value using bindValue. These are the steps I am trying to follow:
$sql = "INSERT INTO customers.customers(customer_id, first_name, last_name, email_address)";
$sql .= " VALUES(":customer_id", ":first_name", ":last_name", ":email_address")";
$this->stmt = prepare($sql);
$this->stmt = bindValue(":customer_id", $customer_uuid); //*** WHAT PDO value to use Here??????
$this->stmt = bindValue(":first_name", $first_name, PDO::PARAM_STR);
$this->stmt = bindValue(":last_name", $last_name, PDO::PARAM_STR);
$this->stmt = bindValue(":email_address", "$email_address, PDO::PARAM_STR);
$this->stmt->execute();
As can be seen here, each "bindValue" statement required to have a PDO parameter type value. I have not been able to find what value can be used for a UUID type column. I tried using the PDO::PARAM_STR, but this creates a Data Type error when inserting the UUID int he column as the column type for customer_id is UUID.
Any suggestions from the community here?
I tried converting the UUID to string and then back to UUID, but it did not work. From here, I don't know what else I can try.

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'];

Can jaydata work with existing table or database?

If I have table in WebSQL database with some data can jaydata work with it?
For example, I have such table:
var shortName = 'Del';
var version = '1.0';
var displayName = 'Del';
var maxSize = 65536;
db = openDatabase(shortName, version, displayName, maxSize);
db.transaction(
function(transaction) {
transaction.executeSql(
'CREATE TABLE IF NOT EXISTS "main" ("name" VARCHAR NOT NULL , "last" DATETIME NOT NULL DEFAULT CURRENT_DATE);'
);
}
);
Disclaimer: I work for JayData
Yes, if you are following the naming conventions JayData uses you are able to use existing databases on a limited extent. Foreign keys and relations are likely a thing that will not work.

HTML5 Database to verify exist table?

Is there a way to verify whether the table is exist inside the database in HTML5 local database?
I need to create 9 tables, and this method will run when the document ready. If each time the page start, it also calling the same method, will it not be waste of memory? I using it for the mobile device (iPhone).
This is the code:
try{
if(!window.openDatabase){
alert('DB not supported.');
}else{
var shortName = 'abc';
var version = '1.0';
var displayName = 'ABC';
var maxSize = 3145728;
var tableName = ['business', 'politic', 'firstread', 'commentary','features', 'insiderasia', 'management', 'media'];
db = openDatabase(shortName, version, displayName, maxSize);
$.each(tableName, function(theCount, value){
db.transaction(
function(transaction){
transaction.executeSql('CREATE TABLE IF NOT EXISTS '+ value +' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, link TEXT NOT NULL, title TEXT NOT NULL, author TEXT NOT NULL, pubdate TEXT NOT NULL, imgLink TEXT NULL, desc TEXT NOT NULL, day TEXT NOT NULL);');
});
});
}
}catch(e){
if(e == INVALID_STATE_ERR){
console.log('invalid database version.');
}else{
console.log('unknown error ' + e + '.');
}
return;
}
For what you need this? If you worry about that you can recreate table that already exist in your database, you need creating your table with this SQL query:
CREATE TABLE IF NOT EXISTS table_name

Cannot refresh row as parent is missing. Zend Framework

i am getting the error "Cannot refresh row as parent is missing" when I try to save. Here is my code
abstract class Webapp_Model_Resource_Db_Table_Abstract
extends Zend_Db_Table_Abstract
{
/**
* Save a row to the database
*
*
* #param array $info The data to insert/update
* #param Zend_DB_Table_Row $row Optional The row to use
* #return mixed The primary key
*/
public function saveRow($info, $row = null)
{
if (null === $row) {
$row = $this->createRow();
}
$columns = $this->info('cols');
foreach ($columns as $column) {
if (array_key_exists($column, $info)) {
$row->$column = $info[$column];
}
}
return $row->save();
}
}
when I call the saveRow() method, I pass in the $_POST values ($form->getValues())
I have reused this class with my other modules in the same application but now I am getting this error and I am not sure why. My table is pretty straight forward:
CREATE TABLE `news` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`headline` varchar(100) DEFAULT NULL,
`snippet` varchar(500) DEFAULT NULL,
`full_text` text,
`author` varchar(100) DEFAULT NULL,
`publish_from` date DEFAULT NULL COMMENT 'Publish date',
`publish_to` date DEFAULT NULL COMMENT 'Take it down or mark as draft after this date',
`datecreated` timestamp NULL DEFAULT NULL COMMENT 'First created on',
`revised` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Timestamp for the last time it was revised',
`draft` tinyint(1) DEFAULT '0' COMMENT 'Should not be published',
`departments_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=214 DEFAULT CHARSET=utf8 COMMENT='Stores news articles';
Anyone know what I am doing wrong?
::::::::::::::ADDTION:::::::::::::
public function saveNews($post,$defaults = array())
{
//get the form
$form = $this->getForm('article' . ucfirst($validator));
//validate
if(!$form->isValid($post)) {
return false;
}
//get fitered values
$data = $form->getValues();
//apply defaults
foreach($defaults as $col => $value) {
$data[$col] = $value;
}
//get the article if it exists
$article = array_key_exists('id', $data) ?
$this->getNewsById($data['id']) : null;
return $this->saveRow($data, $article);
}
When you pass an empty value for the primary key, Zend seems to return this value instead of the inserted auto-increment value - even though a new row is created properly with an auto-increment value, the inserted value will not be returned.
Maybe your problem is related to this. If so, try unsetting the id field prior to saving.
You have to tell DbTable that there is a Auto Incrementing Primary Key by setting $_sequence either to true or the Sequence Name.
15.5.4.1. Using a Table with an Auto-incrementing Key
Check your $info array. Probably you have some empty value for your primary key there.
So array_key_exists($column, $info) returns true and you assign an empty primary key to your row. And this causes the error as the row with this key does not exist.
try
if (array_key_exists($column, $info) and $column != 'YOUR_PRIMARY_KEY_NAME')
{
$row->$column = $info[$column];
}
In my case the problem was missing AUTO_INCREMENT.
Could you post the function:
$this->getNewsById($id)
There is your problem...