Codeigniter 4 - WHERE clause in Model - sql

It's me again, Van.
Hi everyone,
I hope you're doing well!
I am doing a tutorial on a chat application using Codeigniter 4 with Ajax.
Everything worked fine until I applied the following code in the Model below
public function load_chat_data($sender_id,$receiver_id) {
// $where = ['sender_id' => $sender_id, 'receiver_id' => $receiver_id];
$where1 = "sender_id = $sender_id OR sender_id = $receiver_id";
$where2 = "receiver_id = $receiver_id OR receiver_id = $sender_id";
$builder = $this->db->table('chat_messages');
// $builder->where($where);
$builder->where($where1);
$builder->where($where2);
$builder->orderBy('chat_messages_id','ASC');
$results = $builder->get();
$rows = $results->getResultArray();
if($rows > 0)
{
return $rows;
}
else
{
return false;
}
}
The lines that I commented worked well before they were commented but it was not enough data I wanted to get so I tried to get both data of sender and receiver to display on the view by adding more code. However, when I tried $where1 and $where2 for the WHERE clauses, it didn't work. I think it must be the syntax error. Please correct my codes or any ideas on how the codes work with the same meaning supposed.
Thank you so much!!!
I tried as below, but it still didn't work.
$where1 = "sender_id={$sender_id} OR sender_id={$receiver_id}";
$where2 = "receiver_id={$receiver_id} OR receiver_id={$sender_id}";
Also, I tried:
$where1 = "'sender_id'=$sender_id OR 'sender_id'=$receiver_id";
$where2 = "'receiver_id'=$receiver_id OR 'receiver_id'=$sender_id";

I think you are trying to receive the messages of the conversation between two people. Can you try the following code for this?
$builder->groupStart(); // or $builder->orGroupStart();
$builder->where('sender_id', $sender_id);
$builder->where('receiver_id', $receiver_id);
$builder->groupEnd();
$builder->orGroupStart();
$builder->where('sender_id', $receiver_id);
$builder->where('receiver_id', $sender_id);
$builder->groupEnd();

Related

Questions regarding update of table on Prestashop

I'm trying to update ps_stock_available when I modify the product on Prestashop. But it's unsuccessfull. Could you help me please ?
public function hookActionUpdateQuantity(array $params)
{
$id_product = $params['id_product'];
$product = new Product((int)$id_product);
$id_category = $product->id_category_default;
$db = \Db::getInstance();
$request_loc='SELECT location FROM `'._DB_PREFIX_.'category_location` WHERE `id_category` = '.(int)$id_category;
$location = $db->getValue($request_loc);
$request_id_stock='SELECT id_stock_available FROM `'._DB_PREFIX_.'stock_available` WHERE `id_product` = '.(int)$id_product;
$id_stock_available = $db->getValue($request_id_stock);
$result = $db->update('stock_available', array('location' => $location), '`id_stock_available` = '.(int)$id_stock_available);
}
I have written this code but it doesn't seem to work.
in order to accomplish this task I would rely to the native StockAvailable class metehods getStockAvailableIdByProductId() and setLocation() (check the classes/stock/StockAvailable.php file).
Anyway your code seems to be correct, so I would definitely check for undefined variables and/or something not working in the $db->update statement.
In case, you can change it to :
$db->execute('UPDATE '._DB_PREFIX_.'stock_available SET `location` = "'.pSQL($location).'" WHERE id_stock_available = '.(int)$id_stock_available;

Blacklisted words | Filter words discord.bs

I got one error with my blacklisted words, cannot read proprety ".id" of undefined. After "db.get(...)"
Thanks to help me!
// BLACKLISTED words
client.on('message', message => {
if(message.author.bot) return;
let wordarray = message.content.split(" ")
let filterWords = db.get(`blacklistwords_${message.guild.id}_${message.guild.id}`)
for(var i = 0; 1 < filterWords.length; i++) {
if(wordarray.includes(filterwords[i])) {
message.delete()
let Filter = new Discord.MessageEmbed()
.setColor('#FFE90F')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription('<a:AttentionPink:706154679796760657> | **This word is blacklisted from this guild!** Do not say that again!')
.setTimestamp()
message.author.send(Filter)
break;
}
}
});![enter image description here](https://i.stack.imgur.com/Gouis.jpg)
I think you should put your Guild ID in a var like so:
var guildID = message.guild.id;
If this is not working, well it's not the prettiest, but try using this line of code:
var guildID = bot.guilds.get(message.guild.id).id;
EDIT: Source
If the bot receives a message via DMs, it will not be able to get message.guild and that's why it says it is undefined. You can add something like if(message.channel.type === 'dm') return; so that the bot will not listen to DMs

SQLite database isn't holding multiple values under primary key in my Discord.js bot

To start off, here's my main bot.js code (Sorry if it seems like code spaghetti. I'm not the best with javascript):
const fs = require('fs');
const Discord = require('discord.js');
const client = new Discord.Client();
const auth = require('./auth.json');
const pack = require('./package.json');
const SQLite = require('better-sqlite3');
const sql = new SQLite('./scores.sqlite');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.on('ready', () => {
console.log(` Bot: ${client.user.tag}
Version: ${pack.version}
Logged in and clear for takeoff.`);
});
client.on("ready", () => {
const battle_leaderboard = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'scores';").get();
if (!battle_leaderboard['count(*)']) {
sql.prepare("CREATE TABLE scores (id TEXT PRIMARY KEY, user TEXT, guild TEXT, points INTEGER;").run();
sql.prepare("CREATE UNIQUE INDEX idx_scores_id ON scores (id);").run();
sql.pragma("synchronous = 1");
sql.pragma("journal_mode = wal");
}
client.getScore = sql.prepare("SELECT * FROM scores WHERE user = ? AND guild = ?");
client.setScore = sql.prepare("INSERT OR REPLACE INTO scores (id, user, guild, points) VALUES (#id, #user, #guild, #points);");
client.removeScore = sql.prepare("DELETE FROM scores WHERE user=?");
});
client.on('message', message => {
if (!message.content.startsWith(auth.prefix) || message.author.bot) return;
const args = message.content.slice(auth.prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
switch (command) {
case 'ping':
client.commands.get('ping').execute(message, args);
break;
case 'mimic':
client.commands.get('mimic').execute(message, args);
break;
case 'add_role':
client.commands.get('add_role').execute(message, args);
break;
case 'remove_role':
client.commands.get('remove_role').execute(message, args);
break;
case 'bl_add_point':
if (message.member.roles.some(r=>["Fight Officiator"])) {
let score;
let member = message.mentions.members.first() || client.members.get(args[0]);
score = client.getScore.get(member.id, member.guild.id);
if (!score) {
score = { id: `${member.guild.id}-${member.id}`, user: member.username, guild: member.guild.id, points: 0}
}
score.points ++;
client.setScore.run(score);
message.channel.send(`Looks like ${member} got a win! Good one.`);
} else {
message.channel.send(`Sorry, this is only usable by GFOs.`);
};
break;
case '!bl_delete':
if (message.member.roles.some(r=>["Fight Officiator"])) {
let member = message.mentions.users.first();
client.removeScore.run(`${member.guild.id}-${member.id}`)
message.channel.send(`${member} has been set to zero on the leaderboard!`);
} else {
message.channel.send(`Sorry, this is only usable by GFOs.`);
};
break;
case 'bl':
const top5 = sql.prepare("SELECT * FROM scores WHERE guild = ? ORDER BY points DESC LIMIT 5;").all(message.guild.id);
const battleleaderboard = new Discord.RichEmbed()
.setColor('#FFD700')
.setTitle('The Battle Leaderboard - Current Rankings')
.setAuthor(`RankBot`)
.setDescription('The top fighters are displayed here.')
.setTimestamp()
.setFooter(`DM a Gang Fight Officiator to set up a spar with another member and possibly get your name registered onto RankBot's leaderboard!`);
for (const data of top5) {
battleleaderboard.addField(client.users.get(data.user), `${data.points} Win(s)`);
}
message.channel.send(battleleaderboard);
break;
};
});
client.login(auth.token);
I'm creating a bot that should be pretty simple:
The bot is a RankBot (at least that's what i dubbed it as), which is supposed to track the amount of wins in battles (since this is for a discord about a fighting game) using a special role that manually increments those wins with a command, then being able to pull up a leaderboard embed showing the people with the most wins. I'm testing it in a discord separate from the one it's for with a friend, and it seemingly worked until we commanded the bot to open the leaderboard. Nothing was shown. We thought it was strange, since it worked before when only one user was in the database, and I went to the PowerShell Command Line to see if there was an error message, and this showed up.
C:\Users\USER\Documents\OF_RankBot\bot.js:89
battleleaderboard.addField(client.users.get(data.user).tag || client.members.get(data.user).tag, `${data.points} Win(s)`);
^
TypeError: Cannot read property 'tag' of undefined
We were confused by what happened, so I removed the tag part of the command and used it again. The embed showed up this time, but it looked like this.
I assumed that what went wrong was that since they both had the same number of wins listed, the part of the bl command that sorts the users was confused. I then went and used bl_add_point on me and tried again. The near exact same embed was shown.
My guess as to what went wrong was that I messed up at some point when setting up the bl_add_point command, but I'm not sure how to fix the issue.
This isn't part of the main problem, but I can't seem to get bl_delete working either. No errors are shown when I use it. In fact, seemingly nothing happens. I'm not sure if these issues are connected, but I really only need the main issue fixed.
Thanks in advance.
edit: I found out partially what happened with the bl_delete issue, which was I simply put the prefix into the case when the prefix was already defined. Now when I put in the command, the PowerShell responds with:
C:\Users\USER\Documents\OF_RankBot\bot.js:72
client.removeScore.run(`${member.guild.id}-${member.id}`)
^
TypeError: Cannot read property 'id' of undefined

Paypal Php Sdk - NotifyUrl is not a fully qualified URL Error

I have this code
$product_info = array();
if(isset($cms['site']['url_data']['product_id'])){
$product_info = $cms['class']['product']->get($cms['site']['url_data']['product_id']);
}
if(!isset($product_info['id'])){
/*
echo 'No product info.';
exit();
*/
header_url(SITE_URL.'?subpage=user_subscription#xl_xr_page_my%20account');
}
$fee = $product_info['yearly_price_end'] / 100 * $product_info['fee'];
$yearly_price_end = $product_info['yearly_price_end'] + $fee;
$fee = ($product_info['setup_price_end'] / 100) * $product_info['fee'];
$setup_price_end = $product_info['setup_price_end'] + $fee;
if(isset($_SESSION['discountcode_amount'])){
$setup_price_end = $setup_price_end - $_SESSION['discountcode_amount'];
unset($_SESSION['discountcode_amount']);
}
$error = false;
$plan_id = '';
$approvalUrl = '';
$ReturnUrl = SITE_URL.'payment/?payment_type=paypal&payment_page=process_agreement';
$CancelUrl = SITE_URL.'payment/?payment_type=paypal&payment_page=cancel_agreement';
$now = $cms['date'];
$now->modify('+5 minutes');
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
$cms['options']['plugin_paypal_clientid'], // ClientID
$cms['options']['plugin_paypal_clientsecret'] // ClientSecret
)
);
use PayPal\Api\ChargeModel;
use PayPal\Api\Currency;
use PayPal\Api\MerchantPreferences;
use PayPal\Api\PaymentDefinition;
use PayPal\Api\Plan;
use PayPal\Api\Patch;
use PayPal\Api\PatchRequest;
use PayPal\Common\PayPalModel;
use PayPal\Api\Agreement;
use PayPal\Api\Payer;
use PayPal\Api\ShippingAddress;
// Create a new instance of Plan object
$plan = new Plan();
// # Basic Information
// Fill up the basic information that is required for the plan
$plan->setName($product_info['name'])
->setDescription($product_info['desc_text'])
->setType('fixed');
// # Payment definitions for this billing plan.
$paymentDefinition = new PaymentDefinition();
// The possible values for such setters are mentioned in the setter method documentation.
// Just open the class file. e.g. lib/PayPal/Api/PaymentDefinition.php and look for setFrequency method.
// You should be able to see the acceptable values in the comments.
$setFrequency = 'Year';
//$setFrequency = 'Day';
$paymentDefinition->setName('Regular Payments')
->setType('REGULAR')
->setFrequency($setFrequency)
->setFrequencyInterval("1")
->setCycles("999")
->setAmount(new Currency(array('value' => $yearly_price_end, 'currency' => $cms['session']['client']['currency']['iso_code'])));
// Charge Models
$chargeModel = new ChargeModel();
$chargeModel->setType('SHIPPING')
->setAmount(new Currency(array('value' => 0, 'currency' => $cms['session']['client']['currency']['iso_code'])));
$paymentDefinition->setChargeModels(array($chargeModel));
$merchantPreferences = new MerchantPreferences();
// ReturnURL and CancelURL are not required and used when creating billing agreement with payment_method as "credit_card".
// However, it is generally a good idea to set these values, in case you plan to create billing agreements which accepts "paypal" as payment_method.
// This will keep your plan compatible with both the possible scenarios on how it is being used in agreement.
$merchantPreferences->setReturnUrl($ReturnUrl)
->setCancelUrl($CancelUrl)
->setAutoBillAmount("yes")
->setInitialFailAmountAction("CONTINUE")
->setMaxFailAttempts("0")
->setSetupFee(new Currency(array('value' => $setup_price_end, 'currency' => $cms['session']['client']['currency']['iso_code'])));
$plan->setPaymentDefinitions(array($paymentDefinition));
$plan->setMerchantPreferences($merchantPreferences);
// ### Create Plan
try {
$output = $plan->create($apiContext);
} catch (Exception $ex){
die($ex);
}
echo $output->getId().'<br />';
echo $output.'<br />';
Been working with paypal php sdk for some days now and my code stop working.
So i went back to basic and i am still getting the same damn error.
I am trying to create a plan for subscription but getting the following error:
"NotifyUrl is not a fully qualified URL"
I have no idea how to fix this as i dont use NotfifyUrl in my code?
Could be really nice if anyone had an idea how to fix this problem :)
Thanks
PayPal did a update to their API last night which has caused problem within their SDK.
They are sending back null values in their responses.
I MUST stress the error is not on sending the request to PayPal, but on processing their response.
BUG Report : https://github.com/paypal/PayPal-PHP-SDK/issues/1151
Pull Request : https://github.com/paypal/PayPal-PHP-SDK/pull/1152
Hope this helps, but their current SDK is throwing exceptions.
Use below simple fix.
Replace below function in vendor\paypal\rest-api-sdk-php\lib\PayPal\Api\MerchantPreferences.php
public function setNotifyUrl($notify_url)
{
if(!empty($notify_url)){
UrlValidator::validate($notify_url, "NotifyUrl");
}
$this->notify_url = $notify_url;
return $this;
}
If you get the same error for return_url/cancel_url, add the if condition as above.
Note: This is not a permanent solution, you can use this until getting the update from PayPal.
From the GitHub repo for the PayPal PHP SDK, I see that the error you mentioned is thrown when MerchantPreferences is not given a valid NotifyUrl. I see you're setting the CancelUrl and ReturnUrl, but not the NotifyUrl. You may simply need to set that as well, i.e.:
$NotifyUrl = (some url goes here)
$obj->setNotifyUrl($NotifyUrl);
Reason behind it!
error comes from.
vendor\paypal\rest-api-sdk-php\lib\PayPal\Validation\UrlValidator.php
line.
if (filter_var($url, FILTER_VALIDATE_URL) === false) {
throw new \InvalidArgumentException("$urlName is not a fully qualified URL");
}
FILTER_VALIDATE_URL: according to this php function.
INVALID URL: "http://cat_n.domain.net.in/"; // IT CONTAIN _ UNDERSCORE.
VALID URL: "http://cat-n.domain.net.in/"; it separated with - dash
here you can dump your url.
vendor\paypal\rest-api-sdk-php\lib\PayPal\Validation\UrlValidator.php
public static function validate($url, $urlName = null)
{
var_dump($url);
}
And then check this here: https://www.w3schools.com/PHP/phptryit.asp?filename=tryphp_func_validate_url
you can check here what character will reason for invalid.

WCF-project will not return data with 64-bit Win Vista and VS2010

I thought I found the solution to my problem when I found this, but it didn't work for me.
When I run in debug mode, my WcfTestClient does not retrieve any data and I receive the error:
A first chance exception of type 'System.NotSupportedException' occurred in System.Data.Entity.dll
The thread '<No Name>' (0x1b50) has exited with code 0 (0x0).
The program '[7040] WCFTestClient.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).....................................
What WILL retrieve data is the following method:
public List<WShortDeal> Test()
{
try
{
return entities.ProductInstance_Deal
.Select(d => new WShortDeal()
{
Id = d.Deal.Id
// ,
// Name = d.Deal.Deal_Language.SingleOrDefault(l => l.Language.Id == 1).Name**
,
NewPrice = (double)d.ProductInstance.Price * (1 - d.Deal.SalesPercentage / 100)
,
OldPrice = (double)d.ProductInstance.Price
,
Valuta = d.ProductInstance.Valuta.ValutaCode
,
Type = d.Deal.Type
,
IdCompanyAccount = d.ProductInstance.IdCompanyAccount
})
.ToList();
}
catch (Exception)
{
return null;
}
}
If I uncomment the two lines that are now commented out, though, I stop receiving data and receive the error message mentioned above in my output window.
Also if I add this line
,ProductCategory = d.ProductInstance.ProductType.ProductCategory.ProductCategory_Language.Where(pcl => pcl.IdLanguage == idLanguage).Single().Name
instead of the line
, Name = d.Deal.Deal_Language.SingleOrDefault(l => l.Language.Id == 1).Name
to my original SELECT-statement, it will also return no data. So I guess maybe it has something to do with all the tables that represent the many-to-many-relationship with my Language-table(??). Because whenever I forget about the join with the "ProductCategory_Language"-table, I can retrieve data again.
Could someone please help? Is there another solution for my problem? I've been struggling with this problem for days now :(
Thanks in advance.
What if the line returns a null before selecting the name?
Try
Name = d.Deal.Deal_Language.Where(l => l.Language.Id == 1)
.Select(s=>s.Name).SingleOrDefault()