Affichage des articles dont le libellé est Active questions tagged php - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged php - Stack Overflow. Afficher tous les articles

mardi 4 août 2015

How to add "you save" option in the shopping cart of opencart?

I am trying to create a you save option in the shopping cart of opencart.com. I have done the same feature of you save to be displayed in the product page using vqmod. But i am finding it difficult to do it for the shopping cart. here is my vqmod code for adding you save option in the product page.

<modification>
    <id><![CDATA[@tik Savings Note]]></id>
    <version><![CDATA[1.1]]></version>
    <vqmver><![CDATA[2.1.7]]></vqmver>
    <author><![CDATA[OC2PS]]></author>
    <file name="catalog/view/theme/default/template/product/product.tpl">
        <operation>
            <search position="before" offset="2" error="log"><![CDATA[<?php if ($tax) { ?>]]></search>
            <add><![CDATA[<br /><span class="you-save" style="color:red;"><?php echo $text_yousave; ?> <?php echo $yousave; ?></span>]]></add>
        </operation>
    </file>
    <file name="catalog/language/english/product/product.php">
       <operation>
            <search position="replace" error="log"><![CDATA[// Entry]]></search>
            <add><![CDATA[$_['text_yousave']        = 'You save:';// Entry]]></add>
       </operation>
    </file>
    <file name="catalog/controller/product/product.php">
        <operation>
            <search position="replace" error="log"><![CDATA[$data['text_tax'] = $this->language->get('text_tax');]]></search>
            <add><![CDATA[$data['text_tax'] = $this->language->get('text_tax');
                 $data['text_yousave'] = $this->language->get('text_yousave');]]></add>
        </operation>
        <operation>
            <search position="replace" error="log"><![CDATA[$data['special'] = $this->currency->format($this->tax->calculate($product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax')));]]></search>
            <add><![CDATA[$data['special'] = $this->currency->format($this->tax->calculate($product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax')));
                $data['yousave'] = $this->currency->format($this->tax->calculate($product_info['price']-$product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax')));
                $data['yousavepercent'] = round(($product_info['price']-$product_info['special'])*100/$product_info['price'],0);]]></add>
        </operation>
        <operation>
            <search position="replace" error="log"><![CDATA[$special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')));]]></search>
            <add><![CDATA[$special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')));
                    $yousave = $this->currency->format($this->tax->calculate($result['price']-$result['special'], $result['tax_class_id'], $this->config->get('config_tax')));
                    $yousavepercent = round(($result['price']-$result['special'])*100/$result['price'],0);]]></add>
        </operation>        
    </file>
</modification>

Signing JSON objects

I have to exchange JSON objects between different platforms and implementations of a service and make its integrity verifiable via digital signatures. So a platform A would create such an object and create a digital signature. Said signature is then included into the object and sent to platform B. The JSON objects can contain arbitrary attributes and data.

E.g. in PHP:

function signObject($jsonObjectToSign, $privateKey) {
    $jsonObjectToSign->signature = "";
    $msgToSign = json_encode($jsonObjectToSign);

    openssl_sign($msgToSign, $jsonObjectToSign->signature, $privateKey, OPENSSL_SLGO_SHA1);

    return $jsonObjectToSign;
}

Problem is, that e.g. in Java, there is no way to tell whether the attributes of a JSON object will be in the same order you added them (via JSONObject.put()). So, if I do a

$json = json_encode('{"a":1, "b":2}');

in PHP, sign this object as stated above, transfer it to a java based server, decode the json object and then try to verify the signature, I'd probably get a different order of the object's attributes.

So what I need, is a reliable way to create a String from a JSONObject, independent of the language or platform used.

The example object above needs always to output {"a":1, "b":2} and NEVER {"b":2, "a":1}. Unfortunately, this is the usual case e.g. in Java.

Is there any "best practice" to sign JSON Objects in a secure way?

But let me describe the problem in another way:

Let's say I want to do this in Java (or any other language):

JSONObject j = new JSONObject();
j.put("a", 1);
j.put("b", 2);

Now, I need a serialization function, that outputs always the same string representation for this object, no matter how and with what language this object is created.

MySQL trigger: updating column depending of a submitted value

Ths my trigger but it doesn't work.

CREATE TRIGGER events_events_a BEFORE INSERT ON events_events
FOR EACH ROW
BEGIN 
IF NEW.public = 1 THEN
UPDATE events_cats SET etotal=etotal+1, etotal_NEW.region=etotal_NEW.region+1 WHERE id=NEW.category;
END IF;
END;

I need to update column depending of a submitted value.

if NEW.region value is 1, I need to update column etotal_1=etotal_1+1
if NEW.region value is 2, I need to update column etotal_2=etotal_2+1
if NEW.region value is 3, I need to update column etotal_3=etotal_3+1

etc. Is there any way how to update column depending of NEW.region value?

How to write NULL instead of 0 when I leave a field empty

I have a problem with inserting data. When I leave a field empty then he writes a 0 in my db instead of 0. What I have to do that he writes NULL.

<?php

if ($date == '' || $name_home == ''|| $name_away == '')
{

$error = 'Please enter the details!';

valid($date, $name_home, $name_away, $score_home, $score_away, $error);
}
else
{

mysql_query("INSERT name_matches SET date='$date', name_home='$name_home', name_away='$name_away', score_home='$score_home', score_away='$score_away'")
or die(mysql_error());

header("Location: view.php");
}
}
else
{
valid('','','','','','');
}
?>

Divs, including php to appear next to each eachother

Using Bootstrap to layout the page and at first I had images in a grid, like on Facebook, there were 4 in a row and as the page shrunk so did the number of images in a row. Now I have added php so it is easier to update the page but the images all appear under each other. How can I have it the way it was?

Code used:

<section  id="alf40">
   <div class="container-fluid no-padding ">
<div class="row">

        <div class="col-lg-3 col-md-4 col-xs-6 thumb" style="display:inline-block; float:left; position:relative;" >
        <?php $SQL = "SELECT * FROM nw_photo";
        $result = mysql_query($SQL);
        while ( $db_field = mysql_fetch_assoc($result) ) { ?>

            <a class="thumbnail" href="#"><img class="img-responsive" src="
    <?php echo $db_field['image']; ?>" style="display:inline-block; float:left; position:relative;">
            <?php } ?></a>
        </div>

</div>
</div>
  </section>

Alternative to strtotime() in MySQL

I have an EventSet table with those fields:

  • start_day (ex. Monday)
  • start_time (ex. 14:20:00)

I want to create a query that selects specific records by comparing their day an time with the current ones.

So, using a little help from the PHP's strtotime() method I am aiming at something similar to:

SELECT * 
FROM 
   `EventSet` 
WHERE 
    DATE_FORMAT(NOW(), '%W %H:%i:%s') <= 
    date('%W %H:%i:%s', strtotime('start_day start_time'))

*the last date() part is of course pure PHP


So far I've tried using DATE_FORMAT with CONCAT_WS and also TIMESTAMP() / UNIX_TIMESTAMP() but am clearly messing something up.

SELECT * 
FROM 
    `EventSet` 
WHERE 
    DATE_FORMAT(NOW(), '%W %H:%i:%s') <= 
    DATE_FORMAT(CONCAT_WS(' ', start_day, start_time), '%W %H:%i:%s')

I've looked through many similar questions here and in the net, but they all already have a date field to work with and there's no need to concatenate anything, so I can't use any of them.

How to access protected variable form given response [duplicate]

This question already has an answer here:

I want to retrieve _href:protected from given response but i don't know How i can access it .

 Recurly_Subscription Object
(
    [_values:protected] => Array
        (
            [subscription_add_ons] => Array
                (
                )

            [account] => Recurly_Stub Object
                (
                    [objectType] => account
                    [_href:protected] => http://ift.tt/1MJI9ao
                    [_client:protected] => Recurly_Client Object
                        (
                            [_apiKey:Recurly_Client:private] => 
                            [_acceptLanguage:Recurly_Client:private] => en-US
                        )

                    [_links:protected] => Array
                        (
                        )

                )






)
)

i try $sub->account->href for account href but not success. Please provide solution .

CakePHP - How to continue saving if associated model fails validation

Let's say I have an array:

array(
    'Foo' => array(
        'field1' => 'value1',
        'field2' => 'value2'
    ),
    'Bar' => array(
        'field1' => 'value1',
        'field2' => 'value2'
    )
)

Where Foo and Bar have model relationships set up and have their own validation conditions in he model.

How can I make it so if I am doing $this->Foo->save(); even if Bar fails its validation then it will still go ahead and save Foo only

Codeigniter Deprecated: mysql_real_escape_string():

Got below error while using codigniter 3.0

FYI using PHP Version 5.5.12,Apache Version Apache/2.4.9 (Win64) PHP/5.5.12

A PHP Error was encountered

Severity: 8192

Message: mysql_real_escape_string(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

Filename: models/common_model.php

Line Number: 21

Backtrace:

File: C:\wamp\www\Codeigniter\application\models\common_model.php Line: 21 Function: mysql_real_escape_string

get total price of configurable product according to size swatch

I am new in magento.I have created a store and managed some configurable products in it.What I want to do now is show total price in the size swatch dropdown but in default magento gives the individual size price in the dropdown with + or - sign with it.Can anyone suggest me any idea so i can show total price instead of unit price?Any help is appreciated!!Thanks

Wordpress get_permalink doesn't work

I've got some trouble with unclickable images and post titles in my Wordpress blog template. Get_permaling doesn't work (according to what I've read it's because that function should be in loop.php but my template doesn't have that file).

The weird thing is, there's a "read more" link under each post and it has get_permalink attribute - and it works, but when I try to make post image or title clickable the same way, nothing changes. It's a little annoying when people can't open blog posts by clicking on image or header :(

Could you help me with that?

Here's the list of files my template contains, maybe that will be helpful?

404.php

bootstrap_tests.php

class.redux-plugin.php

index.php

kill-travis.php

redux-framework.php

uninstall.php

archive.php

author.php

category.php

comments.php

content-audio.php

content-gallery.php

content-quote.php

content-video.php

content.php

footer.php

class-tgm-plugin-activation.php

color.php

post_type.php

wp_bootstrap_navwalker.php

functions.php

header.php

index.php

(page-templates/alt-header.php)

(page-templates/blog-timeline.php)

(page-templates/blog1.php)

(page-templates/blog2.php)

(page-templates/blog_sidebar1.php)

(page-templates/blog_sidebar2.php)

(page-templates/blog_sorting.php)

(page-templates/template-canvas.php)

(page-templates/template-portfolio.php)

page.php

search.php

shortcodes.php

sidebar-footer.php

sidebar.php

single-portfolio.php

single.php

tag.php

vc_shortcode.php

vc_column.php

vc_row.php

vc_tab.php

vc_tabs.php

Style

style.css

rtl.css

DRAG and DROP file upload work like multiple file upload

I want to make a form with informations such as "name, type, etc.." and i want to make a 'Drag and Drop' image uploader with click fuction. SO drag and drop or click to select the images. Max is 5 images. I found some script and divs but it alway upload the file whzen you drag and drop it or choose it. I want to submit the upload with the whole form, because it is connected to a mysql database. I did't find a solution for this.

Getting date value with find() and Checking if the date is < 30 mins

I try to make an app. that sends e-mail to the user. Whenever i run the code, the current time and date is saved to the database under the name of "created" (column). There are 2 conditions. I could make the first one in that if loop. Second condition is sending e-mail after 30 mins from the previous e-mail. To do this, I try to get those saved values by using find() and compare them to do 30 mins condition. (Btw I am very newbie at programming. I ve been learning for 3 weeks)

Here is the code;

class TemperatureReading extends AppModel {

    function afterSave($created, $options = array()) {

    $temperature = $this->data['TemperatureReading']['temperature'];

    $result = $this->Location->find('first' , array(
            'conditions' => array(
                    'Location.id' => $this->data['TemperatureReading']['location_id']
            )));

    $high_threshold = $result['Location']['high_threshold'];

    $low_threshold = $result['Location']['low_threshold'];

    $created = $this->data['TemperatureReading']['created'];

    $id = $this->data['TemperatureReading']['id'];

    $models_Temp_Loc = $this->find('first' , array(
            'conditions' => array(
                    'TemperatureReading.id' => $id
            )));

    $prev_created_time = $models_Temp_Loc['TemperatureReading']['created'];

// The part, where I have problems. I want to get the values of created (time and date) and compare them to check 30 mins condition. (ex: Assume that app. ran and e-mail sent for the first time at specific time. The application can be run 100 or 241 or 4144.. times in 10 mins after the first e-mail, so there are many date and time data saved in created in 10 mins to be compared for 30 mins condition.)

    $deneme = $this->find('all' , array(
        'conditions' => array(
                'created.id' => $id
                ), 
                    'condition' => array(
                        'created' <30
                )));

    //The part where i can make the first condition without problem

    if ($temperature > $high_threshold || $temperature < $low_threshold) {

        $Email = new CakeEmail('gmail');
        $Email->from(array('xxxxxxx@gmail.com' => 'My Site'));
        $Email->to('xxxxxxxxxx@gmail.com');
        $Email->subject('Temperature Warning!');
        $Email->send('Temperature is at critical value of');

    }

Excuse me for any meaningless things, i am very noob and trying to do hard things.

This is what goes on there without $deneme (wrong part). for every id, there is a date and time to be compared for the 30 min condition.

Temperature is: 12
High_threshold is: 90
Low_threshold is: 0
Created is: 2015-08-04 14:47:52
Id is: 340

Array
(
    [TemperatureReading] => Array
        (
            [id] => 340
            [created] => 2015-08-04 14:47:52
            [temperature] => 12
            [location_id] => 1
        )

    [Location] => Array
        (
            [id] => 1
            [name] => Spor Salonu
            [high_threshold] => 90
            [low_threshold] => 0
            [send_warning_to] => onurcucen@gmail.com
        )

)

2015-08-04 14:47:52

ty for any possible recommendations, comments, answers.

PHP - How to merge foreach arrays into one loop

Here is my code:

$url = "http://ift.tt/1IDweUE";

libxml_use_internal_errors(true); 
$doc = new DOMDocument();
$doc->loadHTMLFile($url);

$xpath = new DOMXpath($doc);

$n = $xpath->query('//td[@data-column-name="Model"]');
$r = $xpath->query('//td[@data-column-name="RAM"]');

foreach ($n as $entry) {
    $Name = $entry->nodeValue;
    $RAM  = $r->nodeValue;
    echo " $Name - RAM: $RAM<br>";
}

I successfully echo $Name but i can not get the value for $RAM because i do not have it in my array. My question is how i can add $r into this foreach loop and make it work ?

Thanks in advance!

How to use Different Button in bootstrap Form

i have used Bootstrap and created form.my form Looks like

  <form action="default_results.php"   method="post" class="calculator"  name="frmCalculator">  

i have put this code begin of the code and end of the page i have used three button Looks like

                            <button id="button2" class="dont-compare shadow-inset" value="reset" >
                                    Reset</button>
                            <button id="button3" data-toggle="pop" class="dont-compare shadow-inset" class="update" >
                                    Update MI</button>
                            <button id="Button4"  class="dont-compare shadow-inset" class="calculator" >
                                    Calculate Scenarios</button>
                        </div>

i have another page its called default_ results.php page. i want load that page when i click Calculate Scenarios button . i used href tag that button. but that three button also load default_results page. how to set particular button? please any idea about it?

Redis scan skipping keys

I'm using predis (with laravel if it makes any difference) php client to work with Redis.

I need to fetch all the keys from Redis that match certain prefix and I do it like this:

$keys = [];
    foreach (new Iterator\Keyspace($this->redis(), Cache::KEY_PREFIX.'*') as $key) {
        $keys[] = $rate_key;
    }

After the work with those keys is done, operation repeats - I'm getting those keys again in again in a loop. I noticed that after a few iterations some keys are not included in $keys array.

The strangest thing is that keys that disappear never appear in next iterations. Restart of the php process (it's a daemon) fixes the problem.

I'm using Redis 3.0.2 with Predis 1.0 and PHP 5.4

P.S. Within the loop over keys, I change values for some of them. I'm not deleting any keys, however.

How to upload image and save URL in database in php

In this php code i want to customize the image upload destination. with this php file, i have directory called uploads. i want to add all my uploaded images to this directory and store path in db. how can i do this?

<?php
// Assigning value about your server to variables for database connection
$hostname_connect= "localhost";
$database_connect= "image_upload";
$username_connect= "root";
$password_connect= "";

$connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR); 
@mysql_select_db($database_connect) or die (mysql_error()); 

if($_POST) { 
    // $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.

    if ($_FILES["file"]["error"] > 0) {
        // if there is error in file uploading 
        echo "Return Code: " . $_FILES["file"]["error"] . "<br />";

    } else {
        // check if file already exit in "images" folder.
        if (file_exists("images/" . $_FILES["file"]["name"])) {
            echo $_FILES["file"]["name"] . " already exists. ";
        } else {  
            //move_uploaded_file function will upload your image.  if you want to resize image before uploading see this link http://ift.tt/UVKZR0
            if(move_uploaded_file($_FILES["file"]["tmp_name"],"images/" . $_FILES["file"]["name"])) {
                // If file has uploaded successfully, store its name in data base
                $query_image = "insert into acc_images (image, status, acc_id) values ('".$_FILES['file']['name']."', 'display','')";
                if(mysql_query($query_image)) {
                    echo "Stored in: " . "images/" . $_FILES["file"]["name"];
                } else {
                    echo 'File name not stored in database';
            }
       }
   } 

}
}
?>

currently when i run the upload i am getting warnings

Warning: move_uploaded_file(images/1409261668002.png): failed to open stream: No such file or directory in D:\xampp\htdocs\image-upload\index.php on line 29

Warning: move_uploaded_file(): Unable to move 'D:\xampp\tmp\php1C1F.tmp' to 'images/1409261668002.png' in D:\xampp\htdocs\image-upload\index.php on line 29

MySQL - One table of each client or Single table with all clients

I am beginning a project where there will be multiple clients. In the database, each client can potentially have hundreds of thousands of rows.

Instead of having all of the clients in a single table, would it make sense to split the clients so that each has their own table? To me this makes sense since each time you query for a client, you would only be looking up a table with their data.

POST a series of products in Laravel / PHP

I'm using Laravel to post a series of products. The user can choose a quantity of each product.

Now I'm wondering how I can post a series, but still have the names of the products.

I have tried the following.

This result gives me an undefined offset error

<input name="{{ $products[$product->id] }}" />

This result doesn't include the name, but does make it a series

<input name="products[]" />

Any idea how I might end up with an array that's called $products, and has all the products in there by name

How to package PHP code like jar or exe or dll?

How to package PHP code like jar in java or exe and dll in visual studio ?

such that when i host it my source code isn't directly available.