Create SQL sentece according to users input MySQL - javascript

what I want to do is this:
First have a form that has 5 input for example:
Name:
Career:
Experience:
City:
Speciality:
what I need to do is create a sql sentence according to the fields that are filled. If only 2 field were filled create a sql with only those fields. I don't have any idea how to do this besides creating a sql sentence for every possibility which turns out to be a pretty extensive work. i read that i could use store procedures, but again I don't know how I would do it. please help me!
well sorry if i didn't elaborate the question.
here is the deal i have diferent tables in mysql database
person
person_id
name
last_name
person_courses
person_id
course
person_carrer
person_id
carrer
person_experience
person_id
position
experience_description
experience_from_date
experience_to_date
all this tables are related to person by foreign_key (person_id)
then i have a page where user have 6 diferent inputs:
name:
last_name:
courses:
experience:(this fields search position and experience_description from table person_experience)
antiquity:(must obtain a sumatory of all person_experience)
the user must obtain results according to the fields he filled.
what i tried to do is create a complex SQL sentence using "%%" like this
select a.person_id, b.name, c.last_name, d.courses, f.experience, g.antiquity
from person a,
(
'SQL SENTENCE' WHERE NAME LIKE "%%"
) b,
(
'SQL SENTENCE' WHERE LAST_NAME LIKE "%%"
) c,
(
'SQL SENTENCE' WHERE COURSE LIKE "%%" GROUP BY PERSON_ID
) d,
(
'SQL SENTENCE' WHERE POSITION LIKE "%%" OR EXPERIENCE_DESCRIPTION LIKE "%%"
GROUP BY PERSON_ID
) f,
(
'SQL SENTECE'
WHERE 'SUMATORY OF ALL PERSON EXPERIENCE, (TO_DATE - FROM_DATE)/365 '>=0 (THIS ZERO WOULD CHANGE IF USER FILLS INPUT ANTIQUITY)
GROUP BY PERSON_ID
) g
WHERE a.person_id = b.person_id and c.person_id = b.person_id and d.person_id = c.person_id and f.person_id = d.person_id and g.person_id = f.person_id
and if the user fills any field i just put the value between '%value%' so this way i get the result, and i get results with this sql sentence but the problem is that if a person doesn't have a experience or carrer it is not shown in the result, so i need someway, as i said in the firstplace, just search in the database according to the users filled inputs.
for example in if the user fills:
carrer, experience: search all person with that carrer and that experience.
name: search all person even if they dont have carrer or course or experience with that name
PS: trying to create an sql sentece for every posibility would result in 64 sql senteces and i am not thinking about doing it!
THANK FOR ALL THE HELP IN ADVANCE

Here is something that may help:
$sql = array(); // initialize empty array for data
foreach(array("name", "career", "experience", "city", "speciality") as $key) { // iterate all the form controls
if(!empty($value = trim($_POST[$key]))) {
// the form input is filled, so we add it to data array (with proper escaping)
$sql["`".$key."`"] = "'".mysqli_real_escape_string($value)."'";
}
}
if(count($sql)) { // only if user had provided some data
// generate the final SQL statement
$sql = "INSERT INTO `table` ("
.implode(", ", array_keys($sql)).") VALUES (" // for example (`name`, `career`)
.implode(", ", array_values($sql)) . ")"; // for example ('Foo', 'Bar')
} else {
// no informations provided
}

Related

INSERT INTO table VALUES float string from postman input

I'm trying to create a new course row into my Courses database in postman and I cannot get the syntax correct.
I've got 159 values that need to be added into a single course. Any chance I can summarise them instead of having to write down all the values?
Currently this is my query:
const addCourse = "INSERT INTO courses VALUES (value1 'value2','value3', 'value4', 'value5', 'value6', 'value7', 'value8', 'value9', 'value10', 'value11', 'value12', 'value13', 'value14', 'value15', 'value16', 'value17', 'value18', 'value19', 'value20', 'value21', 'value22', 'value23', 'value24', 'value25', 'value26', 'value27', 'value28', 'value29', 'value30', 'value31', 'value32', 'value33', 'value34', 'value35', 'value36', 'value37', 'value38', 'value39', 'value40', 'value41', 'value42', 'value43', 'value44', 'value45', 'value46', 'value47', 'value48', 'value49', 'value50', 'value51', 'value52', 'value53', 'value54', 'value55', 'value56', 'value57', 'value58', 'value59', 'value60', 'value61', 'value62', 'value63', 'value64', 'value65', 'value66', 'value67', 'value68', 'value69', 'value70', 'value71', 'value72', 'value73', 'value74', 'value75', 'value76', 'value77', 'value78', 'value79', 'value80', 'value81', 'value82', 'value83', 'value84', 'value85', 'value86', 'value87', 'value88', 'value89', 'value90', 'value91', 'value92', 'value93', 'value94', 'value95', 'value96', 'value97', 'value98', 'value99', 'value100', 'value101', 'value102', 'value103', 'value104', 'value105', 'value106', 'value107', 'value108', 'value109', 'value110', 'value111', 'value112', 'value113', 'value114', 'value115', 'value116', 'value117', 'value118', 'value119', 'value120', 'value121', 'value122', 'value123', 'value124', 'value125', 'value126', 'value127', 'value128', 'value129', 'value130', 'value131', 'value132', 'value133', 'value134', 'value135', 'value136', 'value137', 'value138', 'value139', 'value140', 'value141', 'value142', 'value143', 'value144', 'value145', 'value146', 'value147', 'value148', 'value149', 'value150', 'value151', 'value152', 'value153', 'value154', 'value155', 'value156', 'value157 ', 'value158' )"
This is my courseController code:
const addCourse = (req, res) => {
console.log(req.body);
const { id_curso } = req.body;
//check Curso exists
pool.query(queries.checkIdCursoExists, [id_curso], (error, results) => {
if (results.rows.length) {
res.send("Este curso ja existe.");
}
// add course
pool.query(queries.addCourse),
(error, results) => {
if (error) throw error;
res.status(201).send("Curso criado com sucesso");
};
});
};
The problem I encounter is this error message whether I have value1 in quotes or not:
error: type "value1" does not exist'
The course is not posted onto my database.
The path to your answer lies in your INSERT statement. I guess your courses table has 159 columns in it. (That is a great many columns and may suggest the need to normalize your table. SQL handles multiple-row data more efficiently than multiple-column data where it makes sense to do so. But you did not ask about that.)
The INSERT syntax is either this:
INSERT INTO tbl (col1, col2, col3) VALUES (const, const, const);
or this:
INSERT INTO tbl VALUES (const, const, const);
The first syntax allows you to insert a row without giving values for every column in the table. You use the second syntax. It requires you to give one constant value for each column of your table. But your insert looks like this:
INSERT INTO courses VALUES (value1 'value2', ... , 'value158' )"
I see some problems with this.
You only have 158 values, but your question says you have 159.
value1, the first value in your list, isn't a constant.
You need a comma after your first value.
All your value constants are text strings. Yet you mentioned float in the title of your question.

how to use the variable in snowfalke procedure

var step0=`select INGESTION_SUCCESSFUL,ingestion_uuid from FILE_INGESTION_HISTORY where ingestion_uuid=(
select ingestion_uuid from registration where registry_subject_uuid=:1
qualify row_number() over( order by dnb_latest_received_dt desc)=1)`;
var statement0=snowflake.createStatement( {sqlText: step0,binds: [PARAM_REG_SUB_UUID]} );
variable1= statement0.execute();
variable1.next();
ingsindc=variable1.getColumnValue(1);
ingsuuid=variable1.getColumnValue(2);
when i try to use above ingsuuid in sql where clause it is throwing error
var step1= create or replace temporary table FN_IGSN_REG_LBV1 as select * from registration where ingestion_uuid=**ingsuuid** and (DELETE_INDC=0) qualify row_number() over (partition by REGISTRATION_HASH_KEY order by dnb_latest_received_dt desc, row_created_tmst desc, registration_uuid desc) = 1;
var statement1=snowflake.createStatement( {sqlText: step1} );
statement1.execute();
Binding a variable to a SQL statement allows you to use the value of the variable in the statement.
You can bind NULL values as well as non-NULL values.
The data type of the variable should be appropriate for the use of the value in the SQL statement. Currently, only JavaScript variables of type number, string, and SfDate can be bound. (For details about the mapping between SQL data types and JavaScript data types, see SQL and JavaScript Data Type Mapping.)
Here is a short example of binding:
var stmt = snowflake.createStatement(
{
sqlText: "INSERT INTO table2 (col1, col2) VALUES (?, ?);",
binds:["LiteralValue1", variable2]
}
);
More details: https://docs.snowflake.com/en/sql-reference/stored-procedures-usage.html#binding-variables

Manipulating Javascript Object Format

I am trying to receive all of the players under a certain team along with the team's id.
Here is my query:
SELECT player.team_id, team.name, player.first_name, player.last_name FROM player, team WHERE player.team_id = team.id AND player.league = "League 1";
I am taking the result (stored in teams) and sending it to my client by doing this:
res.send({
success: true,
teams: teams
});
Here is what it returns when I reach its endpoint:
I want to reformat this date to where I get one field for each unique team. It should have a players field (array) inside so I can access the names of each player part of the team. Does anyone know how I can manipulate this data to that format?
So for example, for this data set, inside the teams object, there would only be one field named "Warriors" with a players array that has all of those people's name inside of it.
I tried following the answer, but now it's just returning it as a string, not an actual object.
You can use aggrgation and json functions:
select
t.team_id,
t.name,
json_array_agg(
json_object('first_name', p.first_name, 'last_name', p.last_name)
) as players
from teams t
inner join players p on p.team_id = t.team_id
group by t.team_id, t.name
The third column in the resultset is a json array that contains json objects that represent the players, with keys first_name and last_name.
You can also aggregate the whole resulset as a json array, with another level of aggreation:
select json_array_agg(
json_object('team_id', team_id, 'name', name, 'players', players)
) res
from (
select
t.team_id,
t.name,
json_array_agg(
json_object('first_name', p.first_name, 'last_name', p.last_name)
) as players
from teams t
inner join players p on p.team_id = t.team_id
group by t.team_id, t.name
) t
Edit: json_array_agg() is available starting version 10.5.0 only. In earlier versions, an alternative is string concatenation:
select
t.team_id,
t.name,
concat(
'[',
group_concat(json_object('first_name', p.first_name, 'last_name', p.last_name)),
']'
) as players
from teams t
inner join players p on p.team_id = t.team_id
group by t.team_id, t.name

knexjs and postgres: whereRaw within a join

In the following code I am joining two table and searching for a proper name:
const homesWithUsers = knex('homes')
.join('users', 'homes.id', 'users.home_id')
.whereRaw(
`LOWER("homes.name") LIKE ?`,
'%' + payload.home_name.toLowerCase() + '%'
)
//Stringified
select * from "homes" inner join "users" on "homes"."id" = "users"."home_id" where LOWER("homes.name") LIKE '%george%'
I need to use whereRaw because the database column and the search term are proper names where capitalization is uncertain. (Storing an extra column of the proper names represented in all uppercase is not an option.) However, this query fails with: error: column "homes.name" does not exist. If I remove homes. the query is ambiguous (error: column reference "name" is ambiguous) because both the user and home tables have the columns name.
If I do a simple where statement the query is successful
const homesWithUsers = knex('funeral_homes')
.join('users', 'homes.id', 'users.home_id')
.where({ 'homes.name': payload.home_name })
.select('*');
The only problem is that this will fail with the payload values I expect to field from users interacting with the database.
Any suggestions for how to successfully perform a whereRaw on a joined table?
You need to use identifier replacement syntax ?? when passing column identifiers to raw, which needs to be quotet properly. Like this:
const homesWithUsers = knex('homes')
.join('users', 'homes.id', 'users.home_id')
.whereRaw(
`LOWER(??) LIKE ?`, ["homes.name", '%' + payload.home_name.toLowerCase() + '%']
)

How to make a Drop-down form in a PDF auto-populate a text box [Bluebeam]

I am trying to have a drop down form that is populated with contacts populate a text box that contains the company information and address of that contact.
I have a small amount of knowledge in Javascript and have tried the following code:
var one = this.getField("Contact");
var two = this.getField("Company");
if (one.value == 'John Doe') {
two.value = 'Company1';
} else if (one.value == 'Jane Doe') {
two.value = 'Company2';
}
Is there anyone that can point me in the right direction? I have looked for similar questions but none I could find offered a solution for this specific issue.
Bluebeam is a relatively smart PDF viewer, and it should be possible to do some JavaScripting. You'd have to check whether it works, however; I don't have access to Bluebeam, and can not test it myself). A possible solution would look like this:
a) you create a document-level JavaScript which contains an array of the contact info (which may contain more than just the company name, but also address etc.. This array could look like this:
var contarr = new Array() ;
contarr[0] = ["Contact Person", "Company", "Address", "City", "State", "Zip"] ;
contarr[1] = ["John Doe", "Does and Donz", "Main Street", "Doetown", "TX", "99999"]
// and so on
b) In your Dropdown, you add the contact person name, and as return value, you add the index number of its entry in the contarr array. Let's assume we call the dropdown "Contact".
c) In an independent text field, you add the following Calculation script:
var sele = this.getField("Contact").value ;
this.getField("Company").value = contarr[sele][1] ;
this.getField("Address").value = contarr[sele][2] ;
this.getField("City").value = contarr[sele][3] ;
this.getField("State").value = contarr[sele][4] ;
this.getField("Zip").value = contarr[sele][5] ;
If everything is set up correctly, and you reopened the document, you should be able to select a contact, and the rest of the information would fill the according fields.

Categories

Resources