I have a grid where I need to have some filters in.
Actually I have only 2 parameters available but the thing is that I will have maybe 5/6/7 or even more and I need a good way to manage it in my json encoding.
I manage it by this way :
if(!empty($_GET['q']) && empty($_GET['s'])) {
$client = $_GET['q'];
$requeteDevis = myPDO::getInstance()->prepare(<<<SQL
SELECT SC_libelle, ETP_libelle, DVS_numDevis, DVS_libelle, DVS_montant, DVS_statut, DVS_pourcent, DVS_montant,
USR_Nom, USR_Prenom, CTC_Nom, CTC_Prenom, ctc.idContact, DVS_date
FROM Utilisateur usr, Devis dvs, SiteClient sc, Client clt, Contact ctc, Entreprise etp
WHERE usr.idEntreprise = etp.idEntreprise
AND usr.idUtilisateur = dvs.idUtilisateur
AND dvs.idSiteClient = sc.idSiteClient
AND sc.idClient = clt.idClient
AND dvs.idContact = ctc.idContact
AND clt.CLT_libelle = ?
SQL
);
$requeteDevis->execute(array($client));
} else if (!empty($_GET['s']) && empty($_GET['q'])) {
$stat = $_GET['s'];
$requeteDevis = myPDO::getInstance()->prepare(<<<SQL
SELECT SC_libelle, ETP_libelle, DVS_numDevis, DVS_libelle, DVS_montant, DVS_statut, DVS_pourcent, DVS_montant,
USR_Nom, USR_Prenom, CTC_Nom, CTC_Prenom, ctc.idContact, DVS_date
FROM Utilisateur usr, Devis dvs, SiteClient sc, Client clt, Contact ctc, Entreprise etp
WHERE usr.idEntreprise = etp.idEntreprise
AND usr.idUtilisateur = dvs.idUtilisateur
AND dvs.idSiteClient = sc.idSiteClient
AND sc.idClient = clt.idClient
AND dvs.idContact = ctc.idContact
AND dvs.DVS_statut = ?
SQL
);
$requeteDevis->execute(array($stat));
}
else if ......
So, do you think there is any way to have only one sql statement ? Else it will finish I will have 50 ones :/
Thanks
$cond1 = '';
$cond2 = '';
$cond3 = '';
$var = 2;
if(1==2){
$cond1 = ' AND column1>20';
}
if(3==3){
$cond2 = ' AND column2 < '.$var;
}
$cond3 = ' ORDER BY id DESC';
$baseSQL = "SELECT * FROM table WHERE 1=1 $cond1 $cond2 $cont3";
I have find how to manage it :
Here is the code :
if(empty($_GET['s'])) {
$state = null;
} else $state = $_GET['s'];
if(empty($_GET['q'])) {
$client = null;
} else $client = $_GET['q'];
$requeteDevis = myPDO::getInstance()->prepare(<<<SQL
SELECT SC_libelle, ETP_libelle, DVS_numDevis, DVS_libelle, DVS_montant, DVS_statut, DVS_pourcent, DVS_montant,
USR_Nom, USR_Prenom, CTC_Nom, CTC_Prenom, ctc.idContact, DVS_date
FROM Utilisateur usr, Devis dvs, SiteClient sc, Client clt, Contact ctc, Entreprise etp
WHERE usr.idEntreprise = etp.idEntreprise
AND usr.idUtilisateur = dvs.idUtilisateur
AND dvs.idSiteClient = sc.idSiteClient
AND sc.idClient = clt.idClient
AND dvs.idContact = ctc.idContact
AND (dvs.DVS_statut = :statut OR :statut is null)
AND (clt.CLT_libelle = :client OR :client is null)
SQL
);
$requeteDevis->execute(array(":statut" => $state,
":client" => $client));
So with only one request, you are able to manage every filters. thanks for help tho
Related
I want to know how get this working in laravel:
I have two tables: "orders" and "delivery_boys".
When an order is created I want to get "id" in table "delivery_boys" that correspond to the "store_id" in the "order" table.
which looks like that in mysql
SELECT `id` FROM `delivery_boys` WHERE store_id = '3'
Thanks for your help.
I use this function:
protected $table = 'orders';
public function addNew($data)
{
$user = AppUser::find($data['user_id']);
if(isset($data['address']) && $data['address'] > 0)
{
$address = Address::find($data['address']);
}
else
{
$address = new Address;
}
$add = new Order;
$add->user_id = $data['user_id'];
$add->store_id = $this->getStore($data['cart_no']);
$add->d_boy = $add->?????; <---- here i want to add from "delivery_boys" table the "id" that correspond to the "store_id" added just above from the "order" table ---->
$add->name = $user->name;
$add->email = $user->email;
$add->phone = $user->phone;
$add->address = $address->address;
$add->lat = $address->lat;
$add->lng = $address->lng;
$add->address = $address->address;
$add->d_charges = $this->getTotal($data['cart_no'])['d_charges'];
$add->discount = $this->getTotal($data['cart_no'])['discount'];
$add->total = $this->getTotal($data['cart_no'])['total'];
$add->payment_method = $data['payment'];
$add->payment_id = isset($data['payment_id']) ? $data['payment_id'] : 0;
$add->type = isset($data['otype']) ? $data['otype'] : 1;
$add->notes = isset($data['notes']) ? $data['notes'] : null;
$add->save();
run this before $add = new Order;
$d_boy = DB::table('delivery_boys')
->select('id')
->where('store_id', $this->getStore($data['cart_no']))
->first();
and then add it where you need it:
$add->d_boy = $d_boy->id;
$id= DB::table('delivery_boys')->select('id')->where('store_id', '=', $this->getStore($data['cart_no']))->get();
this is my first post and im really new to php world, Sorry if i use wrong words or terms to describe my problem.
I have a script that was written in php for telegram, and i have two commands that is almost the same.
with this one it is possible to add to multiple groups using this separator ","
/madd
groupid, groupid
this one it is not possible to do
/wadd
groupid
I want to be able to use the second command with a separator between the group ids
I can see in the code how it is written to be able to do that in /madd but I cant figure out how to implement this in /wadd
I will put here the two scripts for the commands, would appreciate any help <3
Thanks.
This is the one with the separator
if(strpos($text,"/madd") === 0){
$e = explode("\n",$text);
if(!isset($e[1]) || !isset($e[2])) exit($bot->sendMessage($user['id'],"/madd\ntelegram_username or ID\ngroup, ids\nmax_posts per day (default 1)\nnumber of reposts (default 0)\n\nAdds new telegram username to the manual autodrop users list.\n\nReplace group_id with * to add to all groups"));
$group = $e[2]; $username = strtolower(ltrim($e[1],"#"));
$addto = [];
if($group == "*"){
$addto = $groups;
}else{
$ex = explode(",",$group);
foreach($ex AS $id){
$id = trim($id);
if(isset($groups[$id])){
$addto[$id] = $groups[$id];
}
}
}
$add = mysqli_fetch_assoc($conn->query("SELECT * FROM utenti WHERE username LIKE '%".mysqli_real_escape_string($conn,$username)."%'"));
if(!isset($add['id'])){
$add = mysqli_fetch_assoc($conn->query("SELECT * FROM utenti WHERE id = ".mysqli_real_escape_string($conn,$username)));
}
if(!isset($add['id'])){ exit($bot->sendMessage($user['id'],"😔 User $username not found! They need to start the bot, or send a simple message in one of the groups.")); }
$result = "❕ <b>Selected User:</b> <a href='tg://user?id=".$add['id']."'>".$add['username']." (".$add['id'].")</a>";
$manual = [
'max_posts' => $e[3] ?? 1,
'reposts' => $e[4] ?? 0,
'groups' => []
];
foreach($addto AS $id => $r){
$manual['groups'][] = $r['group_id'];
}
$conn->query("UPDATE utenti SET manual = '".mysqli_real_escape_string($conn,json_encode($manual,true))."' WHERE id = ".$add['id']);
$bot->sendMessage($user['id'],$result."\n\n".json_encode($manual,JSON_PRETTY_PRINT));
exit();
}
and this is without the separator
if(strpos($text,"/wadd") === 0){
$e = explode("\n",$text);
if(!isset($e[1]) || !isset($e[2])) exit($bot->sendMessage($user['id'],"/wadd\ngroup_id\ntelegram_username or ID\nmax_posts per day (default 5)\nnumber of reposts (default 0)\n\nAdds new telegram username to the whitelisted users list.\n\nReplace group_id with * to add to all groups"));
$group = $e[1]; $username = strtolower(ltrim($e[2],"#"));
if($group != "*" && !isset($groups[$group])) exit($bot->sendMessage($user['id'],"👥 <b>Group $group</b> not whitelisted."));
$add = mysqli_fetch_assoc($conn->query("SELECT * FROM utenti WHERE username LIKE '%".mysqli_real_escape_string($conn,$username)."%'"));
if(!isset($add['id'])){
$add = mysqli_fetch_assoc($conn->query("SELECT * FROM utenti WHERE id = ".mysqli_real_escape_string($conn,$username)));
}
if(!isset($add['id'])){ exit($bot->sendMessage($user['id'],"😔 User $username not found! They need to start the bot, or send a simple message in one of the groups.")); }
$result = "❕ <b>Selected User:</b> <a href='tg://user?id=".$add['id']."'>".$add['username']." (".$add['id'].")</a>";
$premiums = json_decode($add['premiums'],true);
if(!is_array($premiums)) $premiums = [];
$groups_to_update = []; if($group == "*"){ foreach($groups AS $group => $data){ $groups_to_update[] = $group; } }else{ $groups_to_update[] = "-".abs($group); }
$max_posts = $e[3] ?? 5; $reposts = $e[4] ?? 0;
foreach($groups_to_update AS $group_id){
if(isset($premiums[$group_id])){
if($premiums[$group_id]['max_posts'] == $max_posts && $premiums[$group_id]['reposts'] == $reposts){
$result.="\n\n🕐 <i>No changes for group</i> <code>$group_id</code>";
}else{
$result.="\n\n♻️ <b>Updated</b> for group <code>$group_id</code>\nMax. Posts: $max_posts | Reposts: $reposts";
$premiums[$group_id] = ['max_posts' => $max_posts,'reposts' => $reposts];
}
}else{
$result.="\n\n➕ <b>Added</b> for group <code>$group_id</code>\nMax. Posts: $max_posts | Reposts: $reposts";
$premiums[$group_id] = ['max_posts' => $max_posts,'reposts' => $reposts];
}
}
$conn->query("UPDATE utenti SET premiums = '".mysqli_real_escape_string($conn,json_encode($premiums,true))."' WHERE id = ".$add['id']);
$bot->sendMessage($user['id'],$result);
exit();
}
I'm having an issue preparing a SQL statement:
$statement = $conexion->prepare(
'SELECT * FROM celulares
WHERE (MARCA = :marca )
AND
(CATEGORIA = :categoria1 OR CATEGORIA = :categoria2 OR CATEGORIA = :categoria3)
AND
(CATEGORIA2 = :categoria1 OR CATEGORIA2 = :categoria2 OR CATEGORIA2= :categoria3)
AND
(CATEGORIA3 = :categoria1 OR CATEGORIA3 = :categoria2 OR CATEGORIA3 = :categoria3)');
Giving placeholders values with this:
$statement->execute(array(':categoria1' => $categoria1,
':categoria2' => $categoria2,
':categoria3' => $categoria3,
':marca' => $query
));
$query value may variate when my application begins depending on some results:
if ($entrada == "LG") {
if ($query == "") {
$query = "LG";
} else {
$query = $query . ' OR MARCA = "LG" ';
}
}
if ($entrada == "APPLE") {
if ($query == "") {
$query = "APPLE";
} else {
$query = $query . ' OR MARCA = "APPLE" ';
}
}
if ($entrada == "HUAWEI") {
if ($query == "") {
$query = "HUAWEI";
} else {
$query = $query . ' OR MARCA = "HUAWEI" ';
}
}
I tried a lot of things, but none of those worked out it returns an empty array, the only one who works was changing this line of my prepared statement:
WHERE (MARCA = :marca OR MARCA = :marca2 OR MARCA = :marca3 )
And as many "MARCA" as results, i think it's not the best way to do it
UPDATED:
Now trying with IN Statement in my Query (Thanks you all for helping me)
Now it looks like:
$marcas = array("LG", "HUAWEI"); (Static values for test)
$inQuery = implode(',', array_fill(0, count($marcas), '?'));
$statement = $conexion->prepare(
'SELECT * FROM celulares
WHERE (MARCA = IN (' . $inQuery . '))
AND
(CATEGORIA = :categoria1 OR CATEGORIA = :categoria2 OR CATEGORIA = :categoria3)
AND
(CATEGORIA2 = :categoria1 OR CATEGORIA2 = :categoria2 OR CATEGORIA2= :categoria3)
AND
(CATEGORIA3 = :categoria1 OR CATEGORIA3 = :categoria2 OR CATEGORIA3 = :categoria3)');
foreach ($marcas as $k => $marca) {
$statement->bindValue(($k+1), $marca);
}
$statement->bindValue(':categoria1', $categoria1);
$statement->bindValue(':categoria2', $categoria2);
$statement->bindValue(':categoria3', $categoria3);
$statement->execute();
Getting: Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters
Trying to fix it
You can simplify your query:
SELECT * FROM celulares
WHERE (MARCA = :marca )
AND (:categoria1,:categoria2,:categoria3)
IN (
(CATEGORIA,CATEGORIA2,CATEGORIA3),
(CATEGORIA,CATEGORIA3,CATEGORIA2),
(CATEGORIA2,CATEGORIA,CATEGORIA3),
(CATEGORIA2,CATEGORIA3,CATEGORIA),
(CATEGORIA3,CATEGORIA,CATEGORIA2),
(CATEGORIA3,CATEGORIA2,CATEGORIA)
)
This way you only pass in the categories once, and compare it against the six possible permutations of three categories.
That being said, this is a sign that your database is in very poor shape. Generally speaking having any kind of "column2", "column3" system is a sign that you need to restructure your database - the kind of queries you end up with, like the above, are only going to get worse.
Specifically, in this case, just adding CATEGORIEA4 would increase the amount of permutations you need to define from 6 to 24!!
EDIT: I completely missed the part about :marca and IN - I was too focussed on the bad state of the database with regard to categories, sorry!
Well, i fix it, probably it's not the best way to solve it but i have this now:
I fill array with entries from POST
$query = array();
$index = 0;
foreach ($_POST as $entrada) {
switch($entrada) {
case "SAMSUNG":
$query[] = "SAMSUNG";
break;
case "LG":
$query[] = "LG";
break;
case "APPLE":
$query[] = "APPLE";
break;
case "HUAWEI":
$query[] = "HUAWEI";
break;
}
}
$inQuery = str_repeat('?,', count($query) - 1) . '?';
Here's my new query: Problem was that i was mixing "?" with placeholders (:) which not is recommended
$statement = $conexion->prepare(
"SELECT * FROM celulares
WHERE ( MARCA IN($inQuery))
AND
(CATEGORIA = ? OR CATEGORIA = ? OR CATEGORIA = ?)
AND
(CATEGORIA2 = ? OR CATEGORIA2 = ? OR CATEGORIA2= ?)
AND
(CATEGORIA3 = ? OR CATEGORIA3 = ? OR CATEGORIA3 = ?)");
Then i bindValues like that
$c = 0;
foreach ($query as $q => $queries) {
$c++;
$statement->bindValue(($q+1), $queries);
}
$statement->bindValue($c+1, $categoria1);
$statement->bindValue($c+2, $categoria2);
$statement->bindValue($c+3, $categoria3);
$statement->bindValue($c+4, $categoria1);
$statement->bindValue($c+5, $categoria2);
$statement->bindValue($c+6, $categoria3);
$statement->bindValue($c+7, $categoria1);
$statement->bindValue($c+8, $categoria2);
$statement->bindValue($c+9, $categoria3);
$statement->execute();
$resultados = $statement->fetchAll();
I did many test with a lot of querys and it's working fine, probably it's a "dirty" solution but i'll continue learning
Thanks u all for helping me!
Customer Orders not being bound to Customer
Postby DrFeeling » Mon Jun 01, 2015 4:05 pm
Good Afternoon peeps, I'm currently developping a mobile app for opencart that will bridge both tecnologies.
Most of the stuff is already active but I have a problem regarding order histories.
So, when you purchase something, through the main site, the default template of opencart, it generates a order history, that you can see through the website (my orders) or through the admin page.
My problem is that, whenever someone purchases something from the app, the orders of that costumer arent uptaded.
Though they appear in the main admin window (the dashboard) , once you go to customer (sales -> customers -> customers) the order made by the app isnt listed in the myOrders part of that customer, making both the "my previous orders" and the order of that customer inexistent in that place, but they appear in the dashboard and the notification email is foward to the customer
Please help me, and thanks for the support :D
Only order 261 (which was made in the website) is bounded to its customer, the others arent, as you can see in the pic below
AM I missing a parameter or a validation when the checkout process happens?
http://s16.postimg.org/y2h9rg5fp/image.jpg
EDIT: My code to create a order:
public function end_order() {
if ($this->customer->isLogged() == true){
$data= array();
$datap = array();
$this->load->model('account/customer');
$this->load->model('quickcheckout/order');
$this->load->model('checkout/order');
$myArray = $_POST["formData"];
$treatedArray = array();
foreach($myArray as $value) {
$treatedArray[$value['name']] = $value['value'];
}
$email = $_POST["email"];
$delivery = $_POST["deladdress"];
$delivery = array_shift($delivery); // sobe um nivel as posiçoes do array, em vez de usar $array[0]['bla'] , usasse so $array['bla']
$data2 = array();
$data2 = $this->model_account_customer->getCustomerByEmail($email);
$Method = $_POST["PayMethod"];
$TotalCheckout = $_POST["TotalCheck"];
$IP = $_POST["IP"];
$Agent = $_POST["User"];
$Products = $_POST["Prod"];
$length = count($Products);
for ($i = 0; $i < $length; $i++) {
(int)$datap[$i]['product_id'] = $Products[$i]['Id'];
$datap[$i]['name'] = $Products[$i]['Name'];
$datap[$i]['model'] = $Products[$i]['modelo'];
(int)$datap[$i]['quantity'] = $Products[$i]['NItems'];
$datap[$i]['price'] = $Products[$i]['Preco'];
$datap[$i]['total'] = $Products[$i]['Total'];
$datap[$i]['tax'] = 0; //$Products[$i]['Tax'];
(int)$datap[$i]['reward'] = 0; //$Products[$i]['Reward'];
}
$url = $myurl;
$data['invoice_prefix'] = $this->config->get('config_invoice_prefix');
$data['store_id'] = $this->config->get('config_store_id');
$data['store_name'] = "Loja Teste";
$data['store_url'] = $url;
$data['firstname'] = $data2['firstname'] ;
$data['lastname'] = $data2['lastname'];
$data['email'] = $data2['email'];
$data['telephone'] = $data2['telephone'];
$data['fax'] = $data2['fax'];
$data['payment_firstname'] = $delivery['firstname'];
$data['payment_lastname'] = $delivery['lastname'];
$data['payment_company'] = $delivery['company'];
$data['payment_company_id'] = $delivery['company_id'];;
$data['tax_id'] = $delivery['tax_id'];
$data['payment_address_1'] = $delivery['address_1'];
$data['payment_address_2'] = $delivery['address_2'];
$data['payment_city'] = $delivery['city'];
$data['payment_postcode'] = $delivery['postcode'];
$data['payment_country'] = $delivery['country'];
$data['payment_country_id'] = $delivery['country_id'];
$data['payment_zone'] = $delivery['zone'];
$data['payment_zone_id'] = $delivery['zone_id'];
$data['payment_method'] = "Cash On Delivery";
$data['payment_code'] = 1;
$data['total'] = $TotalCheckout;
//NOTA: esta duas variaveis abaixo servem para tratar dos preços, alterar depois para quando a loja tiver opçoes de escolher preços
$data['language_id'] = (int)$this->config->get('config_language_id');
$data['accept_language'] = $this->request->server['HTTP_ACCEPT_LANGUAGE'];
$data['currency_id'] = (int)2;
$data['currency_code'] = "USD";
$data['currency_value'] = (float)1.00000000;
$data['ip'] = $IP;
$data['forwarded_ip'] = $IP;
$data['user_agent'] = $Agent;
$data['products'] = $datap;
(int)$order = $this->model_checkout_order->addOrder($data);
$this->model_checkout_order->confirm($order, 1 , $comment = '', $notify = false);
echo ("teste");
}
}
I use Yii, and I get this error; What should I understand and do?
Not a duplicate of: source or any other;
error is at: ->bindParam(":url_id", $url->id)
$url = Url::model()->findByAttributes(array('link' => $_url));
if (empty($url)) {
$url = new Url();
$url->website_id = $website->id;
$url->link = $_url;
$url->title = '';
$url->description = '';
$url->doctype = $_doctype;
$url->visits = 1;
$url->created = date('Y-m-d h:i:s',time());
$url->updated = date('Y-m-d h:i:s',time());
$url->status = 1;
$url->save(false);
} else {
// update visits
$url->saveCounters(array('visits' => 1));
// url existed, let's load products
if (!Yii::app()->user->isGuest) {
$sql = "select u.id from url as u
left join url_follower as u_f
on u.id = u_f.url_id and u_f.user_id = :user_id
where u.id =:url_id";
$cmd = Yii::app()->db->createCommand($sql)
->bindParam(":url_id", $url->id)
->bindParam(":user_id", Yii::app()->user->id);
$url_id = $cmd->queryScalar();
The solution, tested:
$user_id = Yii::app()->user->id;
$url_id = $url->id;
$cmd = Yii::app()->db->createCommand($sql)
->bindParam(":user_id", $user_id)
->bindParam(":url_id", $url_id);