How to check a value of a variable and call different function - php

I have the following variables in my cart.php file:
<?php $readyTotal = $qty*price ?>;
Now I want to do is that if the $readyTotal > $1000 then call a file which is adding an item into the customer's cart.
($slq= msyql_query("INSERT into `table`.....value.....");
and if the value of $radyTotal < $1000;
dont add any extra item or if it has been added just remove it by calling the removal file.
($sql =mysql_query("DELETE from `table` where .......");
Please note that how to do this I want to call/include the files in my cart.php file. but i am unable to do this. is there any other way to do it or by using ajax/jquery which check every the value of $readyTotal every time when it changes.
function ad(){
$signature =getSignature();
$item = 21;
$type = 100;
$type= 0;
$sql2 = mysql_query("Select * From `temp` where `item`='$item' AND `price`= 0 AND
`signature`='$signature' AND `type`=0 AND `toppings`=0 " );
$count= mysql_num_rows($sql2);
if($count ==0){
$sql = mysql_query("INSERT INTO `temp`
(`item`,`price`,`signature`,`type`,`toppings`, `isCoupon`)
VALUES
('$item','$type','$signature','0','0', '1')");
}
}
function removeMe(){
mysql_query("DELETE FROM `temp` WHERE `item`=21 AND `signature`='".getSignature()."'");
}
When I try the above function individual file it works fine, but when i use both in it does not woks please.... what is wrong with this...

<?php
include_once("customfunctionfile.php");
$object = new quiz;
$readyTotal = $qty*price ;
if($readyTotal > 1000){
$object->ad();
}else{
$object->removeMe();
}
?>;
customfunctionfile.php
class quiz{
function ad(){
$signature =getSignature();
$item = 21;
$type = 100;
$type= 0;
$sql2 = mysql_query("Select * From `temp` where `item`='$item' AND `price`= 0 AND
`signature`='$signature' AND `type`=0 AND `toppings`=0 " );
$count= mysql_num_rows($sql2);
if($count ==0){
$sql = mysql_query("INSERT INTO `temp`
(`item`,`price`,`signature`,`type`,`toppings`, `isCoupon`)
VALUES
('$item','$type','$signature','0','0', '1')");
}
}
function removeMe(){
mysql_query("DELETE FROM `temp` WHERE `item`=21 AND
`signature`='".getSignature()."'");
}
}

You can achieve this something like this using functions without including file.
<?php
$readyTotal = $qty*price;
if($readyTotal > 1000) //considering amount in $
{
addItemToCart($cartDetails) // call function to add item into the cart
}
else {
removeItemFromCart($cartDetails) //call function to remove item from cart
}
?>
Define functions addItemToCart and removeItemFromCart to fire your queries.

Related

Is there a way to update 12000+ rows from txt file in less then 2mins?

I need to update a table with more then 12000 row using php Codeigniter and a txt file.. reading the file and the foreach loop are fine but when updating line by line it takes like 30 mins, I guess the problem is I'm searching by name because I have no id in the txt file...
Here is my code:
controller:
$fn = fopen($this->upload->data('full_path'),"r");
$update = true;
while(! feof($fn) && $update) {
$pieces = explode("|", fgets($fn));
if(sizeof($pieces) == 9 && is_numeric(trim($pieces[1]))) {
$update = $this->model_products->update3s($pieces);
}
}
fclose($fn);
Model:
public function update3s($product) {
if ($product) {
$product[2] = trim(str_replace("'","''",$product[2]));
$product[1] = trim($product[1]);
$product[6] = trim($product[6]);
$product[3] = trim($product[3]);
$sql = "UPDATE products set qty = $product[3], price_vente = $product[6] where (name = '$product[2]')";
echo $sql.'<br>';
$update = $query = $this->db->query($sql);
return $update;
}
return false;
}
You can use transaction and add index for column name in database table.
$fn = fopen($this->upload->data('full_path'),"r");
$update = true;
$updatedCount = 0;
while(! feof($fn) && $update) {
$pieces = explode("|", fgets($fn));
if(sizeof($pieces) == 9 && is_numeric(trim($pieces[1]))) {
if ($updatedCount == 0) {
$databaseInstance->beginTransaction();
}
$update = $this->model_products->update3s($pieces);
++$updatedCount;
if ($updatedCount > 500) { //in one transaction update 500 rows
$databaseInstance->commit();
$updatedCount = 0;
}
}
}
if ($updatedCount > 0) { // if we have not commited transaction
$databaseInstance->commit();
}
fclose($fn);
Some tips
Add index to field name
Use prepared statements
Disable the MySQL forgeign key check Read more
writing sql function can do that even in much lesser time .
using feature like :
REPLACE()
cursors
SPLIT_STRING(custom)
in a mysql user defined function
CREATE FUNCTION update3s(hole_file_content LONGTEXT) RETURNS Boolean
BEGIN
-----Your implementation(same logic in sql ) ------
END
then coll it just by if it is CI 3
$this->db->call_function('update3s', file_get_contents($this->upload->data('full_path')));
else
$this->db->query("select update3s(".file_get_contents($this->upload->data('full_path')).")");

MySQL insert not working, syntax seems okay with phpMyAdmin

I am working with the following php syntax:
$sqlgo = "INSERT INTO invoice_qtydisc (`invoice_id`,`name`,`description`,`price`,`qty`,`discount`,`created`,`created_by`) VALUES ('$invoice_id','$product','$description','$price','$qty','$discount',NOW(),'$update_id')";
$dbconnect->query($sqlgo);
When PHP performed the code above, nothing being inserted into the db but when I echo $sqlgo and performed it in phpMyAdmin, everything seems to be fine. Here's the echo sample of the sql:
INSERT INTO invoice_qtydisc (`invoice_id`,`name`,`description`,`price`,`qty`,`discount`,`created`,`created_by`) VALUES ('118','Sport Socks','','20.00','1','0',NOW(),'1')
Did I miss anything? Hold on .. lemme paste the whole for loop just in case:
$item_maintain = array();
$test = 0;
$sqlgo = "";
for($i=0;$i<count($invoice_product);$i++) {
if(!empty($invoice_product[$i])) {
$product = addslashes($invoice_product[$i]);
$description = addslashes($invoice_product_desc[$i]);
$qty = trim($invoice_product_qty[$i]);
$price = trim($invoice_product_price[$i]);
if (!$invoice_product_discount[$i]) {
$discount = 0;
} else {
$discount = trim($invoice_product_discount[$i]);
}
if (!empty($item_current[$i])) {
$dbconnect->query("UPDATE invoice_qtydisc SET name='$product', description='$description', price='$price', qty='$qty', discount='$discount', updated=NOW(), updated_by='$update_id' WHERE id='$item_current[$i]'");
array_push($item_maintain, $item_current[$i]);
} else {
$sqlgo = "INSERT INTO invoice_qtydisc (`invoice_id`,`name`,`description`,`price`,`qty`,`discount`,`created`,`created_by`) VALUES ('$invoice_id','$product','$description','$price','$qty','$discount',NOW(),'$update_id')";
$dbconnect->query($sqlgo);
$dbconnect->query("INSERT INTO pin_board (title,message) VALUES ('title here','message here')");
$test++;
}
}
}
The 2nd insert line into table "pin_board" worked flawlessly though.

How to pass variables in function from a variable

I have a problem with creating a query through a function (all others variables works correctly) I have a function that doesn't print variables correctly (exactly $NomiFarmacie and $day)
//The problem is present in this function
function Cicla($Periodo, $FarmacieRiordinate, $Query) {
global $tabella_calendario, $count; //them works
foreach ($Periodo as $giorno) {
$day = $giorno->format("Y-m-d");
$NomiFarmacie = addslashes($FarmacieRiordinate[$count % count($FarmacieRiordinate)]);
echo $NomiFarmacie; echo $day; //Both are correct
print_r($Query); //Queries are not completed correctly. OUTPUT Below
$count++;
}
}
$FarmacieRiordinate = $_POST['elementi'];
$DataIniziale = $_POST['data1'];
$DataFinale = $_POST['data2'];
$Query = ("UPDATE $tabella_calendario SET Farmacia='$NomiFarmacie' WHERE Data='$day'");
Cicla(CalcolaPeriodo($DataIniziale, $DataFinale), $FarmacieRiordinate, $Query);
A PORTION OF OUTPUT print_r($Query)
UPDATE calendario SET Farmacia='Array' WHERE Data='1546297200'
UPDATE calendario SET Farmacia='Array' WHERE Data='1546297200'
UPDATE calendario SET Farmacia='Array' WHERE Data='1546297200'
UPDATE calendario SET Farmacia='Array' WHERE Data='1546297200'
The problem is your $Query already be combined as string BEFORE passed into your function.
You can use vsprintf in this case.
function Cicla($Periodo, $FarmacieRiordinate, $Query) {
global $tabella_calendario, $count; //them works
foreach ($Periodo as $giorno) {
$day = $giorno->format("Y-m-d");
$NomiFarmacie = addslashes($FarmacieRiordinate[$count % count($FarmacieRiordinate)]);
echo $NomiFarmacie; echo $day; //Both are correct
$realQuery = vsprintf($Query, array($NomiFarmacie, $day));
print_r($realQuery); //Queries are not completed correctly. OUTPUT Below
$count++;
}
}
$FarmacieRiordinate = $_POST['elementi'];
$DataIniziale = $_POST['data1'];
$DataFinale = $_POST['data2'];
$Query = ("UPDATE $tabella_calendario SET Farmacia='%s' WHERE Data='%s'");
Cicla(CalcolaPeriodo($DataIniziale, $DataFinale), $FarmacieRiordinate, $Query);
You can read more about vsprintf here:
http://php.net/manual/en/function.vsprintf.php
.

Update data array in the same row

I would like to approve leave application based on dates for example as below :
echo "<select name='app_status[]' required>
<option value='' selected>Pending</option>
<option value='1'>Approve</option>
<option value='2'>Reject</option></select>";
$app_status = array();
if(is_array($app_status)) {
foreach($_POST['app_status'] as $key1=>$value1) {
$app_status[]=$value1;
}
}
for($loop = 0; $loop < count($app_status); $loop++) {
if($app_status[$loop]=="" || $app_status[$loop]==null)
$error=1;
}
if(isset($error))
$error=1;
else
$error=0;
if($error==0) {
for ($i = 0; $i < count($app_status); $i++) {
$str = $app_status[$i];
$sql= "UPDATE leaves_apply SET app_status ='$str' WHERE app_id='$app_id'";
$query2 = mysqli_query($sql);
}
}
For example if I approve the leaves for 12/8/2017 - 15/8/2017 except for 16/8/2017, I will get an output like this 11112 And when I check the database, the column app_status will only update 2, as if it only read the last data and not the first four data. If possible I would like the data 11112 to be update in the app_status column for app_id no 1357. I'm not sure if this is the right way, please help me as I'm new to this. Thank you.
I think this modification should do what you would like...
if($error==0) {
// Declare the string for the app_status
$str = "";
// Loop though the statuses and put together the statuses
for ($i = 0; $i < count($app_status); $i++) {
$str .= $app_status[$i];
}
// Update the database record
$sql= "UPDATE leaves_apply SET app_status = '$str' WHERE app_id='$app_id'";
$query2 = mysqli_query($sql);
}
Please remember to escape your database queries to prevent SQL injection.

What is wrong with my function?

Here is my code for the function
function multiple_delete($checkbox, $table = 0, $url = 0, $picture1 = 0, $picture2 = 0, $picture3 = 0){
echo $count = count($checkbox);
for( $j=0;$j<$count;$j++)
{
$delete_id = $checkbox[$j];
$query = "SELECT * FROM $table WHERE id = '$delete_id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if( $picture1 !== 0 && $picture2 !== 0 && $picture3 !== 0)
{
$pic_1 = $picture1;
$pic_2 = $picture2;
$pic_3 = $picture3;
unlink($pic_1);
unlink($pic_2);
unlink($pic_3);
continue;
}
if( $picture1 !== 0 && $picture2 !== 0 && $picture3 == 0 )
{
$pic_1 = $picture1;
$pic_2 = $picture2;
unlink($pic_1);
unlink($pic_2);
continue;
}
}
for($i=0;$i<$count;$i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM $table WHERE id='$del_id'";
$result_delete_data = mysql_query($sql);
}
alert('Deleted Successfully');
redirect_url($url);
return true;
}
My Problem is when i call the function using the following code.
#multiple_delete($_POST['checkbox'], 'news', 'news.php', '$row[\'pic_title\']', '$row[\'pic_brief\']', '$row[\'pic_detail\']');
the three array variables $row['pic_title'], $row['pic_brief'], $row['pic_detail'] , does not parse as the value in the function in first for loop, instead it just print the string and hence is not able to fetch the value stored in the database. for example
in the first if condition i have defined 3 variables,
$pic_1 = $picture1;
$pic_2 = $picture2;
$pic_3 = $picture3;
$picture1, $picture2, and $picture3 holds the value that i declared in the function , now when i do something like this echo $pic_1 = $picture1; it prints $row['pic_title'] the exact value which i declared in the function instead of parsing the value which is actually upload/news/title/pic_title1.jpg i tried testing it like this, instead of declaring the value in the defined function i actually just changed the value of the three variables to
$pic_1 = $row['pic_title'];
$pic_2 = $row['pic_brief'];
$pic_3 = $row['pic_detail'];
this works very fine without any problem. why is that variable $picture1 which holds the value $row['pic_title']; refuses to parse it and force it to just print the string while if i change it manually it works? where i am going wrong?
apart from the last three parameters i dont have any problem parsing the first three parameters it works perfectly fine i have tested it in many ways. the only problem i am facing is of the last three parameters
Edit : i tried double quotes, single quotes, and single quotes with double quote with the combination of concatenation operator. without quotes. nothing works.
P.S : thanks in advance
Try this:
function multiple_delete($checkbox, $table, $url, $picture1, $picture2, $picture3){
echo $count = count($checkbox);
for($j=0; $j<$count; $j++)
{
$delete_id = $checkbox[$j];
$query = "SELECT * FROM $table WHERE id = '$delete_id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$pic1 = $row[$picture1];
$pic2 = $row[$picture2];
$pic3 = $row[$picture3];
if(!empty($pic1) && !empty($pic2) && !empty($pic3))
{
unlink($pic1);
unlink($pic2);
unlink($pic3);
}
else if(!empty($pic1) && !empty($pic2))
{
unlink($pic1);
unlink($pic2);
}
$sql = "DELETE FROM $table WHERE id='$delete_id'";
$result_delete_data = mysql_query($sql);
}
// this is javascript, not php
// alert('Deleted Successfully');
redirect_url($url);
return true;
}
Call the function like this:
multiple_delete($_POST['checkbox_name'], 'table_name', 'redirect_url', 'column_name_pic_1', 'column_name_pic_2', 'column_name_pic_3');
get rid of the apostrophes around your variable names in the function call, ie try
, $row[\'pic_title\'],
instead of
, '$row[\'pic_title\']',
I got the solution for this problem. in case it can benefit anyone here is the link to the solution.
How do i parse the the value from a string in the function call?

Categories