samedi 9 mai 2015

WebsitePanel database restore

I want to be able to use the Database restore option from WebsitePanel.

When I try to restore a database from the hosting space I get "The operation has timed out" exception.

Where can I change the timeout settings (I have dedicated server and have the appropriate permissions)?

The full stack trace is following:

Stack Trace:    System.Net.WebException: The operation has timed out 
at System.Web.Services.Protocols.WebClientProtocol.GetWebResponse(WebRequest request) 
at System.Web.Services.Protocols.HttpWebClientProtocol.GetWebResponse(WebRequest request) 
at Microsoft.Web.Services3.WebServicesClientProtocol.GetResponse(WebRequest request, IAsyncResult result) 
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) 
at WebsitePanel.EnterpriseServer.esDatabaseServers.RestoreSqlDatabase(Int32 itemId, String[] uploadedFiles, String[] packageFiles) 
at WebsitePanel.Portal.SqlRestoreDatabase.RestoreDatabase()

Author and viewer permissions to an article

I am building a Django web application which will contain articles that will only be shared with specific users that the author chooses. It is trivial to give the author the rights to edit the article, however I am trying to find the best way to limit the users that can view the article. I am considering creating a group per article and adding users to that group, however as there will be thousands of articles this will mean making thousands of groups. Also I would have to write code that would programmatically generate the group name and associate it with the specific article.

The alternative approach would be to associate the articles that a user has permission to view with the users profile.

Is there a best practice way to do this? I have researched extensively users and roles but I have been unable to find any articles that discuss this specific situation.

Thank you.

Rails 4: sometimes records are saved and sometimes they are not?

I have a weird thing happening. I have a Model call Recipe that has_many :informations and :directions. When I try to save the @recipe (see my controller) with its many :informations and :directions; sometimes it works and sometimes it does not without me changing anything to the source code.

Also, the :informations are always saved; the problem seems to only be regarding the :directions

Here is my controller:

    def new
        @recipe = current_user.recipes.new
    end

    def create
        @recipe = current_user.recipes.new(recipe_params)

        if @recipe.save
            redirect_to @recipe, notice: "Successfully created new recipe"
        else
            render 'new'
        end
    end     
    private

    def recipe_params
        params.require(:recipe).permit(:category_id, :title, :description, informations_attributes: [:id, :title, :url, :_destroy], directions_attributes: [:id, :title, :url, :step, :_destroy])
    end
end

When I try to save from my form here are the params:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"wfa+wTI+C3hnvscAC1O922EYlssJE3zAbEmmqMbmR+5krb0b17fkWhsXVAW1aFcom8x11uGqGO6drQudGhdcvA==", "recipe"=>{"title"=>"test", "description"=>"test", "category_id"=>"3", "informations_attributes"=>{"1431197959831"=>{"title"=>"test", "url"=>"dede", "_destroy"=>"false"}, "1431197959835"=>{"title"=>"ded", "url"=>"dede", "_destroy"=>"false"}}, "directions_attributes"=>{"1431197963709"=>{"title"=>"dede", "url"=>"dede", "step"=>"de", "_destroy"=>"false"}, "1431197963712"=>{"title"=>"ded", "url"=>"ded", "step"=>"ded", "_destroy"=>"false"}}}, "commit"=>"Create Theme"}

Shema:

  create_table "directions", force: :cascade do |t|
    t.text     "step"
    t.integer  "recipe_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string   "url"
    t.string   "title"
  end


  create_table "information", force: :cascade do |t|
    t.string   "url"
    t.integer  "recipe_id"
    t.datetime "created_at",                            null: false
    t.datetime "updated_at",                            null: false
    t.integer  "cached_votes_total",      default: 0
    t.integer  "cached_votes_score",      default: 0
    t.integer  "cached_votes_up",         default: 0
    t.integer  "cached_votes_down",       default: 0
    t.integer  "cached_weighted_score",   default: 0
    t.integer  "cached_weighted_total",   default: 0
    t.float    "cached_weighted_average", default: 0.0
    t.string   "title"
  end


  create_table "recipes", force: :cascade do |t|
    t.string   "title"
    t.text     "description"
    t.integer  "user_id"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.integer  "category_id"
  end

Thanks for your help !

Android SQLite database contains only null values

I am trying to insert the values from an array into SQLite database. The problem is that the function can insert only null values even though the array does not contain such values.

The function for insert :

public void addArrayEntry(String [] response){
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        //System.out.println(response.length);
        for (int i=1; i<response.length; i++){
            values.put(temperature,response[i]);
            db.insert(tableStatistics,null,values);
        }

        db.close();
    }

    catch (Exception e){
        Log.e("Error in insert", e.toString());
    }

}

String createTable = "CREATE TABLE statistics ( " +
            "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
            "temperature REAL, "+
            "light INTEGER, "+
            "humidity INTEGER)";

Array values :

05-08 14:24:21.405 10720-10720/org.security.andreiism.iotsecurity I/System.out﹕ 23.798828125
05-08 14:24:21.405 10720-10720/org.security.andreiism.iotsecurity I/System.out﹕ 744
05-08 14:24:21.405 10720-10720/org.security.andreiism.iotsecurity I/System.out﹕ 424

SQL Trigger: Inserting a row in a table after an insert on another table, if a given value doesn't already exist in the first table

As the title says, I'm trying to insert a row in one table, triggered after an insertion on another table, but only if a given value doesn't already exist in the first table.

Example:

I have one table, countries, which stores countries and their id's:

Countries

id   country 
1    England 
2    France  
...  ...    

I have another table, events, which stores information about events as follows:

Events

id  timestamp   city    country
1   13435636    London  England
2   45635742    Paris   France
... ... ... ...

What I want to do: create a trigger so that after an insertion on the events table, insert a new row in the countries table with the country that the event occurred in, but only if that country doesn't already exist in the countries table.

What I have tried:

CREATE TRIGGER Update
AFTER INSERT ON events FOR EACH ROW
    INSERT INTO countries (country) VALUES (New.country)
    WHERE NOT EXISTS (SELECT country FROM countries WHERE country = New.country)

CREATE TRIGGER Update
AFTER INSERT ON events FOR EACH ROW
    IF NOT EXISTS (SELECT country FROM countries WHERE country = New.country)
    BEGIN
        INSERT INTO countries (country) VALUES (New.country)
    END

CREATE TRIGGER Update
AFTER INSERT ON events FOR EACH ROW
    IF NOT EXISTS (SELECT country FROM countries WHERE country = New.country)
        INSERT INTO countries (country) VALUES (New.country)

Along with some other variations, and all I get are syntax errors (error #1064).

VB.Net DataGridView Filtering

I have a "DataGridView". And I want to make a filter system with 2 "ComboBox" and 1 "Button".

Column 1 - Column 2
Yes - True
No - Wrong

Let's say this is my table. And My first ComboBox is for "Column 1". When user choose "No" on "ComboBox1" I want to delete others (except no, we want no).

Can not unpin the object until it is saved on parse server using Android-Parse-SDK

I can not unpin my object from local database until it is saved on backend. I save object to local database then call object.saveEventually() like this

object.pinInBackground(new SaveCallback() {
                        @Override
                        public void done(ParseException e) {
                            if(e == null) {

                                object.saveEventually(new SaveCallback() {
                                    @Override
                                    public void done(ParseException e) {
                                        if(e == null) {
                                            Toast.makeText(AppContext.get(), "Object Saved On Parse", Toast.LENGTH_LONG).show();
                                        } else {
                                            Toast.makeText(AppContext.get(), "Object Not Saved On Parse", Toast.LENGTH_LONG).show();
                                        }
                                    }
                                });

                            }
                        }
                    });

if i want to unpin this object before internet connection back and object is saved on back-end what should i do. I tried this but it's not working:

object.unpinInBackground(new DeleteCallback() {
                            @Override
                            public void done(ParseException e) {
                                if(e == null) {
                                    Toast.makeText(getActivity(), getResources().getString(R.string.object_deleted),
                                            Toast.LENGTH_SHORT).show();
                                    updateObjectsList();
                                } else {
                                    Toast.makeText(getActivity(), getResources().getString(R.string.object_not_deleted),
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                        });

How i can cancel object.saveEventually()?

Insert to database without duplicate in php

How can I insert data to database without duplicate of the name for example if the name found in database show message how can do this??

<?php
$username ="root";
$password ="";
$hostname="localhost";
$db="a";
$dbhandle=mysql_connect($hostname ,$username ,$password,$db)or die('not connect to the database because:'.mysql_error());
 mysql_select_db($db,$dbhandle);
 $myusername=$_POST['user'];
$mypassword=$_POST['pass'];
$mypassword_conf=$_POST['Password_conff'];
if($mypassword==$mypassword_conf)
{
$sql="INSERT INTO aa( username, password,pass_con) VALUES 
('$myusername','$mypassword','$mypassword_conf')";
   if(! mysql_query($sql,$dbhandle))
      echo "not insert";
      else
         echo "insert is Done";

          mysql_close();

           }
else
{
    echo "not insert to db found error";
}

?>

Local database choice (Windows Phone 8.1 application)

I am in the process of making a relatively complex Windows Phone 8.1 application and I need a way to store data from server's database into a local database. Data from server is retrieved in JSON format via API. What are my options here? I've tried SQLite database controlled by sqlite-net but it lacks key features such as foreign keys support and 64bit support (?). What other choices do I have? Local database is used in order to give the user ability to work offline and later sync the data from local database with server's database.

Low Level Design for a notification System

We are building a notification system on an existing legacy stack of Codeigniter and MySQL. The case is like this : A notification is send to say 100K users. There are two tables in the DB

1) Messages ( Message ID, Phone ) 2) Status ( Phone, Message ID, Status )

When a message is sent there is single insert happening in messages table which holds phones in comma separated format. And when actually message starts sending ( say via some wrapper on google cloud messaging ) an insert happens in status table. Hence for a single notification to 100K users there can be 1 and 100K inserts respectively. The status table further receives updates from devices to change the status to say READ/ DELIVERED etc.

This doesn't look like a great architecture and would MySQL be able to handle that high volume of inserts ( say batched as well ). Any alternative low level design using the same tech stack or an alternate data store ( cassandra, elastic search ) should be an appropriate fit for this ?

Can't connect to database on notepad++

I can connect to my database just fine when I'm on my website, but when I'm on my notepad++, and I tried to connect to my database, I get the error below. I have XAMPP installed, and apache is working smoothly, but the only thing is that I can't connect to the database while in the notepad++, and yet it works when I'm on my website. All the files are copied from my website, so there is no discrepancy between the files on my website, and the files on my notepad++. I use localhost to get to the index of my page using notepad++, and it works fine. Only when I tried to register information to my database did the error below show up. Please help. Thanks.

Warning: mysql_connect(): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. in E:\xampp\htdocs\iscattered\register.php on line 3 Not connect :A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

<?php

$var = mysql_connect('mysql2.000webhost.com','username','password');

if(!$var){

die('Not connect :'  . mysql_error());

}

$database = mysql_select_db("database",$var);
if(!database){

die("Can't connect : " . mysql_error());

}

?>

Regular Expression "a{2}" not working

I have a record with emp_name = "Rajat" and it is not getting returned.

My query is -

select * from employees where emp_name regexp "a{2}"

Please explain why it is not working

create two foreign key from one table sql server

i am creating user table like code PK Table

CREATE TABLE TblUser (UserId int identity primary key ,Name varchar(20))

AND creating one more table FK Table

CREATE TABLE TblAnnouncements (Id int identity primary key ,Announcements 
varchar(20),CreatedBy INT FOREIGN KEY REFERENCES TblUser (USERID)  ON  DELETE  
CASCADE, UpdatedBy INT FOREIGN KEY REFERENCES TblUser (USERID)  ON DELETE  SET NULL)

i am getting this error

Msg 1785, Level 16, State 0, Line 1
Introducing FOREIGN KEY constraint 'FK__TblAnnoun__Updat__60A75C0F' on table 'TblAnnouncements' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

how to maintain createdby and updatedby in an table....

can you give suggest me any other way to do that ?

thank u.

Execute complex SQL queries in VB.NET

I'm having trouble executing a complex SQL query in VB.NET using OledbDataAdapter. This SQl query works fine in the W3school's SQL Tryit Editor. Following is my existing VB.NET code and is there any way to execute that kind of a SQL query directly in VB.NET or can anyone change this query to work with VB.NET with same results?.

    Dim con As New OleDb.OleDbConnection
    Dim dbProvider As String
    Dim dbSource As String
    Dim ds As New DataSet
    Dim da As OleDb.OleDbDataAdapter
    Dim sql As String

    dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
    dbSource = "Data Source = C:\database.mdb"
    con.ConnectionString = dbProvider & dbSource
    con.Open()
    sql = "With query1 as (SELECT Val,DateAndTime FROM [FloatTable] where TagIndex='0'),Query2 as (SELECT Val,DateAndTime FROM [FloatTable] where TagIndex='1')select query1.val as 'TT348',Query2.val as 'TT358',Query2.DateAndTime as 'DateAndTime' From query1,Query2 where query1.DateAndTime=Query2.DateAndTime"
    da = New OleDb.OleDbDataAdapter(sql, con)

    da.Fill(ds, "Log")
    con.Close()

    DataGridView1.DataSource = ds

When I run this code snippet it gives an error telling

Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.

Greatly appreciate any help and thank you...

Writes to database seem to have no effect

I am working with an ASP.NET web application written in C# deployed to IIS/Windows Server 2008 R2. The application uses NHibernate to interact with an Oracle database running on a networked unix server.

It seems that writes being made by the application to the database have no effect.

If I manually edit the value of a record in the Oracle database, the new value is reflected by the application. However, if I attempt to change a value using the application’s custom “save” functionality, the changes are not reflected in the database. It seems like reads are succeeding, but writes are failing.

Why do writes seem to be failing?

More information:

No obvious error messages are received (ie. the application does not throw an exception and it seems to continue running as if everything is fine).

Another instance of this application is running on IIS/Windows Server 2003. This instance can write to the Oracle database (ie. the changes can immediately be seen in the database by using a database viewer after clicking “save”).

The code is virtually identical between the 2003/2008 applications. However, on the 2008 server, I am using newer versions of Oracle libraries and I changed to target architecture of the visual studio projects from ‘Any CPU’ to ‘x86’ (the 2008 server is 64-bit while the 2003 server is 32-bit).

Disclaimer:

I have very limited experience working with IIS, NHibernate, Oracle databases, Windows Server 2003, and Windows Server 2008 R2. I do, however, have slightly more experience working with C#, ASP.NET web applications, Visual Studio, and MSSQL databases).

Phalcon data migrations separated from schema migrations

Using Phalcon framework and its migrations system, for testing purposes, I need to be able to execute the schema migrations separately from the data migrations.

What I want to do is to have a separate data migrations folder, so on my testing environment I would apply only the schema migrations (for testing purposes, tables should be empty and only populated by fixtures), but on my staging and production environments the data migrations would be applied as soon as the schema migrations are done.

I don't find a way to have two separated sets of migrations in Phalcon. How can I do it?

Choosing the right database index type

I have a very simple Mongo database for a personal nodejs project. It's basically just records of registered users.

My most important field is an alpha-numeric string (let's call it user_id and assume it can't be only numeric) of about differing from about 15 to 20 characters.

Now the most important operation is checking if the user exists at or all not. I do this by querying db.collection.find("user_id": "testuser-123"

if no record returns, I save the user along with some other not so important data like first name, last and signup date.

Now I obviously want to make user_id an index. I read the Indexing Tutorials on the official MongoDB Manual.

First I tried setting a text index because I thought that would fit the alpha-numeric field. I also tried setting language:none. But it turned out that my query returned in ~12ms instead of 6ms without indexing.

Then I tried just setting an ordered index like {user_id: 1}, but I haven't seen any difference.

Can anyone recommend me the best type of index for this case or quickest query to check if the user exists? Or maybe is MongoDB not the best match for this?

Weird 'returned data that does not match expected data length for column' error while the expected length is much bigger - SQL SERVER 2012

In my project I am rebuilding my Access database to an SQL Database. So to do this I am transferring the Access DATA to the SQL Database. I made sure they both have the same structure and the Access fields are modified correctly in the SQL database.

For most of the data this works. Except for 1 table. This table gives me the following weird error message:

OLE DB provider 'Microsoft.ACE.OLEDB.12.0' for linked server 'OPS_JMD_UPDATE' returned data that does not match expected data length for column '[OPS_JMD_UPDATE]...[OrderStatus].Omschrijving'. The (maximum) expected data length is 100, while the returned data length is 21.

So here some more information about both the Access and SQL field/column:

  • Access type: Short text
  • SQL type: nvarchar(MAX)
  • Access column data in it: Normal letters and & - % é + . , : being the 'not normal ones'.
  • A few empty Access records (which is allowed)
  • A total of 135314 record in the Access table

Iv'e set the SQL datatype to nvarchar(MAX) so that the field can never be to small, this didn't seem to help though..

*The OPS_JMD_UPDATE is the linked Access database

What causes this problem? Is it because some characters aren't allowed or..?

AngularJS: Display only first row on ng-repeat not first index

I have two dynamic dropdowns that display a list of data from the database, and refreshes the list on every 'branch' change:

<select id="regions" class="form-control" ng-model="formData.location" required ng-options="rg as rg.type for rg in region">
    <option value="">Choose Location</option>
</select>

<select id="branches" class="form-control" ng-model="formData.branches" required ng-options="c as c[formData.location.displayName] for c in formData.location.data | orderBy:'branch'">
    <option value="">Choose Branch</option>
</select>

displaying by ng-repeat:

<div ng-repeat="codes in response">
  <span ng-if="((codes.branch == formData.branches.alias) && (codes.taken == 0))">
  {{codes.code}}
</div>

I am trying to limit the display of each to just one using limitTo:1. The problem is, this filter only displays the first row from the table. Is there a filter that displays the first child of the displayed list, instead of the first index of the entire list from the database?

Note that the list refreshes a new list from the database each time the branch dropdown switch values.

how can i update a value in record when the date/time match the date/time stored in the record itself

I have the following table

my_table

date | time | status

now my first question is: i need to change a status column from zero to one when the date and time match the date and time of the record which is specified by the user when he/she inserted the record.

second question: when user choose date and time he/she will choose it depends on their time zone so how this will effect if the PHPMyAdmin use different time zone ?

When i send data from a form to access database the first item always replace the first line in database

When i send data from a form to access database the first item always replace the first line in database and as a result when i run the form again it replaces the first item and i loose that data. My code:

this.asfalistratableBindingSource.EndEdit();
this.asfalistratableTableAdapter.Update(this.asfalistradbDataSet.asfalistratable);
this.asfalistratableBindingSource.AddNew();

Rails with Stripe Checkout: How can i seed my db with sample charges and use stripe checkout to generate tokens for each charge?

So I have a rails app that takes donations for a fund raising project using stripe checkout. I save the stripetokens to my db, and then go back and process them all at once if the project funding goal is met (sorta like kickstarter). I've figured out how to do this and have tested my code on a small number of charges (say like 10) without any problems. Here's my code

@project = Project.find(set_project)

# Create new stripe customer
    @customer = Stripe::Customer.create(
        :email => params[:stripeEmail],
        :card => params[:stripeToken]
        )

# Create new charge
    @charge = Charge.new(
        :email => params[:stripeEmail],
        :stripe_token => params[:stripeToken],
        :project_id => @project.id,
        :amount => params[:amount],
        :customer_id => @customer.id
        )
#Save charge to my db
@charge.save

Then in my project model

# Cycle through all charges for project and process using 
# stripe token and stripe customer id
def charge
    self.charges.each do |x|
        begin
            Stripe::Charge.create(
                :amount => x.amount,
                :currency => 'usd',
                :customer => x.customer_id
            )
        rescue Stripe::CardError => e
            x.error = e
        else
            x.processed = true
            x.save
        end
    end
end

Now here's my question. I want to be able to test this code at higher volumes of charges. How can I seed my db with 1,000 or more sample charges and use the stripe checkout script to create a customer and generate tokens for each one?

Exception during connecting to postgresql database using wt c++ library?

I`m trying to connect to postgresql database which name is "galaxydatabase" and I encountered an unhandled exception. Source code:

#include <Wt/Dbo/Dbo>
#include <Wt/Dbo/backend/Postgres>

namespace dbo = Wt::Dbo;

void run()
{
    dbo::backend::Postgres po;
    po.connect("galaxydatabase");
    // or
    //dbo::backend::Postgres po("galaxydatabase"); // the same exception???
}

int main(int argc, char **argv)
{
    run();
}

Password to the database is "dbpass". I don`t know where put this password in the code?

Duplicate entry for key "PRIMARY" in MySQL

Query for creating table :

create table if not exists person ( 
roll_no int(4) AUTO_INCREMENT primary key,
name varchar(25),  
city varchar(25));

Query to set start number for auto-increment primary key :

alter table person auto_increment = 1;

Query to insert data :

insert into person (name,city) values("Maxwell", "Pune");
insert into person (name,city) values("Baldwin", "Bengaluru");
insert into person (name,city) values("Novartis", "Paris");
insert into person (name,city) values("Shaun", "Mumbai");
insert into person (name,city) values("Beckham", "Toronto");
insert into person (name,city) values("Ashish", "Bengaluru");
insert into person (name,city) values("David", "Paris");
insert into person (name,city) values("PK", "London");
insert into person (name,city) values("Chris", "Bengaluru");
insert into person (name,city) values("Aston", "Mumbai");

Query to delete the row :

delete from person where roll_no=5;

Table structure after deleting the row:

roll_no      name       city
1            Maxwell    Pune
2            Baldwin    Bengaluru
3            Novartis   Paris
4            Shaun      Mumbai
6            Ashish     Bengaluru
7            David      Paris
8            PK         London
9            Chris      Bengaluru
10           Aston      Mumbai

Now, while looking to reinstate the deleted row, the compiler is throwing error as " Duplicate entry '5' for key 'PRIMARY' "

Query used to re-instate the deleted row.

update person set roll_no = roll_no + 1 where roll_no >=4 order by roll_no desc;
insert into person (roll_no, name, city) VALUES (5, "Beckham", "Toronto");

What could be the possible reason for this issue ? Any inputs would be highly recommended.

Sqlite Table Create Syntax Error

I am just trying to get text from a JtextField and I want to implement it inside a sql injection to create a table. Here is my code: try { Class.forName("org.sqlite.JDBC"); conni = DriverManager.getConnection("jdbc:sqlite://C://Users//Asus//Dropbox//Admin.sqlite");

                  stmt = conni.createStatement();


                  String sql =  "CREATE TABLE" + projectname.getText() + 
                               "(ID INT PRIMARY KEY     NOT NULL,"  + 
                               " NAME           TEXT    NOT NULL, " +
                               " EstQuantity            INT     NOT NULL, " +
                               " UnitPrice        CHAR(50), " +
                               " TotalPrice         REAL)"; 

                  stmt.executeUpdate(sql);
                  stmt.close();
                  conni.close();
                } catch ( Exception e ) {
                  System.err.println( e.getClass().getName() + ": " + e.getMessage() );
                  System.exit(0);
                }
                JOptionPane.showMessageDialog(null, "Project Created!");

This is the basic structure. When I input my table name it says java.sql.SQLException: near "(my input)CREATE": syntax error Please help!

I'am getting error

NoMethodError in Data#input

Showing /home/adijanuarsyah/Projects/Food/app/views/data/_idfood.html.erb

where line #8 raised:

undefined method `find' for #<TopFood:0x007fdfd558fa90>

When i'am used find method for getting query food = foods.find(rand_number) i'am getting error like above , but when using TopFood.find(rand_number), its working perfectly.

Here is my view

<h2>Suggestion Indonesian top dishes</h2>
<ul id="foodList">

        <% TopFood.where(:country => "ind").find_each do |foods |  %> 
        <% rand_number = rand(52) + 1 %> 
            <% @food = foods.find(rand_number)%>
                <li><%= @food.name  %></li> 
            <% puts @food.inspect %> 
    <% end %>

</ul>
<div id="loadMore">More sugesstions</div>
<div id="showLess">Show less</div>

Any clue as to what is going on here?

Thanks.

Cannot add foreign key constraint 2

im try create a foreign key to Poblacion, on table cp_cliente, but i cant, i take the error "cannot add foreign key", im try change the name, but i cant. If i delete Poblacion foreign key the script work fine.

CREATE TABLE provincias (

Cod_provincia INT(2) PRIMARY KEY,

Provincia VARCHAR(50) NOT NULL );

CREATE TABLE cp_cliente (

CP CHAR(5),

Cod_provincia INT(2),

Poblacion VARCHAR(70),

PRIMARY KEY (CP, Poblacion, Cod_provincia),

FOREIGN KEY (Cod_provincia) REFERENCES provincias(Cod_provincia) ON DELETE CASCADE ON UPDATE CASCADE );

CREATE TABLE cliente (

DNI CHAR(9) PRIMARY KEY,

Nombre VARCHAR(20) NOT NULL,

Apellidos VARCHAR(20) NOT NULL,

Direccion VARCHAR(50) NOT NULL,

CP CHAR(5),

Cod_provincia INT(2),

Poblacion VARCHAR(70),

FOREIGN KEY (CP) REFERENCES cp_cliente(CP) ON DELETE SET NULL ON UPDATE CASCADE,

FOREIGN KEY (Cod_provincia) REFERENCES cp_cliente(Cod_provincia) ON DELETE SET NULL ON UPDATE CASCADE,

FOREIGN KEY (Poblacion) REFERENCES cp_cliente(Poblacion) ON DELETE SET NULL ON UPDATE CASCADE );

What is the problem? I can't see him :(

Sorry my bad english.

How sql with-recursive statement interpreted?

My sources : Hello there.

I would like to ask get some help about understanding how "with recursive" works. More precisely WHY the anchor query (the non-recursive term) isn't replicated into the sub call of the CTE. I tried my best to understand alone but i'm not sure.

First of all let's take the example of PostgreSQL which is the simpliest one i found (make the sum of 1 to 100) :

WITH RECURSIVE t(n) AS (
      VALUES (1)
      UNION ALL
        SELECT n+1 FROM t WHERE n < 100)

    SELECT sum(n) FROM t;

My Code walkthrough ( I used links below) :

" 1. Evaluate the non-recursive term. For UNION [...]. Include all remaining rows in the result of the recursive query, and also place them in a temporary working table.

  1. So long as the working table is not empty, repeat these steps:

    • Evaluate the recursive term, substituting the current contents of the working table for the recursive self-reference. For UNION [...]. Include all remaining rows in the result of the recursive query, and also place them in a temporary intermediate table.

    • Replace the contents of the working table with the contents of the intermediate table, then empty the intermediate table."

LVL 0 :

  1. non-recursive part

    • CTE : (N) 1
    • WORKING TABLE : (N) 1
  2. recursive part

    • CTE : (N) 1
    • WORKING TABLE : (N) 1
    • INTERMEDIATE TABLE (N) 2

(this is the part i mess around i think) - subsitution of WORKING TABLE

so the recursive t will use WORKING TABLE to do SELECT n+1 and put the result in INTERMEDIATE TABLE.

  1. UNION ALL

    • CTE : (N) 1 2
    • WORKING TABLE : (N) 2
    • INTERMEDIATE TABLE : CLEANED

      1. Then we go into the next lvl by the call of t right? (because END condition WHERE n < 100 = FALSE)

LVL 1 :

We know coz postgreSQL says it "So long as the working table is not empty, repeat the recursive steps" So it will repeat the step 2. and 3. (if i'm correct) until END condition then do the SUM.

BUT if I just walkthrough the call of the next lvl of t should we not do VALUES(1) first ?

I'm really confused about how it is possible.

Best regards, Falt4rm

SQL Query Multiple Tables

I have 5 tables,

Machines(ID, Name),

Engineers(ID, Name),

Parts(ID, Name),

Faults(ID, MachineID, EngineerID, Description, Date),

FaultParts(FaultID, PartID)

Key = Primary (bold), Foreign Key (italic), Composite (italic & bold)

A fault can require more than one part to fix it

I am trying to query the database so that I can retrieve the the engineer name, machine name, fault description, and parts requires to fix.

I am unsure how I should go about doing this efficiently or if may tables should be set up as they are.

Any help would be greatly appreciated, thanks.

How can I connect Jboss Fuse to a database?

I would like to directly connect a database to Fuse. My goal is to save all messages received by one or more topics inside a database (MySQL, postgreSQL, MongoDB,...).

I don't need a failover database, basically I would "subscribe" a database to Topics and save all messages for future analysis.

What's the easiest way to do it?

Multiple Junction Tables Between Same Entities

I'm planning a database schema, and I've encountered a situation where I don't know the best way to proceed. I'm really looking for a list of pros and cons to each of my proposed solutions, perhaps followed by a recommendation for which would conform to best databasing practice.

So, the problem is that I have two entities with multiple many-to-many relationships between them. The two tables are Teams and People; a Team is composed of many People, and a Person could have one or many roles on the Team. Roles include team leader, team member, team follower, etc. A person may have more than one role for a particular team, but ideally a subset of these roles are mutually exclusive, while the rest are not.

Here are the solutions I've considered:

1) Create a separate junction table for each role. The presence of a row in each table signifies that a single person belongs to a single team, and the particular table indicates the person's role on the team. Mutually exclusive roles would have to be enforced at the application level.

2) Create a single junction table and store an enumeration on that table to specify which role a person has. A given person-team combo may have multiple rows in this table, one for each role that the person has with the team. Mutual exclusivity of certain roles would have to be enforced on the application level.

3) Create a single junction table, and store a list of boolean flags on the table, one for each role. Each person-team combo has a single row in the table, and the flags determine which roles the user has on that team. Mutual exclusivity could be enforced at the database level, because all mutually exclusive roles could share a single enumerated field on the table.

4) Create two junction tables. This is sort of a combination of (2) and (1) that allows mutual exclusivity to be enforced at the database level. There would be one junction table with an enumeration for mutually exclusive roles, and the other junction table (with enumeration) would handle all non-exclusive roles.

Is there anything I'm forgetting? Which option seems the most natural?

Thanks

Connect to database from another server with PHP

is it possible to connect to another server's database with php? Like I have Website A thats got Database A and on this website I want to load something from a Database B of Website B. Of course I got the connection data!

Condition when BCNF and 3NF are equivalent

Statement - "If a table contains only one candidate key, the 3NF and the BCNF are equivalent."
In the below image, relation is 3nf but not bcnf. But it has only one candidate key ie AB, so according to above statement it should be either both (3nf, bcnf) or nothing. Can somebody explain what i am missing here ? enter image description here

Android: Expandable Listview - Load Child content from remote database

I have an ExpandableListView with Group headers which wont change. Now I want to bind children of the group with different data from remote database such as MySQL or MSSQL. I have already done this for normal ListView using JSON, I have no idea how to implement it for ExapandableListView.

Please help.

Thanks

Which database type is better for around 10 million data, windows or linux

i have around 10 millions of record for my website.i will create a search on my website for my recoreds. which database is comparetively faster linux or windows

Can a button on static html file fire database queries and fetch the results in real time ? [Automation History]

I have a database(mySQL) having the count of daily run results from the automation suite. The results are inserted into the db when the automation suite run is over (@AfterSuite). However, i need to find a way to fetch the results for any particular day and display these from today's run file ( index.html). This index.html is a static html file that shows the daily results- pass, fail , duration ect. I am not sure if a button on the index.html can fire db queries and get the results for any particular day . The automation framework uses Java with TestNG. Please let me know if i am missing something.

MySQL database relationship without an ID

Hi StackOverflow community,

I have these two tables:

tbl_users

  • ID_user (PRIMARY KEY)
  • Username (UNIQUE)
  • Password
  • ...

tbl_posts

  • ID_post (PRIMARY KEY)
  • Owner (UNIQUE)
  • Description
  • ...

Why always everybody make database relationships with foreign keys? What about if I want to relate Username with Owner instead of doing ID_user with ID_user in both tables?

Username is UNIQUE and the Owner is the username of the creator of the post.

Can it be done like that? There is something to correct or make better? Maybe I have a misconception.

I would appreciate detailed and understandable answers.

Thank you in advance.

Inserting data from a form to multiple tables in a mysql database using php

The data inserts into the first table, but the code for getting the ID numbers doesn't seem to work, and the data is not inserted into the next two tables. The code runs and the Thank you message appears thanking the person for submitting their details.

There are three pages of code. The connect code is in one file. The processing code file and the form file.

I won't include the connect code here, because it works.

Here is the form code:

enter code here

    <form method="post" action="formprocess3.php">
    <table>
            <tr>
          <td>Customer Details</td>
          <td>Appointment Preference</td>
          <td>Cupcake Details</td>
    </tr>
    <tr>
      <td>First Name             
      <input name="FirstName" type="text" id="FirstName" maxlength="20" value="<?php if (isset($_POST['FirstName'])) echo $_POST ['FirstName']; ?>"/>
               </td>
      <td>Appointment Date            
              <input name="AppointmentDate" type="date"  id="AppointmentDate" maxlength="10" value="<?php if (isset($_POST['AppointmentDate'])) echo $_POST['AppointmentDate']; ?>"/>
            </td>
           <td>Size     
    <select name="CupcakeSize" id="CupcakeSize" type="radio" maxlength="5" value="<?php if (isset($_POST['CupcakeSize'])) echo $_POST['CupcakeSize']; ?>"/>
            <option></option>
            <option>Small</option>
            <option>Large</option>
            </select></td>
      </tr>
      <tr>
        <td>Surname
             <input name="Surname" type="text"  id="Surname"  maxlength="20" value="<?php if (isset($_POST['Surame'])) echo $_POST['Surname']; ?>"/></td>
          <td>Appointment Time
         <select name="AppointmentTime" type="radio" maxlength="20" value="<?php if (isset($_POST['AppointmentTime'])) echo $_POST ['AppointmentTime']; ?>"/>

              <option></option>
              <option>9.30am -10.30am</option>
              <option>11am - 12pm</option>
              <option>1.30pm - 2.30pm</option>
              <option>3pm - 4pm</option>
              <option>4.30pm - 5.30pm</option>
              <option>7pm - 8pm</option>
            </select>
          </td>
          <td>Quantity             
          <input type="text" name="Quantity" id="Quantity"/></td>
            </tr>
        <tr>
          <td>Email address 
          <input name="EmailAddress" type="email"  id="Email" maxlength="20" value="<?php if (isset($_POST['EmailAddress'])) echo $_POST['EmailAddress']; ?>"/></td>
          <td>Taster 

            <input name="Taster" type="checkbox" id="Taster"/>
             </td>
            <td maxlength="1" type="radio" value="<?php if (isset($_POST['Taster'])) echo $_POST['Taster']; ?>"/>
                     <td>Frosting           
        <select name="CupcakeFrosting" id="CupcakeFrosting" type="radio" maxlength="10" value="<?php if (isset($_POST['CupcakeFrosting'])) echo $_POST['CupcakeFrosting']; ?>"/>
            <option></option>
            <option>Strawberry</option>
            <option>Chocolate</option>
            <option>Vanilla</option>
            <option>Coffee</option>
            <option>Orange</option>
            <option>Blue</option>
            <option>Pink</option>
            <option>Green</option>
            <option>Red</option>
            <option>Purple</option>
            </select></td>
                 </tr>
              <tr>
            <td>Postcode            
          <input name="Postcode" type="text" id="Postcode" style="width: 130px; height: 20px" class="auto-style24" maxlength="10" value="<?php if (isset($_POST['Postcode'])) echo $_POST['Postcode']; ?>"/></td>
      <td>Cake wanted by
      <input name="CakeWantedBy" type="date" id="CakeWantedBy" maxlength="10" value="<?php if (isset($_POST['CakeWantedBy'])) echo $_POST['CakeWantedBy']; ?>"/>
              </td>
          <td>
            <select name="CupcakeFlavour" id="Flavour" type="radio" maxlength="10" value="<?php if (isset($_POST['CupcakeFlavour'])) echo $_POST['CupcakeFlavour']; ?>"/>
            <option></option>
            <option>Banana</option>
            <option>Caramel</option>
            <option>Carrot</option>
            <option>Chocolate</option>
            <option>Vanilla</option>
            <option>Red Velvet</option>
            <option>Oreo</option>
            <option>Coffee</option>
            <option>Decide with taster £20</option>
            </select></td>
            </tr>
        <tr>
            <td>
            <input name="MobileNumber" type="text" id="MobileNumber" maxlength="20" value="<?php if (isset($_POST['MobileNumber'])) echo $_POST['MobileNumber']; ?>"/>          
                            </td>
                             <td>
            <span class="auto-style24">Occasion 
            <select name="Occasion" type="radio" id="Occasion" maxlength="20" value="<?php if (isset($_POST['Occassion'])) echo $_POST['Occassion']; ?>"/>
            <option></option>
            <option>New baby</option>
            <option>Birthday</option>
            <option>Wedding</option>
            <option>New Job</option>
            <option>Christmas</option>
            <option>Easter</option>
            <option>Valentines</option>
            <option>Congratulations</option>
            <option>Anniversary</option>
            <option>Other</option>
            </select></td>
      </tr>
    </table>
    </form>

The code for inserting the form data into the three database tables:

<html>
<head>
<title>Form Process Message</title>
</head><body>
<?php # 

// This script performs an INSERT query to add a record to the users table.


 if ($_SERVER['REQUEST_METHOD'] == 'POST') {

 // open the database...

 require ('mysqli_connect.php'); 

 // Make the query:

// Customer details

 $t = $_POST[Title];
 $fn = $_POST[FirstName];
 $sn = $_POST[Surname];
 $e = $_POST[EmailAddress];
 $ht = $_POST[HomeTelephone];
 $mn = $_POST[MobileNumber];
 $hn = $_POST[HouseNumberName];
 $s = $_POST[Street];
 $tw = $_POST[Town];
 $c = $_POST[County];
 $pc = $_POST[Postcode];

 // Cake details
 $ct = $POST[CupcakeType];
 $cn = $_POST[CupcakeNumber];
 $cf = $_POST[CupcakeFrosting];
 $o = $_POST[Occassion];

 // Preferred Appointment
 $ad = $_POST[AppointmentDate];
 $at = $_POST[AppointmentTime];
 $ta = $_POST[Taster];
 $cwb = $_POST[CakeWantedBy];

 $q = "INSERT INTO customerdetails(Title, FirstName, Surname, EmailAddress,   HomeTelephone, MobileNumber, HouseNumberName, Street, Town, County, Postcode) VALUES ('$t','$fn', '$sn', '$e', '$ht', '$mn', '$hn', '$s', '$tw', '$c', '$pc')";

 //execute query        
 $r = @mysqli_query ($dbc, $q); 

 //get customer id for preferred appointment 
$ci = my_sqli_insert_id($dbc);

 $q1 = "INSERT INTO cakedetail(CupcakeType, CupcakeNumber, CupcakeFrosting, Occassion) VALUES ('$ct','$cn', '$cf', '$o')";

//execute query
$r1 = @mysqli_query ($dbc, $q1);

//get cakedetail id for preferred appointment
$cdi = my_sqli_insert_id($dbc);

$q2 = "INSERT INTO preferredappointment(AppointmentDate, AppoitmentTime, Taster, CakeWantedBy, EmailAddress) VALUES ($ci, $cdi, '$ad','$at', '$ta', '$cwb', '$e')";

//execute query 
$r2 = @mysqli_query ($dbc, $q2);  

// Run the query.

if ($r) { 

// If it ran OK.
// Print a message:


echo '<h1>Thank you!

<br />
Your request is now registered.
<br />  
<a href="gallery.html">Back to the Gallery page</a></h1>';      
        }       
 else { 

// If it did not run OK.
// Public message:  

 echo '<h1>System Error</h1>

 <p class="error">You could not be registered due to a system error. We apologise for any inconvenience.</p>

 <a href="gallery.html">Back to the Gallery page</a>';      
 // Debugging message:

 echo '<p>' . mysqli_error($dbc) . '<br /><br />
 Query: ' . $q . '</p>';

    } 
 //close the dbc        
 mysqli_close($dbc); 
}

  ?>
  </body>
  </html>

There are three database tables called cakeorder, customerdetails and preferred appointment. I don't think the multiple table insert works with earlier versions PHP, which is what I was using to start with, but I am now using xampp 5.5.24 and PHP 5.5.24. I stripped out most the formatting of the html, so I may have left a hanging tag somewhere here, but there isn't one on the actual web page. I am not very proficient in PHP, so a lot of this is put together from looking through this website. Any help would be gratefully received. Thank you

Changing connection string dynamically on runtime in WinForms

I am making Winform dekstop application. I am giving an option in my application that user can select database or set database path. when user select database or database path then connection string should be changed on runtime. I cannot take risk to save database in SQLEXPRESS root directory because when user's windows crash then all data in database will be deleted. So database will be store in other directory and from application setting user will give path of database and connection string should be changed according to that path at runtime. please help. Thanks in Advance.

query handling on no connection to database

suppose we have a condition in which we have many clients are running the same windows application and using the same database but net connectivity is not good in that region so it wont be able to access the database server all the time .can we store SQL queries during this time and then execute them later ?? and also how we will maintain data consistency for all the clients in this situation

Need Context aware movie datset

I need a context aware movie dataset other than CoMoDa. Need datset which consist of context like location, mood, time , age ,etc etc.

What database to use to store action log?

I am building a game and want to store log of all actions in the game.

Requirements:

  1. Each time action is taken it is appended to the log immediately
  2. No queries are made on the logs. Only the whole log is retrieved when the game is loaded.
  3. No data loss. Actions must never roll back

So, the most obvious way is to store the log in filesystem without any database. But when it comes to PaaS such as Heroku the filesystem is not a good way to operate there. So I need some simple datastore which acts as filesystem.

Problems when images need to upload

Good Day to all

I have a problem with my php and mysql. Everything worked fine till I added new things to my database and now my images give me errors when I click on create.

Below is the errors I am getting:

Notice: Undefined variable: conn in C:\wamp\www\SA-Property Finder\create.php on line 140

Fatal error: Call to a member function lastInsertId() on a non-object in C:\wamp\www\SA-Property Finder\create.php on line 140

And here is my code:

//START IMAGES

        // insert data
        if ($valid) {
            $pdo = Database::connect();


            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql = "INSERT INTO properties (title,description,area,map,status,type,bedrooms,bathrooms,parking,garage,garden,pool,price,pets,agentnum,agentemail) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $q = $pdo->prepare($sql);
            $q->execute(array($title,$description,$area,$map,$status,$type,$bedrooms,$bathrooms,$parking,$garage,$garden,$pool,$price,$pets,$agentnum,$agentemail));
            Database::disconnect();

        }
       **$last_id = $pdo->lastInsertId();**
       $directory="uploads/";
       $directoryagents="agents/";
$a=0;

foreach ($_FILES['agentfile']['name'] as $nameFile) {
            $ext = pathinfo($nameFile, PATHINFO_EXTENSION);

            if(is_uploaded_file($_FILES['agentfile']['tmp_name'][$a]))
            {
                move_uploaded_file($_FILES['agentfile']['tmp_name'][$a], $directoryagents.$last_id."_".$a.".".$ext);
            }
            $fileandpath = $directoryagents.$last_id."_".$a.".".$ext;

            $pdo1 = Database::connect();
            $pdo1->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql1 = "UPDATE properties SET agentimageurl=? WHERE PropertyId=?";
            $q1 = $pdo1->prepare($sql1);
            $q1->execute(array($fileandpath,$last_id));
            Database::disconnect();
        }


foreach ($_FILES['file']['name'] as $nameFile) {


        $ext = pathinfo($nameFile, PATHINFO_EXTENSION);
            if(is_uploaded_file($_FILES['file']['tmp_name'][$a]))
            {
                move_uploaded_file($_FILES['file']['tmp_name'][$a], $directory.$last_id."_".$a.".".$ext);
            }
            $fileandpath = $directory.$last_id."_".$a.".".$ext;

            $pdo1 = Database::connect();
            $pdo1->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql1 = "INSERT INTO images (propertyid,imageurl) values(?, ?)";
            $q1 = $pdo1->prepare($sql1);
            $q1->execute(array( $last_id,$fileandpath));
            Database::disconnect();
            $a++;

        }
          header("Location: admin_list.php");
      }

This is line 140:

   $last_id = $pdo->lastInsertId();

I just don't understand it worked fine, can't seem to see where my problem is.

Is the relation in 3NF?

R(ABCD) with FD's

AB -> CD BC -> D

I found this question in a book and it says the relation is in 2nf but not in 3nf.

I cant find any trivial dependencies and also no non prime attribute is functionally dependent on another non prime attribute then how come the relation is not in 3nf?

Should i consider BC as a non prime attribute too? Please help me understand the concept of 3NF

Test Driven Development applied to Database

Well i have this code:

which is a simple database able to insert, delete and modify Contactos. I need to make this class using Test Driven Development

i have began this way....

and function insertarContacto ( addContacto).

Using Eclipse the TestConnection works but testInsertarContacto doesn't.

Dont know if im beginning the right way an any hint or help would be apreciated. Also i have doubts if in testBaseDatosContactos i have to clean the database at beginning or end of tests or how to procceed...

Superkeys of this relation

I am trying to find the superkeys of this relation, but I am having troubles finding out how many superkeys there are and exactly what they are. I figured out that the candidate keys were {A},{B},{C},{D}.

Here is the relation:

R(A,B,C,D)

Functional Dependencies: 

A->B
B->C
C->D
D->A

Candidate keys: {A},{B},{C},{D} (from what I figured out)

Can someone please help me find the superkeys, and how exactly to find them?

Connect to Multiple Databases for Interlinked Applications in Laravel 4

I took on this project which i want to create using Laravel 4 The requirement involves different applications using different databases but each of the applications uses the same user.

Each database can contain tables relevant to it's specific application and the next db can contain other other tables for other projects.

Thanks guys hope you can give me some advice.

vendredi 8 mai 2015

How to create a relationship between two tables that allows duplicates?

I am writing an mvc .net application to learn. I have a table for cards and one for decks. I want to make a "deck" able to have cards added to it. I can do this as a one to one.

I assume I need a third table or a join of some sort.

What I need to be able to do is add duplicates of cards to the deck. Essentially the cards library would only list a card once, but a deck could have 3 of a specific card in it. Also, a card should be allowed to be listed in multiple decks. If you are familiar with MTG cards this will probably make more sense.

Sorry if this is a beginner question. Any assistance would be greatly appreciated. :)

Php pdo POST add data to database with function PDO

I am trying to insert some datas in DB with the following function (I don't get any errors but datas don't get added in my DB)

File name=insertuserdb:

<?php
  function insertUser($U,$P,$E)
   {
    $conn = connPDO();//*function to connect to my DB on the other file
    $query = ("INSERT INTO user (Username, Password, Email) VALUES     (:User,:Pass,:Email)");
    $conn_prepare = $conn->prepare($query);
    $conn_prepare->execute(array( "User" => $U,"Pass" => $P,"Email" =>$E ));
    $id = $conn->lastInsertId();
    $conn_prepare->closeCursor();
    return $id;
 }
?>

AND (my connection function (works/sorry for french)) file name=dbc3.php:

   <?php

     function connPDO()
     {
$PARAM_hote='localhost'; // le chemin vers le serveur
$PARAM_port='';
$PARAM_nom_bd='mygcpage'; // le nom de votre base de données
$PARAM_utilisateur='root'; // nom d'utilisateur pour se connecter
$PARAM_mot_passe=''; // mot de passe de l'utilisateur pour se connecter
try {
    $connexion = new    PDO('mysql:host='.$PARAM_hote.';port='.$PARAM_port.';dbname='.$PARAM_nom_bd, $PARAM_utilisateur, $PARAM_mot_passe);
    return $connexion;
}
catch(Exception $e) {
    echo 'Erreur : '.$e->getMessage().'<br />';
    echo 'N° : '.$e->getCode();
    die;
}

} $conn = connPDO(); if ($conn) { echo "connected"; } else { echo "ERROR: Could not connect!"; } ?>

finally (my form) file name=login.php:

<form method="POST" action="login.php">
                    <table id="reg">
                    <th>Please the fill in the following:</th>
                        <tr><!--Username -->
                            <td>
                                <p>Username:</p>
                            </td>
                            <td>
                                <input type="text" name="username" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <p>Password:</p>
                            </td>
                            <td>
                                <input type="password" name="pass1" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <p>Comfirm Password:</p>
                            </td>
                            <td>
                                <input type="password" name="pass2" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <p>Email:</p>
                            </td>
                            <td>
                                <input type="text" name="email" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input type="submit" name="register" />
                            </td>
                            <td></td>
                        </tr>
                    </table>
                </form>

Android Save Button Not Saving into database

I have a Save button in my app and it doesn't seem to be saving what it should.

This is the function that the button calls: public void newsave (View rootView) { final Dbhandler dbHandler = new Dbhandler(this.getActivity()); //, null, null, 1);

              //  if (result2.getText().toString()=="") {
                //    Toast.makeText(getActivity(), "There is nothing to Save",     Toast.LENGTH_SHORT).show();
                //}
                //else {
                        final String distance = (result2.getText().toString());


    AlertDialog.Builder builder = new             AlertDialog.Builder(this.getActivity());
                    builder.setTitle("Description");
                    final AlertDialog dialog =builder.create();



                        // Set up the input
                        final EditText input = new EditText(this.getActivity());
                        input.setOnFocusChangeListener(new 
View.OnFocusChangeListener() {
                        @Override
                        public void onFocusChange(View v, boolean hasFocus) {
                            if (hasFocus) {
                                dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                            }
                        }
                    });
                        // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
                        input.setInputType(InputType.TYPE_CLASS_TEXT);
                        builder.setView(input);

                        // Set up the buttons
                        builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                m_Text = input.getText().toString();

                                String ddesc = m_Text;
                                //saveDistance distances = new saveDistance(ddesc,distance);
                                try {
                                    dbHandler.addDistances(1,ddesc, distance);
                                    Toast.makeText(getActivity(), "Save Successful", Toast.LENGTH_LONG).show();
                                } catch (Exception e) {
                                    Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
                                }

                            }
                        });

    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });

                        builder.show();

This is my Database handler class

package com.spydotechcorps.hwfar.database;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.spydotechcorps.hwfar.provider.MyContentProvider;

/**
 * Created by INGENIO on 3/8/2015.
 */




public class Dbhandler extends SQLiteOpenHelper {


    private ContentResolver myCR;

    private static  int DATABASE_VERSION = 2;
    private static String DATABASE_NAME = "distanceDB.db";
    public static  String TABLE_DISTANCES = "distances";

    public static final String COLUMN_ID ="_id";
    public static final String COLUMN_DESCRIPTION = "COLUMN_DESCRIPTION";
    public static final String COLUMN_DISTANCE = "COLUMN_DISTANCE";


    public Dbhandler(Context context
            //, String name,
                       //SQLiteDatabase.CursorFactory factory, int version
                       ) {
        super(context, DATABASE_NAME,
                //factory
                null, DATABASE_VERSION);
        myCR = context.getContentResolver();    // obtaining reference to content resolver in content provider
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_DISTANCES_TABLE = "CREATE TABLE " +
                TABLE_DISTANCES + "("
                +
                COLUMN_ID +
                " _id INTEGER PRIMARY KEY," + COLUMN_DESCRIPTION
                + " TEXT," + COLUMN_DISTANCE + " REAL" + ")";
        db.execSQL(CREATE_DISTANCES_TABLE);


    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion,
                          int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_DISTANCES);
        onCreate(db);

    }


    public void addDistances(int c,String a,String b) {

        ContentValues values = new ContentValues();
        values.put(COLUMN_ID,c);
        values.put(COLUMN_DESCRIPTION, a);
        values.put(COLUMN_DISTANCE, b);

        myCR.insert(MyContentProvider.CONTENT_URI, values);
    }

    public saveDistance findDistances(String Distancesname) {
        String[] projection = {
                COLUMN_ID,
                COLUMN_DESCRIPTION, COLUMN_DISTANCE };

        String selection = "Distancesname = \"" + Distancesname + "\"";

        Cursor cursor = myCR.query(MyContentProvider.CONTENT_URI,
                projection, selection, null,
                null);

        saveDistance Distances = new saveDistance();

        if (cursor.moveToFirst()) {
            cursor.moveToFirst();
            Distances.setID(Integer.parseInt(cursor.getString(0)));
            Distances.setdesc(cursor.getString(1));
            Distances.setdistance(cursor.getString(2));
            cursor.close();
        } else {
            Distances = null;
        }
        return Distances;
    }

    public boolean deleteDistances(String Distancesname) {

        boolean result = false;

        String selection = "Distancesname = \"" + Distancesname + "\"";

        int rowsDeleted = myCR.delete(MyContentProvider.CONTENT_URI,
                selection, null);

        if (rowsDeleted > 0)
            result = true;

        return result;
    }



}

And this is the saveDistance Class

package com.spydotechcorps.hwfar.database;

/**
 * Created by INGENIO on 3/8/2015.
 */
public class saveDistance {
    public int _id;
    public String _desc;
    public String _distance;

    public void Distances() {

    }

    /*public void Distances(int id, String desc, String distance) {
        this._id = id;
        this._desc = desc;
        this._distance = distance;
    }*/
    public void Distances(
            //int k,
        String desc, String distance) {
        //this._id=1;
        this._desc = desc;
        this._distance = distance;
    }

    public void setID(int id) {
        this._id = id;
    }

    public int getID() {
        return this._id;
    }

    public void setdesc(String desc) {
        this._desc = desc;
    }

    public String getdesc() {
        return this._desc;
    }

    public void setdistance(String distance) {
        this._distance = distance;
    }

    public String getdistance() {
        return this._distance;
    }


}

Please, it has been giving me a real headache, Kindly help me out.