Quantcast
Channel: PHP Freaks: PHP Help
Viewing all 13200 articles
Browse latest View live

Polling Chat message content to screen using ajax JSON

$
0
0

Hi I successfully designed a chat message system between users and it works fine. The only problem I am having at this point is polling data from chat table to browser real time.

The messages are displayed using ajax and the setInterval works as I checked the console. The issue is that it does not capture new entries to the table for display and hence the user has to keep refreshing the page to see new content.

Please help. My code is below. Please forgive my file naming convention as I will change it later on. PS this is developed using codeigniter framework.

 

Chats.php - Controller

    public function ajax_get_chat_messages(){
    echo $this->_get_chat_messages();
    }
    function _get_chat_messages($recipient = null)
    {
    $user_id = $this->session->userdata('user_id');
    $recipient = $this->input->post('recipient');
    $data['recipient'] = $this->User_model->get_users($user_id);
    $data['chats_count'] = $this->Chats_model->get_chat_messages_count($recipient);
    $content = $this->Chats_model->get_chat_messages_count($recipient);
    $data['chats'] = $this->Chats_model->get_chat_messages($user_id);
    $result = array('status' =>'ok', 'content'=>$content);
    return json_encode($result);
    }

Model - Chats_model.php

 public function get_chat_messages_count($recipient = null){
    $session = $this->session->userdata('user_id');
    $this->db->select('*');
    $this->db->from('chat_messages');
    $this->db->join('users', 'users.user_id = chat_messages.user_id');
    $this->db->where(array('chat_messages.user_id' => $session));
    $this->db->where(array('chat_messages.recipient' => $recipient));
    $this->db->or_where(array('chat_messages.user_id' => $recipient));
    $this->db->where(array('chat_messages.recipient' => $session));
    $this->db->where_in(array('chat_messages.chat_id' => $session ,   $recipient));
    $query = $this->db->get();
    return $query->result_array();
    }

View - chats_view.php

    <script type="text/javascript">
    var user = "<div class='timeline-item' id='view'><ul><?php foreach($chats_count as $chat){echo '<li>'; echo $chat['username']; echo '</li>'; }?></ul></div>";
    </script>
    <div class="wrapper wrapper-content">
    <div class="row animated fadeInRight">
    <div class="col-lg-12">
    <div class="ibox float-e-margins">
    <div class="ibox-title">
    <h5>Chat</h5>
    <div class="ibox-tools" >
    </div>
    </div>
    <div class="ibox-content inspinia-timeline" id="view1" >
    </div>
    </div>
    </div>
    </div>
    </div>
    </div>
    </div>
    </div>

JS - chat2.js

$(document).ready(function(){
    setInterval(function() { get_chat_messages(); }, 2500)
    $("input#chat_message").keypress(function(e){
    if(e.which == 13){
    $("a#submit_message").click();
    return false;
    }
    });

    function get_chat_messages(){
    $.post(base_url +"user/chats/ajax_get_chat_messages",{user: user}, function(data) {
    if(data)
    {
    var current_content = $("#view1").html();
    $("#view1").html(user);
    console.log(user);
    }
    else
    {
    }, "json");
    }

    get_chat_messages();
    });

Attached Thumbnails

  • consoledata.png
  • mysqldata.png
  • browserdata.png

data entry in firebase

$
0
0

i am using php to generate some stuff & using javascript to insert those stuff in my firebase DB

 

but now the problem is some of those generated strings contain some html anchor tag in them so my JS script is refusing them & they are not getting inserted because they contain single quote

i tried to replace single quote with double quote but then firebase is adding a backslash before every " so those anchor tags are not working when i am showing DB on a page

 

 

so far i was only able to think about one solution that i should remove all single & double quote & href will still work & i can replace space with %20 so the link will not get broke

 

example generated string by my php

 

hello <a href='https://forums.phpfreaks.com'>PHP freaks</a>

 

my JS script


[API keys]

firebase.initializeApp(config);
var database = firebase.database();
var ref = database.ref('phpfreaks');
var data = {
		text: '$text1',
		text2: '$text2'
		}
ref.push(data);

PS

 

i cant remove single quote before my variable in JS script

if i do so the data will not get entered...

In_array question

$
0
0

Hi guys, have a quick question for ya'll.

Is it possible to make an in_array from a SQL table field where the data is stored?

 

I've tried something like this:

$result = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT allowid FROM articles WHERE id =".sqlesc($id)) or sqlerr(__FILE__, __LINE__);
$cats = array();
while ($row = mysqli_fetch_array($result)){
$cats[] = $row['allowid'];
}
if (!(in_array($CURUSER['id'],$cats))){
stderr("Error", "Special access is required !");
}

Where the allowid table field contains numbers separated by a comma corresponding to each userid. If the userid doesn't match one of those numbers they shouldn't get access. This is what i am trying to do instead of having a separate table with different rows in it.
 

 

When should isset, empty & is_null to be used?

$
0
0

The other day, this topic came up for discussion, when catching $_POST what are your thoughts on the best way of catching it?

 

I had been using "isset" as my main weapon for catching $_POST / $_GET, however, It was suggested that checking for "Empty" over "Isset" was the better approach, I did look into the 101 manuals and Google and got mixed views, though, I am now more incline to agree on using "empty" over "isset", the reason why is that, if a space is inputted, "empty" will return false, whereas isset will declare true and boolean sent as TRUE will also return False from "empty", though True from "isset" and many data outputs that can found: (https://www.virendrachandak.com/demos/php-isset-vs-empty-vs-is_null.php).

 

 
 
IF (isset($_POST["From_Form"])){ ... }

IF (empty($_POST["From_Form"])){ ... }

IF (is_null($_POST["From_Form"])){ ... }

 

 

I would like to know your thoughts on this topic?

PHP/MYSQL using table data to loop through multiple other tables

$
0
0

Hey guys, i have been working on a script for a little while now and just can't seem to find a solution.The issue I'm having is that i can't seem to loop through multiple tables using a primary tables information. In the bottom case i have two records with the same title 'fire_index'  which has the same formula, the only thing that differs is the sensors and unit_id's have changed.  

 

Breakdown of steps:

 

1.) Automatically loop through calculation table retrieve all records with desired title e.g 2 records , fire_index

2.) Use the information retrieved from the calculation table to build query's for getting data

3.) Loop through data queries to get results , apply results to formula (string replace x,y,z) and output to output table

 

Firstly i have looped through the calculation table which contains pre-made formulas, types , company names, unit id's, sensors. The user chooses the sensor and the unit they want to apply the formula to. The script is based on the formula type e.g fire index. 

 $query = mysqli_query($mysqli, "SELECT * FROM calculation where title = 'fire_index'");
    while($row = mysqli_fetch_array($query))
    {
      $title = $row['title']; // fire_index
      $time = $row['time']; // 2017-12-3
      $formula = $row['formula']; // e.g 10^(0.009254 + (0.01201*x) + (0.2789*(SQRT(y)) - 0.09577*(SQRT(z))))
      $unit= $row['unit_id']; //23223
      $sensor = $row['sensor'];  // AT - Air Temp
      $unit1 = $row['unit1_id'];  //123424
      $sensor1 = $row['sensor1']; //RH - Relative Humidity
      $unit2 = $row['unit2_id']; //123525
      $sensor2 = $row['sensor2']; //AVGWN - Avg Winspeed
      $unit3 = $row['unit3_id']; // Etc..
      $sensor3 = $row['sensor3']; //Etc...
      $unit4 = $row['unit4_id']; //Etc..
      $sensor4 = $row['sensor4']; //Etc..
}

The next query's rely on the calculation table to get the correct columns :

  $query1 = mysqli_query($mysqli,"SELECT $sensor as sensor from data where unit_id = '$unit'");
        while($row = mysqli_fetch_array($query1))
    {
    $x = $row['sensor']; /// GETS data from AT column


   }

  $query2 = mysqli_query($mysqli,"SELECT $sensor1 as sensor1 from test where unit_id = '$unit1'");
        while($row = mysqli_fetch_array($query2))
    {
    $y = $row['sensor1'];  /// GETS data from RH column

   }
$query3 = mysqli_query($mysqli,"SELECT $sensor2 as sensor2 from test where unit_id = '$unit2'");
        while($row = mysqli_fetch_array($query3))
    {
    $z = $row['sensor2']; /// GETS data from WNSAVG column

   }


 

I have successfully made the script to work with looping individual units using one unit_id, but when it comes to multiple it doesn't work. 

 

Example output variable storing the finalised formula inside the end of the loop: 

$step1 =  str_replace("x",$x,$formula);
$step2 =  str_replace("y",$y,$step1);
$step3 =  str_replace("z",$z,$step2);

eval('$output = ('. $step3 .');');

After the task i need to insert the output into the output table. 

 

FULL CODE EXAMPLE : Here

MySQL table Example: Here

 

Thanks, any help at all would be amazing.

Proper use for cURL

$
0
0

I was recently working on a script where the browser client makes an ajax REST request to a webserver, and that webserver makes a REST request using cURL to another server, and kept intermittently getting the following text in my response.

<!DOCTYPE HTML PUBLIC \"-\/\/IETF\/\/DTD HTML 2.0\/\/EN\">\n<html><head>\n<title>400 Bad Request<\/title>\n<\/head><body>\n<h1>Bad Request<\/h1>\n<p>Your browser sent a request that this server could not understand.<br \/>\n<\/p>\n<\/body><\/html>\n

Both servers are under my control, and I spent way to much time figuring out the problem.  None of the machines logged any errors (should they have?  Maybe my error logging is not correct?), and the correct data was being returned to each machine, but this damn text kept on breaking my JSON.   It turns out that CURLOPT_POSTFIELDS must be set if a POST request (i.e. CURLOPT_POST=1).  At least on my machines, this is not required for either PUT or DELETE requests.  The solution was just to include an empty string in CURLOPT_POSTFIELDS.

 

I started using this function a while back just because it worked, and I think it is about time to reconsider how I am using it.  Specifically, should I really be using the values for CURLOPT_RETURNTRANSFER, CURLOPT_HEADER, CURLOPT_FOLLOWLOCATION, CURLOPT_ENCODING,and CURLOPT_USERAGENT as I show?  Also, should I consider changing anything else?  As I said, I spent way too much time identifying this issue, and don't ever want to do it again.

 

Thanks

function CallAPI($method, $url, array $data, array $options=[])
{
    $options=$options+[    //Don't use array_merge since it reorders!
        CURLOPT_RETURNTRANSFER => true,     // return web page
        CURLOPT_HEADER         => false,    // don't return headers
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
        CURLOPT_ENCODING       => "",       // handle all encodings
        CURLOPT_USERAGENT      => "unknown",// who am i
        CURLOPT_AUTOREFERER    => true,     // set referrer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
        CURLOPT_TIMEOUT        => 120,      // timeout on response
        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
    ];
    //Optional authentication
    if (isset($options[CURLOPT_USERPWD])) {$options[CURLOPT_HTTPAUTH]=CURLAUTH_BASIC;}
    switch (strtolower($method)) {
        case "get":
            if ($data) {$url = sprintf("%s?%s", $url, http_build_query($data));}
            break;
        case "post":
            $options[CURLOPT_POST]=1;
            //if ($data) {$options[CURLOPT_POSTFIELDS]=http_build_query($data);}
            $options[CURLOPT_POSTFIELDS]=$data?http_build_query($data):'';
            break;
        case "put":
            //$options[CURLOPT_PUT]=1;
            $options[CURLOPT_CUSTOMREQUEST]="PUT";
            if ($data) {$options[CURLOPT_POSTFIELDS]=http_build_query($data);}
            break;
        case "delete":
            //$options[CURLOPT_DELETE]=1;
            $options[CURLOPT_CUSTOMREQUEST]="DELETE";
            if ($data) {$options[CURLOPT_POSTFIELDS]=http_build_query($data);}
            break;
        default:trigger_error("Invalid HTTP method.", E_USER_ERROR);
    }
    $options[CURLOPT_URL]=$url;
    $ch      = curl_init();
    curl_setopt_array( $ch, $options );
    $rsp=['rsp'=>curl_exec( $ch ),'errno'=>curl_errno($ch),'code'=>curl_getinfo($ch, CURLINFO_HTTP_CODE),'error'=>false];
    if($rsp['errno']) {
        $rsp['error']=curl_error($ch);
    }
    curl_close( $ch );
    return $rsp;
}

 

Any body familiar with IPTV?

$
0
0

Hey guys , i have my own IPTV provider and i would like to make a web portal .

 

in iptv there are some providers that offer a web viewer if you have no source for streaming like a Mag box..

 

the link is all M3U

 

we login and we see the channels and EPG guide(tv guide)

 

so in m3 u mode we get a link:

http://stb.spades-tv.xyz:25461/client_area/live.php

 and if you use a M3u player like VLC or perfect player you  get

 

http://stb.spades-tv.xyz:25461/get.php?
username=xxxxx&password=xxxxx&
type=m3u_plus&output=ts

in a m3u file :

#EXTVLCOPT:http-user-agent=tttttttiiii LibVLC/3.0.0-git
#EXTINF:-1,SFR Sport 1HD Fr
http://rmd.primatv.club:8899/live/BestTV.FB/OAfllsYAJy/1464.ts

gives you the channel and icon and link to video

 

 

so the question is what can i use to play this?HTML5? i know the php is to get the files...

 

 

Parse Error

$
0
0

I am new to php and cannot get rid of this error:

 

Parse error: syntax error, unexpected '}', expecting end of file in C:\inetpub\wwwroot\354\Groups\Group-A2\getMarketing.php on line 29

 

Here is the Query:   

 

 <?php

$content = "";
if (isset($_POST['submit'])) {
  require_once("db.php");
  $customer = mysqli_real_escape_string($con, $_POST['customer']);
  $content .= "
      <h4>Marketing Campaign '{$customer}':</h4>";
          
  $query = "SELECT m.tool, m.number_recruited
  FROM 354groupa2.marketing m";
  $results = mysqli_query($con, $query) or die("Query failed: " . mysqli_error($con));
  $content .= "
        <table>
          <tr>
            <th>Campagin Tool</th>
            <th>Number Recruited</th>
          </tr>";
    $content .= "
while ($row = mysqli_fetch_array($results)) {
          <tr>
            <td>{$row['tool']}</td>
            <td>{$row['number_recruited']}</td>
          </tr>
  </table>";
  }
 
  mysqli_free_result($results);
  mysqli_close($con);
}
?>
 
 
Any help would be greatly appreciated. 

Getting Error 500 on Web Server for PHP select query.

$
0
0
I'm getting and Error 500 from my server. I'm not sure why... I think it might be my code. Can someone take a look please.

localhost is currently unable to handle this request.

HTTP ERROR 500

<?php
include("common/common.php");
include("../common/db_connector.php");

$email_sent = $_POST["inputEmail"];
$password_sent = md5($_POST["inputPassword"]);


// Check database for user credentials...
$sql = "SELECT * FROM users WHERE email = '$email_sent'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        //checks for true conditions if password and meail match database......
        if($email_sent == $row["email"] AND $password_sent == $row["password"]) {

			$_SESSION["username"] = $email_sent;
			echo "<script>window.location = 'dashboard/index.php';</script>";
		} else {
			echo "<script>alert('access denied'); window.location = 'index.php';</script>";
		}
    }
}
//////////////////////////////////////////////
?>

Filter Pivot data from mysql...or not

$
0
0

Hi there I been trying this for days with no joy so thought I'd ask the question to see if its even possible?

 
I have a php pivot based on mysql query, it works great but I would like to have an external filter for years..Currently i can only include 2017 for example in the where clause, I've tried to remove that but cant seem to work out how to have it display current years data on load then filter it by user input of year. 
 
Basically I'm trying to return all data but initially only display current year. Then when user selects a year from a dropdown it filters it to only that year? I think half my problem is that the date fields (i.signedupdate) are all summed so I cant actually target a year (2017, 2016, 2015 etc etc). Is this even possible?
 
SELECT * FROM 
  (SELECT c.Adviser,
  Sum(Case When Month(i.signedupdate) = 1 Then i.comms + i.broker_fee + i.legal_fees Else 0 End) Jan,
  Sum(Case When Month(i.signedupdate) = 2 Then i.comms + i.broker_fee + i.legal_fees Else 0 End) Feb,
  Sum(Case When Month(i.signedupdate) = 3 Then i.comms + i.broker_fee + i.legal_fees Else 0 End) Mar,
  Sum(Case When Month(i.signedupdate) = 4 Then i.comms + i.broker_fee + i.legal_fees Else 0 End) Apr,
  Sum(Case When Month(i.signedupdate) = 5 Then i.comms + i.broker_fee + i.legal_fees Else 0 End) May,
  Sum(Case When Month(i.signedupdate) = 6 Then i.comms + i.broker_fee + i.legal_fees Else 0 End) Jun,
  Sum(Case When Month(i.signedupdate) = 7 Then i.comms + i.broker_fee + i.legal_fees Else 0 End) Jul,
  Sum(Case When Month(i.signedupdate) = 8 Then i.comms + i.broker_fee + i.legal_fees Else 0 End) Aug,
  Sum(Case When Month(i.signedupdate) = 9 Then i.comms + i.broker_fee + i.legal_fees Else 0 End) Sept,
  Sum(Case When Month(i.signedupdate) = 10 Then i.comms + i.broker_fee + i.legal_fees Else 0 End) Oct,
  Sum(Case When Month(i.signedupdate) = 11 Then i.comms + i.broker_fee + i.legal_fees Else 0 End) Nov,
  Sum(Case When Month(i.signedupdate) = 12 Then i.comms + i.broker_fee + i.legal_fees Else 0 End) Dece,
  Sum(i.comms + i.broker_fee + i.legal_fees) As Total
From
  tbl_lead i Inner Join
  tbl_clients c On c.client_id = i.client_id
Where
    Year(i.signedupdate)= 2017
Group By c.Adviser with rollup) As t

 

   

Directory structure

$
0
0
I would like to continue https://forums.phpfreaks.com/topic/305804-critique-script/, but specifically how the directory structure should be arranged, and with an empathis on namespace. 
 
The /var/www/ has the following files and directories, and represents my EmbeddedWebserver project.
bin/
config/
docs/
public/
   index.php
   resources/
      css/
      js/
   vendors/
      jquery/
resources/
scr/
   MyPhpFiles.php
templates/
   some_template.html
tests/
vendors/
   michael/
      simple-router/
         src/
            SimpleRouterFiles.php
      my-larger-package/
         SomeSubPart1/
            SomeClasses.php
         SomeSubPart2/
            SomeOtherClasses.php
         Exceptions/
            SomeExceptions.php
   some_other_vendor/
   Pimple.php
 
Say, I was the author of simple-router and I use it on multiple projects and maybe even host it publicly and have a composer.json file to configure it.  It seems to be it should be located in vendors/ along with any other 3rd party packages.  Am I mistaken?  Assuming I am not, my classes for simple-router will use the Michael\SimpleRouter\ name space or maybe even some sub-namespace under it.
 
Pimple which doesn't have any namespace declared will be located directly in vendors/.  Side note, but will it be possible to configure a composer.json file to load it here?
 
My files in src/ will use the Michael\EmbeddedWebserver\ namespace or maybe some sub-namespace.
 
In regards to organizing directories in src/ (or vendors/michael/simple-router/src/ for that mater), I assume there really can't be much of a standard as each project is different.
 
Does it ever make sense to have a common Exceptions directory for multiple sub-packages as I have shown?
 
Should a cache/ or tmp/ directory ever be located in the root?
 
Am I somewhat on the right track?
 
Thanks
 

echo result from prepared statement function

$
0
0
$username = "user1";

$result = single_row_prepared($username);

echo $username . " - " . $country . " - " . $about . " - " . $age;

It says the variables are undefined. How do I echo them out?

  function single_row_prepared($username) {
global $connect;

$sql = "SELECT profile_username, profile_country, profile_about, profile_age ";
$sql .= "FROM profiles ";
$sql .= "WHERE profile_username = ?";
$stmt = mysqli_prepare($connect, $sql);


mysqli_stmt_bind_param($stmt, 's', $username);

mysqli_stmt_execute($stmt);

mysqli_stmt_bind_result($stmt, $username, $country, $about, $age);

mysqli_stmt_fetch($stmt);

mysqli_stmt_close($stmt);
  }

[06-Dec-2017 08:19:54 UTC] PHP Notice:  Undefined variable: country in /home/buysnapchats/public_html/examples/prepared_statement_single_row.php on line 13
[06-Dec-2017 08:19:54 UTC] PHP Notice:  Undefined variable: about in /home/buysnapchats/public_html/examples/prepared_statement_single_row.php on line 13
[06-Dec-2017 08:19:54 UTC] PHP Notice:  Undefined variable: age in /home/buysnapchats/public_html/examples/prepared_statement_single_row.php on line 13

Multidimensional array for nested menu items

$
0
0

Hi,

 

I am having problems getting a multi level menu working and have read a lot of previous forum posts trying to make sense of it and an example like https://forums.phpfreaks.com/topic/303449-php-recursive-multidimensional-array-to-html-nested-code/?hl=%2Bmultidimensional+%2Barray#entry1544308 should probably tell me everything I need to know, but I simply cannot get my head around this correctly and make it work. I hope there are some experienced coders here who will bare with my n00bness hehe.. 

 

My menu items are stored like:

mysql> SELECT id, name, parent FROM menu_items;
+----+-------------------+--------+
| id | name              | parent |
+----+-------------------+--------+
|  1 | Programming       |      0 |
|  2 | PHP               |      1 |
|  3 | Python            |      1 |
|  4 | Operating-Systems |      0 |
|  5 | Windows 2012 R2   |      4 |
|  6 | Linux Mint        |      4 |
|  7 | Network           |      0 |
|  8 | Some stuff        |      6 |
+----+-------------------+--------+


Programming
 |- PHP
 |- Python
Operating-Systems
 |- Windows 2012 R2
 |- Linux Mint
   |- Some Stuff
Network

Today it only supports 1 sub-level because I just put one loop within another like this:

 

$query = "SELECT id, name FROM menu_items WHERE parent = 0";
$result = $link->query($query);

if ($result->num_rows > 0) {
  while ($row = $result->fetch_assoc()) {
    $children = getMenuChildrenCount($row['id']);
    $links_count = getLinksCountFromParentId($row['id']);
    echo "\t\t\t\t\t\t<li class=\"haschildren\"><div><a href=\"links.php?pid={$row['id']}\" class=\"link\">".$row['name']." ({$links_count})</a> <a href=\"#\" class=\"expand\">".$children."<i class=\"fa icon\"></i></a></div>\n";
    echo "\t\t\t\t\t\t<ul>\n";
    ${query . $row['id']} = "SELECT id, name FROM menu_items WHERE parent = " . $row['id'];
    ${result . $row['id']} = $link->query(${query . $row['id']});
    if (${result . $row['id']}->num_rows > 0) {
      while (${row . $row['id']} = ${result . $row['id']}->fetch_assoc()) {
        $links_count = getLinksCountFromParentId(${row . $row['id']}['id']);
        echo "\t\t\t\t\t\t\t<li><div><a href=\"links.php?pid=".${row . $row['id']}['id']."\" class=\"link\">".${row . $row['id']}['name']." ({$links_count})</a></div></li>\n";
      }
    }
    echo "\t\t\t\t\t</ul>\n";
    echo "\t\t\t\t\t</li>\n";
  }
}

That, of course, is not optimal or the right way to do it.. Can someone please tell me how to come around multi level with X depth?

 

Thank you very much :-)

 

WSQ Compression with PHP

$
0
0

Hello guys,

 

Please I'm working on a project that requires me to accept fingerprint images in bmp format and then convert it to a compressed WSQ file before sending it as bytes to a web service. My challenge is achieving the WSQ compression with PHP. Has anyone done this with PHP before?

external cron jobs


Is there a reason why some images won't upload using this script?

$
0
0

I am using this script for image uploads.

 

https://www.w3schools.com/php/php_file_upload.asp

 

I noticed that with some of the image uploads, I would get the error 

"Sorry, only JPG, JPEG, PNG & GIF files are allowed."

 

The images i upload are one of the file types listed above.  So I am wondering why i would get an error for some images but not others despite all them of being the same file types?

 

Can you tell why judging from the script?

 

 

Why does this keep looping? (New to coding)

$
0
0

Hey guys, wondering if anyone can help me with this issue. Basically i need the price per text to be next to the total price. But every time i move that piece of code into the other. It breaks the styling and echos out 7 times... Im probably missing something very simple as im new to developing but id really like to get this done. Any help would be fantastic. 

 

 

picdisc.PNG

 

Please find the code underneath. 

 

  1. 
    	
    /** * Format the price with a currency symbol. * * @param float $price * @param array $args (default: array()) * @return string */function wc_price( $price, $args = array() ) {    extract( apply_filters( 'wc_price_args', wp_parse_args( $args, array(        'ex_tax_label'       => false,        'currency'           => '',        'decimal_separator'  => wc_get_price_decimal_separator(),        'thousand_separator' => wc_get_price_thousand_separator(),        'decimals'           => wc_get_price_decimals(),        'price_format'       => get_woocommerce_price_format(),    ) ) ) );
        $negative        = $price < 0;    $price           = apply_filters( 'raw_woocommerce_price', floatval( $negative ? $price * -1 : $price ) );    $price           = apply_filters( 'formatted_woocommerce_price', number_format( $price, $decimals, $decimal_separator, $thousand_separator ), $price, $decimals, $decimal_separator, $thousand_separator );
        if ( apply_filters( 'woocommerce_price_trim_zeros', false ) && $decimals > 0 ) {        $price = wc_trim_zeros( $price );    }
        $formatted_price = ( $negative ? '-' : '' ) . sprintf( $price_format, '<span class="woocommerce-Price-currencySymbol">' . get_woocommerce_currency_symbol( $currency ) . '</span>', $price );    $return          = '<span class="woocommerce-Price-amount amount">' . $formatted_price . '</span>';
        if ( $ex_tax_label && wc_tax_enabled() ) {        $return .= ' <small class="woocommerce-Price-taxLabel tax_label">' . WC()->countries->ex_tax_or_vat() . '</small>';    }
        return apply_filters( 'wc_price', $return, $price, $args );}

    Thats the total price part of the code. And this is the price per part.

    //packsize
            $packsz = get_post_meta(get_the_id(),'price_breakdown',true);
            if($packsz != ''){
                echo '<p class="packSize">'.$packsz.'</p>';
            }
    

 

Calculate percentage discount in php?

$
0
0

Hi! I need help! Stuck with this task

 

Have a set of products for example: A, B, C, D, E, F, G.

And also the conditions for the discount:
- 5% for any 3 products,
- 10% for any two goods + one of the goods "A" or "C"
- 15% of the total cost of the composition of products above 100 $
Prices for goods are random, but not more than $ 100
Need a method  that calculates the discount based on the entered product composition.
 
I see it like :
 
class test{
public $a = 10;

public $b = 15;
public $c = 20;
public $d = 30;

public $e = 40;

public $f = 50;

public $g = 60;

 

// do i need it in array 

 

public function share($A, $B, $C, $D, $E, $F, $G) {

$this->$a = $A; 

.........

if(){} //condition

}

}

$value = new test();

$value->share   //  

 

 

 

Maybe someone knows how to solve it in different way?

 

 

 

 

 

 

 

 

 

 

PHP I/O warning

$
0
0

Hi professionals

 

I am experiencing a huge generating error log file with the following output and error

 

[04-Dec-2017 19:14:44 Australia/Brisbane] PHP Warning:  simplexml_load_file(): I/O warning : failed to load external entity "<?xml version="1.0" encoding="UTF-8"?>
<geoPlugin>
<geoplugin_request>62.210.201.88</geoplugin_request>
<geoplugin_status>206</geoplugin_status>
<geoplugin_credit>Some of the returned data includes GeoLite data created by MaxMind, available from &lt;a href='http://www.maxmind.com'&gt;http://www.maxmind.com&lt;/a&gt;.</geoplugin_credit>
<geoplugin_city></geoplugin_city>
<geoplugin_region></geoplugin_region>
<geoplugin_areaCode>0</geoplugin_areaCode>
<geoplugin_dmaCode>0</geoplugin_dmaCode>
<geoplugin_countryCode>FR</geoplugin_countryCode>
<geoplugin_countryName>France</geoplugin_countryName>
<geoplugin_continentCode>EU</geoplugin_continentCode>
<geoplugin_latitude>48.8582</geoplugin_latitude>
<geoplugin_longitude>2.3387</geoplugin_longitude in public_html/files/currency/currency_converter.php on line 18
 
Here is some of the code in the currency_converter.php file lines 11 through to 26
 
if(isset($_SESSION['currency_code']) && empty($_SESSION['currency_code'])){
    unset($_SESSION['currency_code']);
}
if(!isset($_SESSION['currency_code']) && empty($_SESSION['currency_code'])){
    $xml = simplexml_load_file("http://www.geoplugin.net/xml.gp?ip=".$ip);
    $ip_currency = (string)$xml->geoplugin_currencyCode ;
    $currency_symbol=(string)$xml->geoplugin_currencySymbol;
    $geo_currency_code=(string)$xml->geoplugin_currencyCode;
    $_SESSION['currency_symbol']=$currency_symbol;
    $_SESSION['currency_code']=$geo_currency_code;
    if(empty($xml)){
        // If GeoPlugin Limit Exceeds use default
        $_SESSION['currency_symbol']='$';
        $_SESSION['currency_code']='AUD';
    }
}
 
 
I did not write this and i am not sure what to do to fix it.  Any ideas

How to show data from mysql database in decending order using pdo?

$
0
0

I am trying to show data using  "fetch(PDO::FETCH_desc" for show from descending order but it only works for assoc order like bellow code, how I can show it in descending order? I am new to php and pdo, please help.

$stmt = $DB_con->prepare(" SELECT name, id FROM class  ORDER BY id DESC  LIMIT 1, {$recordsPerPage}");
    $stmt->execute();
    echo $name;
   
    if($stmt->rowCount() > 0)
      
    {
        while($row=$stmt->fetch(PDO::FETCH_ASSOC))
        
        {
            extract($row);
            
            echo $name;
            
        }
    }
           
Viewing all 13200 articles
Browse latest View live