NodeJS MySQL module can't use two placeholders in a query - mysql

I'm trying to do this, which is exactly as it is in the documentation:
get_ids_query = 'SELECT ?? from ?? WHERE stat = 1 LIMIT 10'
then I call the function with two values placed inside variables:
var name = Table_Names.Tables_PR[t].name
var PK = Table_Names.Tables_PR[t].PK
ids = await this.getIds(PK, name)
This is the function:
async getIds(conf1, conf2) {
return await this.mydb.query(this.get_ids_query, conf1, conf2)
}
and these are the logs:
console.log(PK)
console.log(name)
console.log(mysql.format(this.get_ids_query, conf1, conf2))
output: idusers
users
SELECT `idusers` from ?? WHERE stat = 1 LIMIT 10
I've also tried:
var name = [Table_Names.Tables_PR[t].name]
var PK = [Table_Names.Tables_PR[t].PK]
which logs like this and it still returns the same query:
[ 'idusers' ]
[ 'users' ]
query format: SELECT `idusers` from ?? WHERE stat = 1 LIMIT 10
What am I doing wrong here? why is it reading the first placeholder but won't read the second one?

Related

update a object second value as a object with JSON_SET in mysql apostrof problem

I hava a longtext type column in mysql and it is default value is like that :
{"aaaaa": [], "bbbbb": []}
when I want to update that column with :
const IamCreator = 1;
const myValue= [1,22,66,77]; //object
const query = `UPDATE 8users SET content = JSON_SET(content, '$.aaaaa', '?') WHERE id = ?`;
connection.query(query,[myValue,IamCreator],function (err, result, fields) {
console.log(err)
})
it give syntex problemand update value like that ;
{"aaaaa": "[1,22,66,77]", "bbbbb": []}
how can I solve that appostrof prolem?
I tried :
content = JSON_SET(content, '$.aaaaa', ?)
content = JSON_SET(content,'$.aaaaa', [?])
const query = `UPDATE table SET json_column = JSON_SET(json_column, '$.mykanban', ?) WHERE id = ?`; connection.query(query, [JSON.stringify(myValue), IamCreator]);
ı took syntex error all the time

Check IF Result from Select Query with Async NodejS in MySQL?

I've got the following code in NodeJS using an Async/Promises wrapper for Mysql ;
row_c = await db.query( 'SELECT tagid FROM tags WHERE tagname = ?', [tag1] );
How do I now check if there is a result for an IF statement?
I tried;
if (row_c.tagid){
///some code
}
But it's not picking up the conditional. How do I check if the query returned a row?
db.query returns an array of rows. You can do the following:
row_c = await db.query( 'SELECT tagid FROM tags WHERE tagname = ?', [tag1] );
if (row_c.length) {
// if data is returned
console.log(row_c);
}

PHP/PDO Select from columns multiple conditions

I am trying to obtain results for a given member where status is pending or accepted doing the below:
$status1 = "Pending";
$status2 = "Attended";
$query = $conn->prepare('SELECT * FROM members WHERE member_id=:mID AND status=:status1 OR status=:status2');
$query->execute(array(':mID' => $mID,':status1' => $status1, ':status2' => $status2));
if ($query->rowCount() > 0) {
//start to create my table
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
//create variable, loop through and fill the table etc
}
}else{
echo "something";
}
This displays data - however, it even obtains results not specific to the member id (mID). Meaning other members data too!
I'm clearly missing something and or my query is wrong but struggling to find anything..
Any help appreciated.
You need to look at operator precedence for your database. You're doing this:
SELECT * FROM members WHERE member_id = :mID AND status = :status1 OR status = :status2;
Which most likely results in this:
SELECT * FROM members WHERE (member_id = :mID AND status = :status1) OR status = :status2;
But that's not what you want, so you will have to explicitly use parens like this:
SELECT * FROM members WHERE member_id = :mID AND (status = :status1 OR status = :status2);
Alternatively, you can use IN so that there's no OR:
SELECT * FROM members WHERE member_id = :mID AND status IN (:status1, :status2);

How to convert this query to doctrine DQL

SELECT apntoken,deviceid,created
FROM `distribution_mobiletokens` as dm
WHERE userid='20'
and not exists (
select 1
from `distribution_mobiletokens`
where userid = '20'
and deviceid = dm.deviceid
and created > dm.created
)
What this query does is selects all mobiletokens where the user id is equal to 20 and the deviceid is the same but chooses the newest apntoken for the device.
My database looks like below.
For more information on this query, I got this answer from another question I asked here(How to group by in SQL by largest date (Order By a Group By))
Things I've Tried
$mobiletokens = $em->createQueryBuilder()
->select('u.id,company.id as companyid,user.id as userid,u.apntoken')
->from('AppBundle:MobileTokens', 'u')
->leftJoin('u.companyId', 'company')
->leftJoin('u.userId', 'user')
->where('u.status = 1 and user.id = :userid')
->setParameter('userid',(int)$jsondata['userid'])
->groupby('u.apntoken')
->getQuery()
->getResult();
//#JA - Get the list of all the apn tokens we need to send the message to.
foreach($mobiletokens as $tokenobject){
$deviceTokens[] = $tokenobject["apntoken"];
echo $tokenobject["apntoken"]."\n";
}
die();
This gives me the incorrect response of
63416A61F2FD47CC7B579CAEACB002CB00FACC3786A8991F329BB41B1208C4BA
9B25BBCC3F3D2232934D86A7BC72967A5546B250281FB750FFE645C8EB105AF6
latestone
Any help here is appreciated!
Other Information
Data with SELECT * FROM
Data after using the SQL I provided up top.
You could use a subselect created with the querybuilder as example:
public function selectNewAppToken($userId)
{
// get an ExpressionBuilder instance, so that you
$expr = $this->_em->getExpressionBuilder();
// create a subquery in order to take all address records for a specified user id
$sub = $this->_em->createQueryBuilder()
->select('a')
->from('AppBundle:MobileTokens', 'a')
->where('a.user = dm.id')
->andWhere('a.deviceid = dm.deviceid')
->andWhere($expr->gte('a.created','dm.created'));
$qb = $this->_em->createQueryBuilder()
->select('dm')
->from('AppBundle:MobileTokens', 'dm')
->where($expr->not($expr->exists($sub->getDQL())))
->andWhere('dm.user = :user_id')
->setParameter('user_id', $userId);
return $qb->getQuery()->getResult();
}
I did this for now as a temporary fix, not sure if this is best answer though.
$em = $this->em;
$connection = $em->getConnection();
$statement = $connection->prepare("
SELECT apntoken,deviceid,created
FROM `distribution_mobiletokens` as dm
WHERE userid=:userid
and not exists (
select 1
from `distribution_mobiletokens`
where userid = :userid
and deviceid = dm.deviceid
and created > dm.created
)");
$statement->bindValue('userid', $jsondata['userid']);
$statement->execute();
$mobiletokens = $statement->fetchAll();
//#JA - Get the list of all the apn tokens we need to send the message to.
foreach($mobiletokens as $tokenobject){
$deviceTokens[] = $tokenobject["apntoken"];
echo $tokenobject["apntoken"]."\n";
}

LINQ to SQL - Group By/Where

I'm trying to implement a group messaging feature in ASP.NET MVC. I want to display a list of all threads for a specific ContactID, displaying the latest message in that thread (no matter who it's from). I've set up my table as below:
MessageID ThreadID MessageBody ContactID
10000004 300152,300160, msg1 300160
10000005 300152,300160, msg2 300160
10000008 300152,300160, msg3 300152
I was able to display the latest message grouped by ThreadID. Ex:
ThreadID Count LatestMessage
300152,300160, 3 10000008
However, if I add the Where clause before the group by (see below), it'll filter on ContactID first before doing the group by, and producing this result:
ThreadID Count LatestMessage
300152,300160, 2 10000005
Here's the code:
var result = from s in pdc.Messages
where s.ContactID == contactID
group new { s } by new { s.ThreadID } into d
let maxMsgID = d.Max(x => x.s.MessageID)
select new {
ThreadID = d.Key.ThreadID,
Count = d.Count(item => item.s.MessageType == GlobalConstants.MessageTypeText),
LastMessage = d.Where(x => x.s.MessageID == maxMsgID)
};
Is there a way to do the group by and then filter on ContactID?
var result = from s in pdc.Messages
where s.ContactID == contactID
group new { s } by new { s.ThreadID } into d
select new {
ThreadID = d.Key,
Count = d.Count(item => item.s.MessageType == GlobalConstants.MessageTypeText),
LastMessage = d.select(x => x.s.MessageID).Max(),
};
Hope it can help you and have a nice day.