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
Related
I am using the Postgres Package (On the pub.dev site) to UPDATE records in a very simple database. It has two fields: a Text field prime key named number, and a Date field named date_of_birth.
If the date_of_birth is a valid DateTime string then all is well (as can be seen from the code below). But if date_of_birth is unknown (so I set to null) the UPDATE fails:
import 'package:postgres/postgres.dart';
void main() async {
final conn = PostgreSQLConnection(
'localhost',
XXXXX,
'XXXXX',
username: 'XXXXX',
password: 'XXXXX',
);
await conn.open();
DateTime dob = DateTime.now();
var results;
results = await conn.query('''
UPDATE account_details
SET date_of_birth = '$dob'
WHERE number = '123123'
''');
await conn.close();
}
If I set:
dob = null;
The program fails with the error:
Unhandled exception:
PostgreSQLSeverity.error 22007: invalid input syntax for type date: "null"
So I need to include a check on the dob field and the program now looks like this:
DateTime dob = DateTime.now();
dob = null;
var results;
if (dob == null) {
results = await conn.query('''
UPDATE account_details
SET date_of_birth = null
WHERE number = '123123'
''');
} else {
results = await conn.query('''
UPDATE account_details
SET date_of_birth = '$dob'
WHERE number = '123123'
''');
}
That works fine for my simple database, but in my real App. I have a number of date fields in one table. So I have to do a check for each possible combination of those date values - writing a code block for each!
Can anyone tell me how I can UPDATE both null and a valid date using a single statement please?
You are quoting the query parameters yourself. NEVER do this. In addition to the sort of problem you have just seen it also leaves you open to a trivial SQL injection attack.
The library you are using will have some way of putting placeholders into the query text and passing variables when executing the query. Use that.
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'];
I have two tables with relationships, they are :
Table users - Table Region
----------------- -----------------
' idUser ' ' idRegion '
'-------------- ' '---------------'
' email ' ' regionName '
'---------------' '---------------'
' password '
'---------------'
' user_name '
'---------------'
' phone_number '
'---------------'
' id_Region '
'---------------'
In my case, it has three states of inserting and updating datas.
The user will populate just the Email and password rows.
The user is able to populate the rest of rows including the RegionName.
And finally, the user can update any rows that he wants but email and password.
So, the first case I already did, it's easy, the second works fine, but the problem is when I try to update for the second time, inside of my Regiontable it creates a new row instead of change the selected field.
My Code :
public HttpResponseMessage Update(UsersGetModel usersGetModel)
{
using (var context = new GoneDatabase())
{
try
{
var user = context.users.Where(a => a.idUser== usersGetModel.id).FirstOrDefault();
user.userName = usersGetModel.Name;
user.PhoneNumber = usersGetModel.PhoneNumber;
user.Region = new region{ regionName= usersGetModel.Region };
context.Entry(user).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
It's creating a new row because you're literally telling it to by constructing a new Region instance at
user.Region = new region{ regionName= usersGetModel.Region };
Rather, you need to retrieve an existing Region instance from the DbContext and use that, like
user.Region = context.Set<Region>().Where(r => r.Name.Equals(usersGetModel.Region).SingleOrDefault();
A couple notes:
"SingleOrDefault" will throw an exception if there is more than one row in the Region table that matches the "Where" criteria
You need to put some constraints on your database tables to prevent #1 from happening, if business logic/specs indicate it
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.
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);
}