This sounds like an interesting problem. It sounds like you know how to do everything else on PHP, except the sockets.

I tend to think about these different then most legacy PHP applications. I like

I like to have my PHP and use it too...

I've used both extensively.
NodeJS and PHP both run server side.

Relative Features of Node:
  • Typically run standalone without apache or nginx
  • Is not multi threaded, but is defaulted as async (which makes it non-blocking)
  • It's javascript syntax (the more complex the feature, the less built out it is)
  • A lot of devs get super excited, build a library, then don't keep up with the next flavor of node
  • npm is cool, until its not. It supports windows, but will break pathing after a while.
  • hasn't been used a lot in ecommerce server side environments
  • Make sure your Database has a module.
  • Make sure you figure out how you are going to keep it running (as a service / cronjob?)
Relative Features of PHP
  • Typically run behind apache or nginx (standalone is considered beta, not for production)
  • Is not multithreaded and a single process is blocking (apache/nginex spawn multiple processes). Additional ReactPHP.
  • Php syntax - just happens to be very clean.
  • Composer is cool.
  • much more mature in the e-commerce space.
  • Your database is probably supported

I personally prefer PHP - it's more mature and I like the syntax.

This thread, good definition of irony.

I prefer windows 8 to other version of windows. Custom KDE over Gnome. I do not like the fractured file system that Linux defaults to for program installations. Nor do I like most Linux fonts. XP was dead to me before this post even started, before that I had xp64.

James, if you could mark the thread as resolved, that would be great! (Any future questions could easily fit their own thread)

Thank-you, Kyle

Ah, not quite as familiar with linux specific email details. However - if it is your own server, you'll probably want to setup sendmail (apt-get install sendmail). The settings are INI settings, they can be set at run time, or directly in the php.ini file. To find what settings are currently in place, add a new .php file to your web server and add this line to it: <?php phpinfo(); ?>. You'll be able to pull this up in the browser to see your current settings and the .INI location.

Additionally, based on the mail() documentation and possibly more relevant to your code example; what do you get by checking the return of calling 'mail'?

$wasAcceptedForDelivery = mail(...);
if (!$wasAcceptedForDelivery)
    die("<span class='failure'><h3>Sorry, Server not configured for e-mail.</h3></span>");

You are correct in your suspicion, you do need an SMTP server. If you are running in a Windows environment, the 'mail' function might use a built in Windows SMTP (which might need to be configured).

Here is the PHP documentation.
More specifically, the runtime configuration

Also, are you getting any specific error message? If not, what is your output? Do you have any PHP Ini settings for mail?

Hey Douglas,
I was wondering if this request is at a point of resolution. I understand there may be more (specific) questions.

It is always possible to reference this thread in future questions related to this topic as well.



Hello suneet,

Judging by your question, I think you might need an ajax style request built into the page. But there is another option.

You have a server / client interaction going on - php can only work on the server side, the client cannot interact directly. So, unless you want to navigate to a new page, you need to make an ajax query back to the server for the database information you are needing to lookup. That is, if you want to only push relevant information to the client.

The other option, is to load EVERYTHING into the client, then filter when they do something. This is probably much more expensive, if you have any decent size dataset.

Hi Ramsiva, this seems more like a Javascript question then a PHP question. If still relevant, I would suggest migrating this question there.

Just an FYI: str_replace is much more efficient then preg_replace. It's like using a bulldozer vs. a shovel.
(Also, please mark as solved, thank-you)

To Ips's point, I would recommend asort.
It also helps to reduce the 'scope' of the issue. You have a double array, but only the sort on the outer array is relevant. I've removed everything else. Now, you may not need asort if you don't care about the index. The 'printout' from the following method should clarify.

  public function ExplanationIndex()
        $data = [ // initialize everything
            'title' => 'User Group Permissions'            

        // sample 'file' list, unsorted.
        $file_list = ['z','y','x','w','a','b','c','d','e'];
        echo 'before';

        // initialize the array
        $controller_file_list = [];
        foreach ($file_list as $file)
            $controller_file_list[] = [
                'name' =>           $file.'name',
                'controller' =>     $file.'controller',
                'module' =>         [rand(0,100),rand(0,100),rand(0,100),rand(0,100),rand(0,100)],
                'install' =>        $file,
                'installed' =>      (bool)rand(0,1)

        echo 'after';
        $data['controller_files'] = $controller_file_list;

I will assume you've followed some of these steps already - I am mostly listing them to insure everyone is on the same page.

  • Web Server (phpserver of some sort)
  • Mail chimp oath secret and connnect (DO NOT DISCLOSE)
  • Database (you've confirmed you have one, and assuming mysql.)
  1. Find the appropriate API wrapper
  2. Initializing the wrapper
  3. Transferring data
Find the appropriate API wrapper

There are many API wrappers, and it would also be possible to write a direct API interface yourself. These are all located here on the MailChimp download page. The difference between the provided API's and writing your own is how the interaction occurs. If you write your own, you are writing direct restful'esque url requests to mailchimp. If you use a pre-built API, you require a file and then call into the required file (the mailchimp API docs might not be extremely useful at this point).

For the officail client, I would expect the documentation you referenced to be more useful, additionally - examples of usage are located here: examples.

Initializing the wrapper

Once you have the appropriate API Client downloaded and in place, you can 'require' it into your php code, initialize the class - then start calling onto the standard API methods.

  • require the client source php
  • register client with you secret key
  • Send a request through pre-built client.
  • Handle the response.
Transferring data ...

Hi Douglas,

Do you have any examples of what you've tried to date? I could write something in PHP that talks to the API, but without your input, it won't truly be helpful. Maybe some of the code area where you are looking to add the API call for an example.

Nightrain is an interesting Python wrapper of a PHP webserver running on localhost. It still uses up a port. Essentially, someone made a browser for PHP and burried all the browser elements to make it look like an application.

Yes, it does allow you to make a 'application' looking thing. However - in its current state you cannot even hide the console window in the background.

Currently, php can run standalone as a 'desktop application' - but it does not have a decent method for visual rendering (i.e. it runs command line). The optimum approach to convert to a Desktop application would involve php without a webserver running.

Anyhow, it is a good effort, it 'looks' like what you might want for an application - but it definately does not behave like one.

RikTelner commented: Thank you for your contribution. +2
diafol commented: havent tried it yet - good observation - thanks +15
Huge Disclaimer about security

The first, and most critical piece of information is that your query is vulnerable to an injection attack. In fact, your current problem is the equivalent to how an injection attack works.

Here's a not quite appreviated rundown of how PHP interacts with SQL. First, to run a query on SQL, you need a string in PHP select somevar from some table where table.col='value';. This works great. So we move to the next step of making the query dynamic and adding a variable. select somevar from sometable where table.col=$value;. This still seems fine, but in fact could be susceptible to an attack. For you see, the $value could really be ANY value. Let's say for example, $value = '2;drop sometable;'. Now, you run the full query as this: select somevar from sometable where table.col=2;drop sometable;. In your question, you are getting the value from a $_POST variable, meaning, anyone who can view the page can do anything to the database.

Security Suggestion

This would involve using something like the PDO driver, or the MYSQLi driver.

Examples for MySQLI
Examples for PDO

Converting to a Prepared Query will help to secure your application.

Specific variable issue

Now, finally, down to the exact issue:

  1. What is $y?
  2. What are you passing into $_POST['goodsDesc']?

A join might be what you are looking for. In order to join, you need to identify a map between the each table. For offersescription and odoffersimagegallery it would likely be spaid. I cannot tell what it would be for spa.

Sorry for typoes, on a phone atm.

A join would look like this:

Select, od OfferDescription, od.spaid, odf.offimgid, odf.offerimage, odf.offerPath from offerdescription od
Join odffersimagegallery odf on odf.spaid = od.spaid

$stockData = QueryForStock($connect);
echo BuildStockDataHtml($stockData, $connect);

 * @param link $connect
 * @return array
function QueryForStock($connect)
    $results = array();
    $query  = "SELECT sid, oqty, icode, item, iunit, icat FROM stock";

        $result = mysqli_query($connect, $query);

        while ($row = mysqli_fetch_array($result)) 
            $results[] = $row;

    catch(Exception $e)
        error_log($e . __FILE__.' '.__LINE__);
        $results = array();
    return $results;

function QueryForItemInward($sid, $connect)
    $results = array();

    $statement = mysqli_prepare($connect, "SELECT sum(qty) FROM purchase WHERE sid=?");
    mysqli_stmt_bind_param($statement,'i', $sid);

    return (int)$total;

function QueryForItemOutward($sid, $connect)
    $results = array();

    $statement = mysqli_prepare($connect, "SELECT sum(qty) FROM sales WHERE sid=?");
    mysqli_stmt_bind_param($statement,'i', $sid);

    return (int)$total;

function QueryDataForCurrentValue($sid, $connect)
    $query = <<<QUERY
select date, qty, rate, amt from stock st
join purchase p on st.sid = p.sid where st.sid = ?
union all
select date, -qty, rate, amt from stock st
join sales s on st.sid = s.sid where st.sid = ?
union all
select null, oqty, oprice, oamt from stock where sid = ?
order by date desc;

    $statement = mysqli_prepare($connect, $query);
    mysqli_stmt_bind_param($statement,'iii', $sid, $sid, $sid);
    $statement->bind_result( $date, $qty, $rate, $amt);

        $results[] = [ 'date' => $date, 'qty'=> $qty, 'rate' => $rate, 'amt' => $amt];


    return $results;

function BuildStockDataHtml(array $stockData, $connect)

    $tableRows = '';
    foreach($stockData as $stock)
        $inQuantity         = QueryForItemInward($stock['sid'], $connect);
        $outQuantity        = QueryForItemOutward($stock['sid'], $connect);
        $currentQuantity    = $stock['oqty'] + $inQuantity - $outQuantity;
        $costOfGoodsForSale = CostOfGoodsForSale($stock['sid'], $connect, $currentQuantity);

         $averageCostOfGoodsForSale = $costOfGoodsForSale / ...

It looks like this logic might be a little askew in cms.php:

$something = isset($_POST['user_name'])?$_POST['user_name']:'';
if($something) {

As you are attempting to pull it out of the session in cms.php after the login, it should be

$something = isset($_SESSION['user_name']) ? $_SESSION['user_name'] : null;
if ($something === null) {
    echo '<p>Not logged in.</p>';

(Just for reference, this is a continuation )

This can all likely be optimized. I wrote the CostOfGoodsForSale for a single SID.

You'll need to calculate the $countofgoodsforsale - good practice with PHP.
Then for the data table, it is the results from the query built into an array.

$sid = 1;
$query = <<<QUERY
select date, qty, rate, amt from stock st
join purchase p on st.sid = p.sid where st.sid = {$sid}
union all
select date, -qty, rate, amt from stock st
join sales s on st.sid = s.sid where st.sid = {$sid}
union all
select null, oqty, oprice, oamt from stock where sid = {$sid}
order by date desc;

$dataSet = array();
$result = mysql_query($query, $connection);
while(($row = mysql_fetch_array($result, 1) )!== false)
    $dataSet[] = $row;

// Determine the $countOfGoodsForSale

$finalResult = CostOfGoodsForSale($dataSet, $countOfGoodsForSale) / $countOfGoodsForSale;

If this answers your question, could you be so kind as to mark the question as resolved?

If you are inserting programmatically, you can determine the query failed then log the error and the query that you built to be sent to the server. Of course, you might be inserting a large collection, in which case you will need to use pritaeas' answer.

Indeed, cursors are intrinsically slow (but don't lock tables as much). What is preventing you from using a set based approach? What does your dataset look like? Constructing this type of query depends entirely on how well formed your data is.

(final query I used as well)

select date, qty, rate, amt from stock st
join purchase p on st.sid = p.sid where st.sid = 1
union all
select date, -qty, rate, amt from stock st
join sales s on st.sid = s.sid where st.sid = 1
union all
select null, oqty, oprice, oamt from stock where sid = 1
order by date desc;

sid 1: 37875
sid 2: 63000
sid 3: 32000
sid 4: 27400

Have you made any attempt to calculate the values yourself?

(if my site is up)View the results here
Here's my final function to calculate the cost of the current level of stock:

function CostOfGoodsForSale($dataSet, $countOfGoodsForSale)
    $totalPurchaseValue = 0;
    $totalPurchaseQty = 0;
    $done = false;
    foreach($dataSet as $row)
        // skip sales rows
        if ($row['qty'] < 0)

        for ($i=0; $i<$row['qty']; $i++ )
            $totalPurchaseValue += $row['rate'];

            if ($totalPurchaseQty == $countOfGoodsForSale)
                return $totalPurchaseValue;

    return $totalPurchaseValue;

If you do want to continue using login.php to run your sql query, as you are populating a session variable, then you would need to use the session variable in cms.php to get the username back out.

replace your 'post' check in cms.php with a $_SESSION check.

if (isset($_SESSION['user_name']))
    $username = $_SESSION['user_name'];

A word of caution:
Sessions can be insecure. Please read this article


The direct relationship between php and javascript is primarily one way. PHP on the server can be built out to print out javascript. However, javascript is a client side language. Once the code reaches the client, the only way to get back to the PHP is to return to the server (via Ajax or a new Webpage request).

This means you could build up your javascript array and send it back to the server to be handled by your array. But you cannot directly set a php value from javascript.

Solution Ideas
  1. You might try using jQuery as you are already using a framework.
  2. Another approach (with the basic concept) is a php form
  3. It is possible to do it without jquery, but if you aren't familiar with setting up ajax, cross browser support is already baked into jQuery.

I had taken the total amount for purchase and the original amount added these together and then subtracted the total amount of sales. I divided the resulting number by the final total qty

(totalPurchaseAmount + originalAmount - totalSalesAmount) / (totalPurchaseQty + OriginalQty - totalSalesQty)

How did you get 2@38000 from PVN 1?

Without the original:
((1 * 38000 + 20 * 38000 + 1 * 35000 +5 * 38000) - (1*45000 + 1 * 45000+2 * 45000+1 * 45000+1 * 45000)) / 21 = 35857

With the Original row included
((3*38000) + (1*38000 + 20*38000 + 1*35000 +5*38000) - (1*45000 + 1*45000+2*45000+1*45000+1*45000)) / (3+21) = 36125

This might be off course, but it was kind of interesting... For the 'test' data, I think this works:

select st.sid, (st.oamt + sum(something.totalv)) / (st.oqty+sum(totalqty)) as newRate, (st.oamt + sum(something.totalv)) as newAmount, (st.oqty+sum(totalqty)) as newQty from (   
select st.sid, sum(qty * rate) as totalv, sum(qty) as totalqty from stock st
join purchase p on st.sid = p.sid group by st.sid  -- where st.sid = 1
union all
select st.sid,  -sum(qty * rate) as totalv,  -sum(qty) as totalqty from stock st
join sales s on st.sid = s.sid group by st.sid -- where st.sid = 1;
) as something
join stock as st on st.sid = something.sid group by st.sid;

I get these results:

sid     New Rate    New Amount  New Qty
1       36125.0000  867000      24
2       60293.7500  964700      16
3       24615.3846  320000      13
4       27400.0000  685000      25

This 'works' because it isn't real time data. Meaning, the transactions have already been completed.

In the end, there are a lot of suggested approaches. A db is a heavy handed solution, imo, but it would also work. Regardless, I think the original question has been answered quite thoroughly.

Ah, a chat system. If you are using a single server(the most likely scenario), then you use that server's time.

You then make a client that each user would use to connect to the server. (a browser page for example) Any message must first be sent to the server, and then the server send it to the client (and a confirmation back to the original sender for their timestamp. The clients can then set the local time zone however you want to let them.

Another option is to not use a server and let each client set the time stamp for when it displays the message. The only potential drawback, is that two separate clients might have different timestamps for the same conversation. This is the easier approach.

One thing to note for a client application - unless run through browser requests, PHP is not a wonderful for installing on client boxes.

Added note: I think this was described, but you could also request the current time from a SQL server.

It depends on what you want as a source of truth for time. Using an alternate time source isn't a trivial problem. An easier approach that I would recommend, and use myself, is to keep the server/computer time synced and then just use the server/computer time inside of PHP.

Unfortunately, I don't know of any specific time servers or time applications to recommend