Query Sql Server able to delete the last row of the table - javascript

I would like to expose you my problem: practically, through an AJAX function I call a server-side function, which should execute a query. This query, based on the data provided, deletes the last row of the table where the data in question is present. In the server side function everything works except the query, which instead of deleting the last row, deletes all the rows. Can anyone tell me the exact query?
public static void Contr_Dati(string provin)
{
string queryString = "DELETE FROM Prov_inser WHERE (SELECT MAX (Province_Inserite) FROM Prov_inser) = #Prov";
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["coso"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(queryString, connection))
{
SqlParameter parameter = new SqlParameter("Prov", provin);
command.Parameters.Add(parameter);
command.ExecuteNonQuery();
connection.Close();
}
}
}

If #Prov is the Max(key) of the table, your query
DELETE FROM Prov_inser WHERE (SELECT MAX (Province_Inserite) FROM Prov_inser) = #Prov
is equal to
DELETE FROM Prov_inser WHERE 1 = 1
which will delete all rows in the table
===================================================================
So you have to change it to
DELETE FROM Prov_inser WHERE Province_Inserite = #Prov
or without parameter
DELETE FROM Prov_inser WHERE Province_Inserite = (SELECT MAX(Province_Inserite) FROM Prov_inser)
If #Prov isn't a key, you have to add a key or a timestamp audit field (i.g. Created_Time) to identify the last inserted row of the table.

The solution that comes closest to the problem is: 'DELETE FROM Prov_inser WHERE Province_Inserite = Prov'. However #prov is not a key, but rather an input parameter. Prov_Inser is the name of the table and Province_Inserite is not the key.

Related

I'm trying to create Two Tables in sql.js but there is an error regarding foreign key constraint. there is no problem in creating the first table [duplicate]

This question already has an answer here:
Foreign keys not working - sqlite3.OperationalError: unknown column "user_id" in foreign key definition [duplicate]
(1 answer)
Closed 11 months ago.
Sample Code
<script>
config = {
locateFile: filename => `sql-wasm.wasm`
}
initSqlJs(config).then(function(SQL)
{
//Create the database
const db = new SQL.Database();
//create first table - Questions (Parent Table)
let question = "CREATE TABLE Questions(qid INT NOT NULL, qdesc CHAR, PRIMARY KEY(qid));\
INSERT INTO Questions VALUES(1, 'set1');\
INSERT INTO Questions VALUES(2, 'set2');\
INSERT INTO Questions VALUES(3, 'set3');\
INSERT INTO Questions VALUES(4, 'set4');\
INSERT INTO Questions VALUES(5, 'set5');";
db.run(question);
const result = db.exec("SELECT * FROM Questions");
console.log(result);
//create second Table - Qimages (Child Table)
let qimage = "CREATE TABLE Qimages(img_id INT AUTO_INCREMENT, imgurl VARCHAR,FOREIGN KEY (qid) REFERENCES Questions(qid));\
INSERT INTO Qimages VALUES('https://www.w3schools.com/howto/img_woods.jpg',1);\
INSERT INTO Qimages VALUES('https://www.w3schools.com/howto/img_5terre.jpg',1);\
INSERT INTO Qimages VALUES('https://www.w3schools.com/howto/img_mountains.jpg',2);";
db.run(qimage);
const res = db.exec("SELECT * FROM Qimages");
console.log(res);
</script>
Below is the Error I'm Getting
uncaught (in promise) Error: unknown column "qid" in foreign key definition
As the message says, there is no qid column in the Qimages table. I suspect that you want:-
CREATE TABLE Qimages(img_id INT AUTO_INCREMENT, imgurl VARCHAR,qid INTEGER REFERENCES Questions(qid));
Thus the value of the qid column (now defined), that uses the column level version of the Foreign Key constraint declaration, must have a corresponding value in the qid column of the Question table.
Alternately you could use:-
CREATE TABLE Qimages(img_id INT AUTO_INCREMENT, imgurl VARCHAR,qid INTEGER, FOREIGN KEY (qid) REFERENCES Questions(qid));

How to create a dynamic columns in a table using array values in codeigniter

public function addDynFields()
{
$checkedfileds=$_POST['CheckedFileds'];
$fields=implode(',',$checkedfileds);
$dynflds = strtolower($fields);
$dynclmns = 'add_to'.'_'.$dynflds;
if($fields == 'Title')
{
$this->db->query("ALTER TABLE `pm1asset_dynamic_fields` ADD ".$dynclmns." int(11) NOT NULL");
}
else
{
$this->db->query("ALTER TABLE `pm1asset_dynamic_fields` ADD ".$dynclmns." varchar(255) NOT NULL");
}
}
How to create a dynamic columns in a table using array values in codeigniter. Using First array value we need to create first and using second we need to create a second dynamic column in a table and so on. How to do that can any one please help me. Any help could be appreciated.
I would not advise that because you also need to give type, length, default value, null etc. So, it will be a hectic task. Also, you'll have to check if the table already exists then use Alter table query.
If you must then also take the type, length value from the user
Possible Solution
In your function check if the table exists,
$query = "SELECT 1 from `Your_Table` LIMIT 1";
//returns false if the table does not exist.
$tableExists = $this->db->query($query);
IF NOT--Use CREATE TABLE query-- //if($tableExists === FALSE)
CREATE TABLE Your_Table(
Column_1 Column_1_Attributes,
Column_2 Column_2_Attributes,
.
.
)
Eg:
$query = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
email VARCHAR(50)
)";
IF YES--
Use ALTER TABLE query--
ALTER TABLE Your_Table
MODIFY COLUMN new_column new_column_attributes;
Eg:
$query = "ALTER TABLE MyGuests
ADD lastname VARCHAR(30) NOT NULL";

sqlite - unable to query web db with WHERE clause

I'm using the WHERE clause while trying to query my sqlite database. I know there is data in the db which I should be able to retrieve based on the conditionals in my query, but I can't seem to get it to work.
When I query without conditionals...
sql = 'select LocationGUID, ID, Fullname FROM tblUser';
I'm able to return all the data from the selected columns. Is this is a quotation issue? I've tried single and double-quotes around the conditional values but the number of rows I return is still 0.
Javascript:
sql = 'select LocationGUID, ID, Fullname FROM tblUser WHERE UserName=\'mike\' AND Password=\'mike123\'';
mydb = getDBConn();
mydb.transaction(function(tx) {tx.executeSql(sql, [], function(tx,results) {
var size = results.rows.length;
console.log(size);
for (var i=0;i<size;i++) {
for (var key in results.rows.item(0)){
var row = results.rows.item(i);
console.log(row[key]);
}
}
SQLite DB
The correct query to find this row would be this:
SELECT ... FROM tblUser WHERE UserName = 'mike ' AND ...
You might want to change the code that stores the data to remove these unwanted spaces.
To fix the database, use something like this:
UPDATE tblUser SET UserName = rtrim(UserName)

Jquery, getting the column data of selected row using jtable

I have 3 fields in my jtable; Name, Age, Occupation.Lets say I select a specific row, How would i get the specific column data of that row?
Ex:
I select the following row:
Row 2: Joe Brown, 25, Teacher
How would I get the age data (which is 25) of that row ?
Thanks
PS: I intend to delete that row, so I need the name to query the sql database properly (im using jdbc)
$('#yourTable tr').each(function() {
var age = $(this).find("td").eq(1).html();
alert(age);// for testing purpose
});
You will get the value of the second row (the index is zero-based)
var rowIndex = // the zero based index of the selected row
var age = $('.jtable tbody').children(rowIndex).children('td').eq(1).text(); // return the age

SQLite database on phonegap resultset length increase every time

I am developing an application using phonegap and i am using database as sqlite.
I have created a table using following commands:
var dbb;
var shortName = 'Vaccine1';
var version = '2.0';
var displayName = 'vaccine';
var maxSize = 100000;
dbb = window.openDatabase(shortName, version, displayName,maxSize);
and inserted values using this function..
function AddDBvalues()
{
dbb.transaction(function(tx){
//tx.executeSql( 'DROP TABLE IF EXISTS Vaccin',nullHandler,nullHandler);
tx.executeSql( 'CREATE TABLE IF NOT EXISTS Vaccin(Vday INTEGER NOT NULL,VName TEXT NOT NULL, CCountryid INTEGER NOT NULL , Sex TEXT NOT NULL)', [],nullHandler,errorHandler);},errorHandler,successCallBack);
dbb.transaction(function(transaction) {transaction.executeSql('INSERT INTO Vaccin(Vday,VName,CCountryid,Sex) VALUES (?,?,?,?)',["0","BCG","91","both"], nullHandler,errorHandler);});
dbb.transaction(function(transaction) {transaction.executeSql('INSERT INTO Vaccin(Vday,VName,CCountryid,Sex) VALUES (?,?,?,?)',["0","OPV dose 1 of 5","91","both"], nullHandler,errorHandler);});
dbb.transaction(function(transaction) {transaction.executeSql('INSERT INTO Vaccin(Vday,VName,CCountryid,Sex) VALUES (?,?,?,?)',["1","Hepatites B dose 1 of 2","91","both"], nullHandler,errorHandler);});
dbb.transaction(function(transaction) {transaction.executeSql('INSERT INTO Vaccin(Vday,VName,CCountryid,Sex) VALUES (?,?,?,?)',["42","DPT dose 1 of 3","91","both"], nullHandler,errorHandler);});
dbb.transaction(function(transaction) {transaction.executeSql('INSERT INTO Vaccin(Vday,VName,CCountryid,Sex) VALUES (?,?,?,?)',["42","OPV dose 2 of 5","91","both"], nullHandler,errorHandler);});
dbb.transaction(function(transaction) {transaction.executeSql('INSERT INTO Vaccin(Vday,VName,CCountryid,Sex) VALUES (?,?,?,?)',["70","DPT dose 2 of 3","91","both"], nullHandler,errorHandler);});
}
and used this function to get valuse from database..
function ShowValue()
{
var cnn = sessionStorage.getItem('cid');//getting from session
var cn=parseInt(cnn);
alert (cn); //always show correct value
dbb.transaction(
function (transaction) {
transaction.executeSql("SELECT * from Vaccin WHERE CCountryid='"+cn+"';",[], dataHandler, errorHandler);});
function dataHandler(transaction, results){
alert("first method" + results.rows.length);
for (var i=0; i<results.rows.length; i++) {
...... }
}}
i am getting an unexpected error is that the length of resultset increase every time
means if run app first time it show correct value and when i run it again it just show the length of resultset = results.rows.length+results.rows.length means double and so on....every time.
please help me if anybody know what's going wrong.
Is AddDBValues getting called on every run of the app? IF NOT EXISTS has no effect on the insert statements.
Is the database persistent between runs? If so then the data is doubling because not you're dropping the table. In you AddDBvalues() function the DROP ... command is commented out.
//tx.executeSql( 'DROP TABLE IF EXISTS Vaccin',nullHandler,nullHandler);
Unrelated but you also have a possible SQL injection vulnerability. The variable cn should be passed in as a bind variable and not simply added to the SQL as a string.
transaction.executeSql("SELECT * from Vaccin WHERE CCountryid='"+cn+"';",[], dataHandler, errorHandler);});

Categories