Cannot delete from mysql (file.size) - javascript

First I inserted a new record into a database with a field file_size. It all works fine. Then I want to delete the record with a given name and size from the database. It works with name, but when I add AND statement it doesnt work.
$conn->query("DELETE FROM mytable WHERE name LIKE '%{$t}' AND file_size = '$file_size'");
file_size is passed through $file_size= $_POST['size']; and it works correctly. The number in the database and the one passed is the same. I have no idea why the above doesnt work...at first I thought that maybe these are different data types and hence I am comparing string with integer, but in Javascript it shouldnt matter...Any advice would be greately appreciated.

Maybe prepare request
$query=$conn->prepare("DELETE FROM mytable WHERE name LIKE :like_param AND file_size = :filesize");
$query->excute(array(':like_param' => '%'.$t, ':filesize' => $file_size));

Related

How to Check if value exists in sql column?

I want Chack If Value exists in coulmn, If value exist do not insert to table.
If not exist insert to table a new data.
I tried this but not works..
my code in node.js
`
//add new meeting
async function addNewMeeting(meeting: Meeting): Promise<Meeting>{
const sql = `INSERT INTO meetings Values (
DEFAULT,
${meeting.meeting_code},
'${meeting.meeting_start_date}',
'${meeting.meeting_end_date}',
'${meeting.meeting_description}',
'${meeting.meeting_room}'
)`;
const result:OkPacket = await dal.execute(sql);
meeting.id = result.insertId;
return meeting;
}
`
I tried to chack if the value - '2022-10-15 07:03:42' exist or not.
If not exists insert to table a new data.
if exist send a error that cannot insert a new meeting because there is already meeting at this time.
thanks :)
You can solve this at the SQL level by using the keyword UNIQUE when defining that column in the table. This will prevent you from being able to insert duplicate values.
SQL UNIQUE
Note that this will throw an error and depending on the package you are using to connect to your database, you might need some error handling.
Alternatively in your javascript you can select all values in the column that should be unique, and then only proceed with the insertion code if there is not a match.

Check if firebase array contains value then get all data in that index

So I have an array in a firebase document called ActivityLikes. It looks like this:
The collection is like this below:
const db = fire.firestore();
db.collection("eventLikes")
.doc(eventID)
.set({
ActivityLikes: likes
})
I have another collection which has the word "Avoca" saved, and I have this right now and I basically want to pull the data that has "Avoca" in it. So like with the name "Avoca" i can also get the imgURL. I've tried a for loop to go inside the object that firebase returns but I guess my logic is due to the fact theres multiple value and key pairs inside of it so how would i get all of the data inside of index 1 because it has the name = "Avoca".
I have the activitylikes in a hook so I have it after calling it from firebase.
I've tried like:
for (var i=ActivityLikes.length; i--;) {
if (myArr[i].indexOf("Avoca")>=0) break;
}
I think my logic is off Im just not sure how to get all of the data inside of the index once the name matches
The other collection just looks like this: https://i.stack.imgur.com/TqhWd.png. I know how to call this from firebase, I just need to figure out the logic for getting all the data in the array in the ActivityLikes when the name "Avoca" is present
If you are looking just for the word "Avoca" then try using find():
// data is snapshot.data() after query
const avocaData = data.ActivityLikes.find(d => d.name === "Avoca")
Here avocaData will either be the first object from likes array where name is Avoca or undefined is there isn't any. After that you can use an if statement to check that and proceed with rest of the logic.

How can I INSERT new values and values from an already existing table?

I'm currently learning MySQL and have learned the INSERTO INTO statement and the INSERT INTO SELECT statement.
The INSERT INTO statement works like this:
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
While the INSERT INTO SELECT works like this:
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;
What I'm trying to do is add new values while also adding values that I already have stored in another table.
con.query("INSERT INTO vehicles (vehicleType, vehicleModel, vehicleOwner, vehicleSpawnX, vehicleSpawnY, vehicleSpawnZ)")
From the query above, I already have the vehicleOwner value stored in another table, while the other ones I've just gotten.
How can I do this? Add a VALUES statement before SELECT?
I'm using SQL Workbench 8.0 and JavaScript. Also, all the values are NOT NULL, so I can't make two different queries, unless on the first one I add temporary values that I'll update on the second one.
What I want to replace:
vehicleType -> "players"
vehicleModel -> vehicleCreate.model
vehicleOwner -> playerID FROM players table
vehicleSpawnX -> pos.x
vehicleSpawnY -> pos.y
vehicleSpawnZ -> pos.z
Thanks!
It's not possible... But you can select data and store that on variables, then you will store it in another table
You would construct a query. Your data model is a bit hard to follow since you give no examples of the data or of what you really want to do.
So let me give a simpler example. Say, you have a table with two columns for two players and you want to put the ids into a table -- but using their names. The query would look like:
insert into pairs (playerId1, playerId2)
select p1.playerId, p2.playerId
from players p1 join
players p2
on p1.name = ? and p2.name = ?;
The ? are for parameter placeholders. I assume you know to aways use parameters when passing values into a query.

Objection.js How to use outer values in inner query?

I'm struggling with a somewhat more complex SQL Query which HAS TO BE in Objection.js.
Below is the code so far
const tagEntry = await Tag_overview.query()
.where('playable') //the playable column is a boolean
.whereExists(
InnerTableName.query().findById([<normal variable>, tag.id]) //<= tag.id is the id of the row in the outer query
)
)
.orderBy(raw('random()'))// this randomly orders the selection
.limit(1)
"tag.id" should be the value of the row in the top/outer query thats currently being checked. In SQL I'd solve it with a simple line like (< normal variable> is a Javascript variable passed into the query and can be trated as a hardcoded value, it and tagid are a compound key)
and EXISTS (SELECT tagid, othercolumn FROM kunstmakler_preselection WHERE tag.id = tagid AND <normal variable> = othercolumn)
But I have absolutely no clue how to do this in Objection.js. Yes, it needs an inner Query, but HOW do I pass this tag.id in there? I'm completely lost and neither the API Reference nor the Recipe Book is any help (found here: https://vincit.github.io/objection.js/recipes/ )
Is a join necessary here? Would it be worth it? [The tagoverview Table is rather small while "InnerTableName" is quite large]. I feel like that can't really be the solution since in ülain SQL it'd be such a smooth one liner
First make sure that you have declared composite key correctly in model InnerTableName https://vincit.github.io/objection.js/recipes/composite-keys.html
Then you should be able to do:
.whereExists(
InnerTableName.query().findById([theJsVariable, ref("Tag_overview.id")])
)

Filter Parse Query based on pointer field value

I have two tables A & B, in table B I have a column of type pointer, each field points to a class in table A.
I need to know how to query table B based on the value of a particular field in the pointer column.
So for example, I have 4 objects (records) in table B, and in the pointer column I have pointer1, pointer2, pointer3 and pointer4. So if I want to carry out a query on table B and I want to extract the record with the field value of pointer3 how do I do this in javascript?
Based on your comment I would suggest storing both object IDs for each row. You could use Parse.when(recordA.save(), recordB.save()).then(...) to wait until both finished if you needed to provide feedback in the UI.
An alternative is to just store the object ID for the table B record and in the success handler you'll get back the updated record that'll include the pointer where you can then execute another save. This is slow as it will do two saves in sequence instead of kicking both off at once.
So after a long time searching and looking around and asking questions I figured it out myself in the end. I needed to pass in an object in the query.equalTo method like so:
query.find({
success: function(results) {
var detailsObject = results[0];
detailsObject.set("uuid", uuid);
detailsObject.set("proximity", prox);
detailsObject.set("campaignId", campaignId);
detailsObject.set("location", location);
detailsObject.set("sub_location", subLoc);
detailsObject.save(null, {
success: function(detailsObject) {
var content = Parse.Object.extend("Content");
var contentQuery = new Parse.Query(content);
var id = detailsObject.id;
contentQuery.equalTo("descId", detailsObject);
So "descId" is the pointer column in my content table and rather than trying to query the value in the field (object id of details object), I needed to pass the details object into the query.equalTo
I hope this is of benefit to someone else.

Categories