jeudi 13 août 2015

PHP MySQL ORDER BY level DESC LIMIT 1 not working on all searchs

I have searched for an answer to this problem all over the web and here at Stackoverflow. Nothing seems to help. This should be a very simple function. I have multiple records with the same content EXCEPT a field called level. I want to find the record with the highest int value in level. An example would be that I have multiple records with the same userid and email but the first record starts at level 1, the next may be level 2 and then the next may be level 1 again. I want to find the record with level = 2. My code is very simple.

  $LoginRS__query=sprintf("SELECT userid, email, level FROM orders WHERE userid=%s AND email=%s ORDER BY level DESC LIMIT 1", GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text"));

For some this works correctly, returning the record with level = 2, 3, 8, 9, whatever. For others it will only return the record with level = 1. The field level is int length 1. I'm running php Version 5.3.28 and MySQL 5.5.36

Any ideas anyone? Like most, I'm in a rush. Thanks...



via Chebli Mohamed

JSONException: End of input at character 0 of , i dont find the error in my code

i am searching for hours in the Internet and i dont know how i can handle this Error. I get empty content from my Inputstream. Maybe some one of you can look at my code where my error is.

public class SigninActivity  extends AsyncTask<String,Void,String> {
private TextView  testtext;
private Context context;
int code = 0;
View view;
String json = " ";
JSONObject jsonObj;


//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,View view, TextView testtext) {
    this.context = context;

    this.testtext = testtext;

    this.view = view;

}

protected void onPreExecute() {


}

@Override
protected String doInBackground(String... arg0) {

        try {
            String username = (String) arg0[0];
            String password = (String) arg0[1];



            String link = "http://ift.tt/1L9RGYe";
            String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
            data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");

            URL url = new URL(link);
            URLConnection conn = url.openConnection();

            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

            wr.write(data);
            wr.flush();
            Log.d("JSON Input stream", json.toString());


            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            Log.d("my JSON BufferedReader", json);
            StringBuilder sb = new StringBuilder();
            String line = null;

            // Read Server Response
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                Log.d("my JSON Server Response", json.toString());
                break;
            }


            this.json = sb.toString();


            return json;

        } catch (Exception e) {
            Log.e("Login Fail", e.toString());
            return new String("Exception: " + e.getMessage());
        }
    }


//@Override
protected void onPostExecute(String flag) {

    this.testtext.setText(flag);

    try
    {

        JSONObject json_data = new JSONObject(flag);
        Log.d("my", " JSON Object Parser" );
        int code= (json_data.getInt("code"));
        Log.d("my", " JSON get code");
        Log.d("my", String.valueOf(code));





        //int code =1 ;
        if(code==1)
        {
            Toast.makeText(context, "Login Successfully",
                    Toast.LENGTH_LONG).show();

            //Start des Hauptdingens
            Intent myIntent = new Intent(view.getContext(), MainActivity.class);
            // Start der Register Acitivty;
            //startActivityForResult(myIntent, 0);
            //startActivity(myIntent);
            //ActivityCompat.startActivityForResult(myIntent, 0);
            //finish();

        }
        else
        {
            Toast.makeText(context, "Sorry, Try Again",
                    Toast.LENGTH_LONG).show();
        }
    }
    catch(Exception e)
    {
        Log.e("my JSON Fail", e.toString());
    }
}

}

here i have my php file, i am not an expert at php maybe someone of you can help me :

<?php
$con=mysqli_connect("localhost","root","","my_db");
//echo "Welcome, I am connecting Android to PHP, MySQL";

if (mysqli_connect_errno($con))
{
//echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$username = $_POST['username'];
$password = $_POST['password'];



$result = mysqli_query($con,"SELECT Username FROM user where         Username='$username' and Password='$password'");



$flag['code'] =0;

if($result)
{
    $flag['code']=1;


} else {

    $flag['code'] = 0;

}

//print(json_encode($flag));
//echo json_encode($flag)


mysqli_close($con);
?>

i commented the echo lines out, because i read that this could make some errors, but this didnt help. the login with the post methode, but the resonse with flag doesnt work.

thanks for your help



via Chebli Mohamed

AJAX request to PHP - Handling response data

Im working on some AJAX login function, making a request via PHP. I am wondering how do I return data via the PHP so that I can handle it like the code mentioned below. I only worked on the javascript side and not the PHP server side so I am confused now.

I want to get a value/values stored in the response like data.name , data.sessionID , data.listOfnames

Is the data a JSON Object by itself? Thanks!

The code below was used before and has been verified to work.

function retrieveVersion(){
                                var URL = RSlink + "/updates";
                                $.ajax({
                                        headers : {
                                                "Content-Type" : "application/json; charset=UTF-8",
                                                "sessionid" : result
                                        },
                                        type : "GET",
                                        url : vURL,

                                        statusCode : {
                                                0 : function() {
                                                        hideLoadingMsg();
                                                        showError(networkError, false);
                                                },
                                                200 : function(data) {
                                                        currentVersion = String(data.version);
                                                        updatesArray=data.updates;
                                                        });
                                                        
                                                        }
                                                }
                                        });​


via Chebli Mohamed

Setting a Cookie if Hash is Valid in URL

what I'm doing is passing a hash in the URL from page1.php to page2.php which has been working fine so far but instead of setting $valid to TRUE I want to set a cookie.

Currently I have the code working like this:

if ($hash === md5($key.$test_time)) $valid = TRUE;

To set the cookie instead I tried this:

if ($hash === md5($key.$test_time))
//set "Cookie" for 24 hours
$cookie_value = "Cookie";
setcookie("Placed", $cookie_value, time()+86400);

I am getting these errors:

Notice: Undefined variable: cookie_value in /Dev/sites/files/page2.php on line 19

and

Warning: Cannot modify header information - headers already sent by (output started at /Dev/sites/files/page2.php:19) in /Dev/sites/files/page2.php on line 19

How do I fix this so I can set a cookie instead of a value?



via Chebli Mohamed

Email with php:[SMTP Error: Could not connect to SMTP host]

I have search many similar questions asked before but I still cannot find the solving method for this. Sorry for asking this question.

Below is my php coding using to send email:

<?php
require("class.phpmailer.php"); // path to the PHPMailer class

$mail = new PHPMailer();  

$mail->IsSMTP();  // telling the class to use SMTP
$mail->Mailer = "smtp";
$mail->Host = "ssl://smtp.gmail.com";
$mail->Port = 465;
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "testingtesting0330@gmail.com"; // SMTP username
$mail->Password = "xxxxxxxx"; // SMTP password 

$mail->From     = "testingtesting0330@gmail.com";
$mail->AddAddress("testingtesting0330@gmail.com");  

$mail->Subject  = "First PHPMailer Message";
$mail->Body     = "Hi! \n\n This is my first e-mail sent through PHPMailer.";
$mail->WordWrap = 50;  

if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
?>

The class.phpmailer.php file is placed in the same file with the previous php document. I have also changed the content of class.phpmailer.php as follow:

  var $Host        = 'ssl://smtp.gmail.com';

  var $Port        = 465;

I have also change the content of php.ini:

[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = smtp.gmail.com
; http://ift.tt/1cwgMO0
smtp_port = 465

; For Win32 only.
; http://ift.tt/1g9xnI4
sendmail_from = testingtesting0330@gmail.com

The openssl function is also enabled in php.ini:

extension=php_openssl.dll

It also show openssl enabled in php info.

But after this, the error did show again. So, I would like to ask for the solution for this.

Also, if I need to connect to a certain SMTP server, only change the coding and php.ini is enough?

Thank you guy very much. This is very important to me and hope this problem can be solved.

After you guy helping me, I have tried more method to solve the problem.

I have change the SMTPSecure from "ssl" to "tls".

$mail->SMTPSecure = 'tls';

The error change from "SMTP -> ERROR: Password not accepted from server" to >"SMTP -> ERROR: Failed to connect to server: php_network_getaddresses: >getaddrinfo failed: No such host is known"

Further, if I changed the host from smtp.gmail.com to my IP address,

the error became "ERROR: Failed to connect to server: connection attempt failed >because the connection object has for some time did not respond correctly, or >connection establishment failed because the host connection can not respond"

Many thanks to all of you.



via Chebli Mohamed

Cant post my links to my Facebook-pages

I have been looking like crazy for a solution to this problem but have not found what may be wrong. What I want to do is share my articles available on my website to all my Facebook pages.

To share articles on my private Facebook Wall is no proble. It works with the code below "// posting to profile"

require 'facebook.php';

    $facebook = new Facebook(array(
        'appId' => 'App ID',
        'secret' => 'Secret Code'
    ));


    if($facebook->getUser() == 0){
        $loginUrl = $facebook->getLoginUrl(array(
            scope => 'manage_pages,publish_actions'
        ));

        echo "<a href = '$loginUrl'>Login with facebook</a>";
    }
    else{

        //posting to pages

        $pages = $facebook->api('me/accounts');
        $id = $pages[data][0][id];
        $token = $pages[data][0][access_token];
        $api = $facebook->api($id . '', 'POST', array(
            access_token => $token,
            link => 'http://ift.tt/1UGjrJu',
            message => 'Se årets bästa överraskning: Så avslöjar mannen att frun är gravid.'
        ));

        //posting to profile
        $api = $facebook->api('me/feed', 'POST', array(
            link => 'http://ift.tt/1UGjrJu',
            message => 'Se årets bästa överraskning: Så avslöjar mannen att frun är gravid.'
        ));

        //displaying logout link
        echo

 "<br><a href = 'logout.php'>Logout</a>";
}



via Chebli Mohamed

Can't open index.php by default with Nginx on Amazon EC2

I cannot access index.php when I go to my Amazon EC2 public IP.

I have php5-fpm and php5-mysql installed.

It shows 404 error when I open http://publicIP/index.php.
I have my index.php file in /var/www/html.

The following is the contents of /etc/nginx/sites-enabled/

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /var/www/html;
    index index.php index.html index.htm;

    # Make site accessible from http://localhost/
    server_name _;

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            try_files $uri $uri/ =404;
            # Uncomment to enable naxsi on this location
            # include /etc/nginx/naxsi.rules
    }
    location ~ \.php$ {
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
    #       # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
    #
    #       # With php5-cgi alone:
            fastcgi_pass 127.0.0.1:9000;
    #       # With php5-fpm:
    #       fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            include fastcgi_params;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #       deny all;
    #}
}



via Chebli Mohamed

Getting length of var and creating a width

I have a banner background that is complex and the text blends into it so I need to add a background to this div so it shows the text given. Is there a way using PHP that I can get the length of the text and turn it into a px so I then can use it to set a width on the div?



via Chebli Mohamed

Changing Mysql functions to Mysqli breaks the script

I have this script that deletes a certain picture from the website. It's written with mysql functions so i wanted to update it to mysqli but doing so makes the script stop working. No die message from the script are shown no php errors and adding error_reporting(E_ALL); doesn't show any errors either.

Original script:

    if(isset($_POST['F3Verwijderen']))
    try 
    {                           
        //delete the file
        $sql = "SELECT PandFoto3 FROM tblpand WHERE `PK_Pand` = '".$pandid."'";

        $con = mysql_connect('WEBSITE.mysql', 'WEBSITE', 'PASS');
        if (!$con) {
        die('Could not connect: ' . mysql_error());
        }
        mysql_select_db("WEBSITE");
        $result = mysql_query($sql, $con);
        while ($row = mysql_fetch_array($result)) {                     
            if(file_exists($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3'])) {
                unlink($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3']);
            } else {
            echo $row['PandFoto3'];
            }
        }
        //delete the path url from the database field
        mysql_query("UPDATE tblpand SET PandFoto3 = NULL WHERE `PK_Pand` = '".$pandid."'");
        mysql_close($con);          


        header('Location: ../admin/pand-aanpassen.php?id='.$pandid);
    }

Updated to mysqli:

try 
    {                           
        //delete the file
        $sql = "SELECT PandFoto3 FROM tblpand WHERE `PK_Pand` = '".$pandid."'";

        $con = mysqli_connect('WEBSITE.mysql', 'WEBSITE', 'PASS');
        if (!$con) {
        die('Could not connect: ' . mysqli_error());
        }
        mysqli_select_db("WEBSITE");
        $result = mysqli_query($sql, $con);
        while ($row = mysqli_fetch_array($result)) {                        
            if(file_exists($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3'])) {
                unlink($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3']);
            } else {
            echo $row['PandFoto3'];
            }
        }
        //delete the path url from the database field
        mysqli_query("UPDATE tblpand SET PandFoto3 = NULL WHERE `PK_Pand` = '".$pandid."'");
        mysqli_close($con);         


        header('Location: ../admin/pand-aanpassen.php?id='.$pandid);
    }



via Chebli Mohamed

How to decode pagination in JSON?

I am trying to populate my website with products using the API of chinavasion.com. I've successfully fetch a list of products under a certain category but the response JSON only gives 10 products and a pagination which I literally don't know how to use, I'm guessing that it might be the one limiting the list of products echo'd?

Here is the sample JSON response:

{
 "products": [
  {
   "product_id": 19433,
   "model_code": "CVABR-C405",
   "short_product_name": "13.3 Inch Roof Mounted Car Monitor  ",
   "product_url": "http://ift.tt/1IM4Oio",
   "category_name": "Car Video",
   "category_url": "http://ift.tt/1DRy0FT",
   "subcategory_name": "Roof Monitors",
   "status": "In Stock"
  },
   .... and 9 more.

 "pagination": {
  "start": 0,
  "count": 10,
  "total": 53
 }
}

And here is my PHP so far, I just want to echo all the short product name of all the item, thing is I only get 10 items but there is a total of 53 items. (which can be seen on the sample JSON response pagination total)

<?php
$API_KEY = '4rxVx5-bxo7ldVQ5GcPSmX8XeqcSZoTnJnxF7xhRr8g.';
$url = "http://ift.tt/1IM4PD5";
$data = array(
'key' => $API_KEY,
'categories' => array('Car Video')
);

$content = json_encode($data);

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$json_response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE); 
curl_close($curl);

$response = json_decode($json_response, true);

foreach($response['products'] as $res)
{
    echo $res['short_product_name'],'<br />';
}
?>

So is there a way to fetch the other remaining 43 products at this point? I am not pretty sure if its possible or not as I am really pretty new to programming and haven't done JSON before, hope you guys can help me.



via Chebli Mohamed

I have looked through the q&a's and couldn't work out how to do it based from the answers

if I want to make

all requrests to localhost/[file/path]

to

localhost/something/[file/path]

what is the .htaccess

I have tried

RedirectMatch localhost/$ /something/

RedirectMatch ^/$ /something/



via Chebli Mohamed

Getting Next and Previous from MySQL When Dates Are the Same

Right now I have a problem because importing rows to my database from an external source happens so quickly.

If more than one row is created with the exact same publish date, it is impossible to sort by date and scroll through posts sequentially.

Let's say five rows are all generated at exactly 11:22:04 AM:

  • Row 1 - 11:22:04 AM
  • Row 2 - 11:22:04 AM
  • Row 3 - 11:22:04 AM
  • Row 4 - 11:22:04 AM
  • Row 5 - 11:22:04 AM

If a visitor is viewing Row 3 and wants "the next row" I am going to ask the database to give me the next row published later than or equal to 11:22:04 AM, which is going to be Row 1 no matter what I do.

  • If I don't say "or equal to" that would just mean that the visitor would never get to see Row 4 or Row 5, which is just as bad as always getting Row 1.
  • Adding the row ID to the order by clause doesn't help because -- again -- it's just going to always give me Row 1 (if I'm currently looking at Row 3).
  • Adding a greater than or less than to the where clause doesn't help because -- for example -- if I'm looking at Row 3 and I want "the next" row but say the ID needs to be greater than 3, I'm then never going to get Row 1.

I can cheat the system by updating every row in the database published at the exact same time with the row's ID as the seconds, which would turn the above records into:

  • Row 1 - 11:22:01 AM
  • Row 2 - 11:22:02 AM
  • Row 3 - 11:22:03 AM
  • Row 4 - 11:22:04 AM
  • Row 5 - 11:22:05 AM

That actually works very well. The problem is that new rows are added every time an administrator imports data, and I can't be constantly updating the database to correct this.

My queries to get next and previous look like this:

// next row
select  t.*
from    table t
where   t.postdate  >= '{$current_date}'
and     t.postdate  < now()
and     t.id        <> {$current_id}
order   by t.postdate
limit   1

// previous row
select  t.*
from    table t
where   t.postdate  <= '{$current_date}'
and     t.postdate  < now()
and     t.id        <> {$current_id}
order   by t.postdate desc
limit   1

(Yes, I have googled this extensively and reviewed several similar questions on Stackoverflow!)



via Chebli Mohamed

Long Polling don't works;

longpolling.js

function getContent( timestamp )
{
    var queryString = {"timestamp" : timestamp};

    $.ajax({
            type: "GET",
            url: '/php-long-polling-master/server/server.php',
            data: queryString, 
            sucess: function ( data ) {
            var obj = jQuery.parseJSON( data )[0];
            $( '#response' ).html( obj.content );       
            // reconnect with other timestamp from **server.php**
            getContent( obj.timestamp );
            }
    });
}


$( document ).ready ( function ()
{
    getContent();
});

server.php

<?php
require 'pdo.php';
set_time_limit(0);
while ( true )
{
    $requestedTimestamp = isset ( $_GET [ 'timestamp' ] ) ? (int)$_GET [ 'timestamp' ] : time();

    clearstatcache();

    $stmt = $pdo->prepare( "SELECT * FROM publication WHERE publication_time >= :requestedTimestamp" );

    $stmt->bindParam( ':requestedTimestamp', $requestedTimestamp );
    $stmt->execute();
    $rows = $stmt->fetchAll( PDO::FETCH_ASSOC );

    if ( count( $rows ) > 0 )
    {
        $json = json_encode( $rows );

        var_dump($rows);

        echo $json;
        break;


} else  {
    sleep( 2 );
    continue;
    }

}
?>

The problems:

  1. longpolling.js don't have a timestamp, the log shows: get /directory/directory/server.php instead server.php?timestamp=TimeInMilisseconds

  2. If don't have a timestamp, the server.php never will show results :|



via Chebli Mohamed

Yii Ajax returns whole webpage in LimeSurvey Plug-in environment. Why?

In the Plug-in environment of LimeSurvey I have the following code snipped in a view file which will print out two dependent dropdown lists:

<?php echo CHtml::dropDownList('survey_id', '', CHtml::listData(Survey::model()->active()->findAll(), 'sid', function($survey){return $survey->getLocalizedTitle()." ($survey->sid)";}), array(
        'ajax' => array(
        'type' => 'POST', //request type
        'cache' => false,
        'url' => 'direct?plugin=AcornReporting&function=MaturityLevels&action=dynamicResponses', //url to call.
        'update' => '#AcornMaturityLevels_response_id', //selector to update
        //'data'=>'js:javascript statement' 
        //leave out the data key to pass all form values through
    )));

    //empty since it will be filled by the other dropdown
    echo CHtml::dropDownList('response_id','', array(), array('style'=>'margin-left: 20px')); ?>

In the corresponding controller the following code should handle the ajax request:

public function actionDynamicResponses() {
    $data = CHtml::listData(Response::model($_POST['survey_id'])->findAll(), 'id', 'id');

    foreach ($data as $value => $name) {
        echo CHtml::tag('option', array('value' => $value), CHtml::encode($name), true);
    }
}

The Response as seen in chromes dev tool surprised me. The first line is what I expected. But what follows is a whole webpage whicht I do not know where it comes from.

<option value="1">1</option><!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
                <link rel="shortcut icon" href="/acorn/acorn-htmstyles/favicon.ico" type="image/x-icon" />
        <link rel="icon" href="/acorn/acorn-htmstyles/favicon.ico" type="image/x-icon" />
                        <link rel="stylesheet" type="text/css" href="/acorn/acorn-htm/third_party/qTip2/dist/jquery.qtip.min.css" />
<link rel="stylesheet" type="text/css" href="/acorn/acorn-htm/third_party/jquery-superfish/css/superfish.css" />
<link rel="stylesheet" type="text/css" href="/acorn/acorn-htm/third_party/jquery-notify/ui.notify.css" />
<link rel="stylesheet" type="text/css" href="/acorn/acorn-htm/tmp/assets/5dcd5e76/css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="/acorn/acorn-htm/tmp/assets/5dcd5e76/css/bootstrap-yii.css" />
<link rel="stylesheet" type="text/css" href="/acorn/acorn-htm/tmp/assets/7666aa2b/acorn.css" />
<link rel="stylesheet" type="text/css" href="/acorn/acorn-htm/styles/gringegreen/jquery-ui/jquery-ui.css" />
<link rel="stylesheet" type="text/css" href="/acorn/acorn-htm/styles/gringegreen/printablestyle.css" media="print" />
<link rel="stylesheet" type="text/css" href="/acorn/acorn-htm/styles/adminstyle.css" />
<link rel="stylesheet" type="text/css" href="/acorn/acorn-htm/styles/gringegreen/adminstyle.css" />
<link rel="stylesheet" type="text/css" href="/acorn/acorn-htm/styles-public/jquery.multiselect.css" />
<link rel="stylesheet" type="text/css" href="/acorn/acorn-htm/styles-public/jquery.multiselect.filter.css" />
<link rel="stylesheet" type="text/css" href="/acorn/acorn-htm/styles/gringegreen/displayParticipants.css" />
<link rel="stylesheet" type="text/css" href="/acorn/acorn-htm/tmp/assets/7165e62e/css/notify.css" />
<link rel="stylesheet" type="text/css" href="/acorn/acorn-htm/tmp/assets/b27bf437/nav.css" />
<link rel="stylesheet" type="text/css" href="/acorn/acorn-htm/tmp/assets/5dcd5e76/css/select2.css" />
<script type="text/javascript" src="/acorn/acorn-htm/third_party/jquery/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="/acorn/acorn-htm/tmp/assets/5dcd5e76/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/acorn/acorn-htm/third_party/jqueryui/js/jquery-ui-1.10.3.custom.min.js"></script>
<script type="text/javascript" src="/acorn/acorn-htm/third_party/qTip2/dist/jquery.qtip.min.js"></script>
<script type="text/javascript" src="/acorn/acorn-htm/third_party/jquery-superfish/js/superfish.js"></script>
<script type="text/javascript" src="/acorn/acorn-htm/third_party/jquery-superfish/js/hoverIntent.js"></script>
<script type="text/javascript" src="/acorn/acorn-htm/third_party/jquery-cookie/jquery.cookie.js"></script>
<script type="text/javascript" src="/acorn/acorn-htm/third_party/jquery-notify/src/jquery.notify.min.js"></script>
<script type="text/javascript" src="/acorn/acorn-htm/tmp/assets/5dcd5e76/js/bootstrap.bootbox.min.js"></script>
<script type="text/javascript" src="/acorn/acorn-htm/scripts/admin/admin_core.js"></script>
<script type="text/javascript" src="/acorn/acorn-htm/tmp/assets/13abf2bc/script.js"></script>
<script type="text/javascript" src="/acorn/acorn-htm/tmp/assets/b27bf437/nav.js"></script>
<script type="text/javascript">
/*<![CDATA[*/
LS.data = {"baseUrl":"http:\/\/localhost\/acorn\/acorn-htm","showScriptName":true,"urlFormat":"path","adminImageUrl":"\/acorn\/acorn-htm\/styles\/gringegreen\/images\/","csrfToken":"e5329206519e6671e4962fac47a933a29149dfb0","replacementFields":{"path":"\/acorn\/acorn-htm\/index.php\/admin\/limereplacementfields\/sa\/index"}};
$.ajaxSetup({data: {YII_CSRF_TOKEN: LS.data.csrfToken}});
LSdebug = {"session":{"adminlang":"en","LSWebUser":{"__returnUrl":"\/acorn\/acorn-htm\/index.php\/plugins\/","__id":"1","__name":"admin","__states":{},"plugin":"Authdb"},"loginID":1,"user":"admin","full_name":"Administrator","htmleditormode":"default","templateeditormode":"default","questionselectormode":"default","dateformat":"1","session_hash":"697c7382a18ddfd48d3ac4bd1d6f5dc70df1ba2c4a86a2dffb8145896438ee95","USER_RIGHT_INITIALSUPERADMIN":1,"just_logged_in":true,"loginsummary":"<br \/>Welcome Administrator!<br \/>&nbsp;"},"server":{"HTTP_HOST":"localhost","HTTP_CONNECTION":"keep-alive","CONTENT_LENGTH":"231","HTTP_ACCEPT":"*\/*","HTTP_ORIGIN":"http:\/\/localhost","HTTP_X_REQUESTED_WITH":"XMLHttpRequest","HTTP_USER_AGENT":"Mozilla\/5.0 (X11; Linux x86_64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/44.0.2403.155 Safari\/537.36","CONTENT_TYPE":"application\/x-www-form-urlencoded; charset=UTF-8","HTTP_REFERER":"http:\/\/localhost\/acorn\/acorn-htm\/index.php\/plugins\/direct?plugin=AcornReporting&function=MaturityLevels&action=create","HTTP_ACCEPT_ENCODING":"gzip, deflate","HTTP_ACCEPT_LANGUAGE":"de-CH,de;q=0.8,en;q=0.6,de-DE;q=0.4,en-US;q=0.2","HTTP_COOKIE":"YII_CSRF_TOKEN=e5329206519e6671e4962fac47a933a29149dfb0; PHPSESSID=8sc7m2t2df348epd8his1c9vn7","HTTP_DNT":"1","PATH":"\/usr\/local\/sbin:\/usr\/local\/bin:\/usr\/sbin:\/usr\/bin:\/sbin:\/bin","SERVER_SIGNATURE":"<address>Apache\/2.4.7 (Ubuntu) Server at localhost Port 80<\/address>\n","SERVER_SOFTWARE":"Apache\/2.4.7 (Ubuntu)","SERVER_NAME":"localhost","SERVER_ADDR":"127.0.0.1","SERVER_PORT":"80","REMOTE_ADDR":"127.0.0.1","DOCUMENT_ROOT":"\/var\/www\/html","REQUEST_SCHEME":"http","CONTEXT_PREFIX":"","CONTEXT_DOCUMENT_ROOT":"\/var\/www\/html","SERVER_ADMIN":"webmaster@localhost","SCRIPT_FILENAME":"\/var\/www\/html\/acorn\/acorn-htm\/index.php","REMOTE_PORT":"33729","GATEWAY_INTERFACE":"CGI\/1.1","SERVER_PROTOCOL":"HTTP\/1.1","REQUEST_METHOD":"POST","QUERY_STRING":"plugin=AcornReporting&function=MaturityLevels&action=dynamicResponses","REQUEST_URI":"\/acorn\/acorn-htm\/index.php\/plugins\/direct?plugin=AcornReporting&function=MaturityLevels&action=dynamicResponses","SCRIPT_NAME":"\/acorn\/acorn-htm\/index.php","PATH_INFO":"\/plugins\/direct","PATH_TRANSLATED":"\/var\/www\/html\/plugins\/direct","PHP_SELF":"\/acorn\/acorn-htm\/index.php\/plugins\/direct","REQUEST_TIME_FLOAT":1439512250.393,"REQUEST_TIME":1439512250}};
console.dir(LSdebug)

LS.messages=[];
/*]]>*/
</script>
<title>Limesurvey Administration</title>
    </head>
    <body>
        <div class="wrapper clearfix">
            <div id="notify-container" style="display:none;">
    <div id="default-notify"  class="ui-state-highlight ui-corner-all">
        <p>
            <a class="ui-notify-close" href="#"><span class="ui-icon ui-icon-close" style="float:right">&nbsp;</span></a>
            <span style="float:left; margin:2px 5px 0 0;" class="ui-icon ui-icon-info">&nbsp;</span>
            #{message}
        </p>
    </div>
    <div id="error-notify"  class="ui-state-highlight ui-corner-all ui-state-error error">
        <p> 
            <a class="ui-notify-close" href="#"><span class="ui-icon ui-icon-close" style="float:right">&nbsp;</span></a>
            <span style="float:left; margin:2px 5px 0 0;" class="ui-icon ui-icon-alert">&nbsp;</span>
             #{message}
        </p>
    </div>
    <!-- ui-state-success doesn't exist -->
    <div id="success-notify"  class="ui-state-highlight ui-corner-all ui-state-success success">
        <p>
            <a class="ui-notify-close" href="#"><span class="ui-icon ui-icon-close" style="float:right">&nbsp;</span></a>
            <span style="float:left; margin:2px 5px 0 0;" class="ui-icon ui-icon-alert">&nbsp;</span>
             #{message}
        </p>
    </div>
</div>
            <div class="maintitle titlebar">Acorn Human and Talent Management</div>            <div class="menubar">
    <div class="menubar-title ui-widget-header"><div class="menubar-title-left"><strong>Administration</strong> -- Logged in as:<strong><a href="/acorn/acorn-htm/http://ift.tt/1IM4NLn"> admin <img src="/acorn/acorn-htm/styles/gringegreen/images/profile_edit.png" alt="Edit your personal preferences" /></a></strong></div></div><nav class="menubar"><ol class="menubar-left level0"><li><a href="/acorn/acorn-htm/http://ift.tt/1DRxYxJ"><img src="/acorn/acorn-htm/styles/gringegreen/images/home.png" alt="Default administration page" /></a></li><li><img src="/acorn/acorn-htm/styles/gringegreen/images/separator.gif" alt="" /></li><li><a href="/acorn/acorn-htm/index.php/admin/user"><img src="/acorn/acorn-htm/styles/gringegreen/images/security.png" alt="Manage survey administrators" /></a></li><li><a href="/acorn/acorn-htm/http://ift.tt/1IM4NLp"><img src="/acorn/acorn-htm/styles/gringegreen/images/usergroup.png" alt="Create/edit user groups" /></a></li><li><a href="/acorn/acorn-htm/http://ift.tt/1DRxYxL"><img src="/acorn/acorn-htm/styles/gringegreen/images/global.png" alt="Global settings" /></a></li><li><img src="/acorn/acorn-htm/styles/gringegreen/images/separator.gif" alt="" /></li><li><a href="/acorn/acorn-htm/http://ift.tt/1IM4P6c"><img src="/acorn/acorn-htm/styles/gringegreen/images/checkdb.png" alt="Check data integrity" /></a></li><li><a href="/acorn/acorn-htm/http://ift.tt/1DRxYxN"><img src="/acorn/acorn-htm/styles/gringegreen/images/backup.png" alt="Backup entire database" /></a></li><li><img src="/acorn/acorn-htm/styles/gringegreen/images/separator.gif" alt="" /></li><li><a href="/acorn/acorn-htm/http://ift.tt/1IM4P6e"><img src="/acorn/acorn-htm/styles/gringegreen/images/labels.png" alt="Edit label sets" /></a></li><li><img src="/acorn/acorn-htm/styles/gringegreen/images/separator.gif" alt="" /></li><li><a href="/acorn/acorn-htm/http://ift.tt/1DRxYxR"><img src="/acorn/acorn-htm/styles/gringegreen/images/templates.png" alt="Template editor" /></a></li><li><img src="/acorn/acorn-htm/styles/gringegreen/images/separator.gif" alt="" /></li><li><a href="/acorn/acorn-htm/http://ift.tt/1IM4NLv"><img src="/acorn/acorn-htm/styles/gringegreen/images/cpdb.png" alt="Central participant database/panel" /></a></li><li><a href="/acorn/acorn-htm/index.php/plugins"><img src="/acorn/acorn-htm/styles/gringegreen/images/plugin.png" alt="Plugin manager" /></a></li><li><a href="http://localhost/acorn/acorn-htm/index.php/plugins/direct?plugin=AcornReporting&amp;function=Cockpit"><img src="/acorn/acorn-htm/styles/gringegreen/images/bounce.png" alt="Acorn Reporting" /></a></li></ol><ol class="menubar-right level0"><li><label for="surveyid">Surveys:</label><select class="select" id="surveyid" data-route="admin/survey/sa/view" name="surveyid">
<option value=""></option>
<optgroup label="Expired">
<option value="142833">(Demo) 3 Groups, some questions</option>
<option value="91">Acorn TM Survey with 2 Ems</option>
<option value="957916">ATM Survey active</option>
<option value="296591">ATM Survey finished</option>
<option value="92">ATM Survey, EM test</option>
<option value="134138">Deutsche Börse AG, V0.1</option>
<option value="678544">Short survey for testing EM class</option>
<option value="116811">V0.1 Test</option>
</optgroup>
<optgroup label="Inactive">
<option value="957791">Acorn HTM V0.1</option>
<option value="944555">Acorn Talent Management Survey</option>
<option value="356369">All groups, some questions</option>
<option value="543114">Copy1 of ATMS</option>
<option value="14272">Test of EM question attributes</option>
<option value="532311">v1.0 All Questions</option>
<option value="912161">V2.0 All Questions für Testing</option>
</optgroup>
</select></li><li><a href="/acorn/acorn-htm/http://ift.tt/1IM4NLx"><img src="/acorn/acorn-htm/styles/gringegreen/images/surveylist.png" alt="Detailed list of surveys" /></a></li><li><a href="/acorn/acorn-htm/http://ift.tt/1DRy0pm"><img src="/acorn/acorn-htm/styles/gringegreen/images/add.png" alt="Create, import, or copy a survey" /></a></li><li><img src="/acorn/acorn-htm/styles/gringegreen/images/separator.gif" alt="" /></li><li><a href="/acorn/acorn-htm/http://ift.tt/1IM4NLB"><img src="/acorn/acorn-htm/styles/gringegreen/images/logout.png" alt="Logout" /></a></li><li><a href="http://ift.tt/1DRy1tf"><img src="/acorn/acorn-htm/styles/gringegreen/images/showhelp.png" alt="LimeSurvey online manual" /></a></li></ol></nav></div>
            <div id="content">
            <div class="acorn-page" >
    <nav class="menubar acorn-menu clearfix">
    
        <h1 class="acorn-plugin-title">Acorn Plugin</h1>
        
        <ol class="menubar-left level0"><li><a href="/acorn/acorn-htm/http://ift.tt/1IM4NLD"><img src="/acorn/acorn-htm/plugins/AcornReporting/assets/images/glyphicons/glyphicons_040_stats.png" alt="Cockpit" /></a></li><li><a href="/acorn/acorn-htm/http://ift.tt/1DRy0po"><img src="/acorn/acorn-htm/plugins/AcornReporting/assets/images/glyphicons/glyphicons-547-quote.png" alt="Texts" /></a></li><li><a href="/acorn/acorn-htm/http://ift.tt/1IM4Pms"><img src="/acorn/acorn-htm/plugins/AcornReporting/assets/images/glyphicons/glyphicons-69-ruler.png" alt="Rules" /></a></li><li><a href="/acorn/acorn-htm/http://ift.tt/1DRy0pq"><img src="/acorn/acorn-htm/plugins/AcornReporting/assets/images/glyphicons/glyphicons-140-adjust-alt.png" alt="Rulesets" /></a></li><li><a href="/acorn/acorn-htm/http://ift.tt/1IM4O1S"><img src="/acorn/acorn-htm/plugins/AcornReporting/assets/images/glyphicons/glyphicons-609-newspaper.png" alt="Reports" /></a></li><li><a href="/acorn/acorn-htm/http://ift.tt/1DRy0pt"><img src="/acorn/acorn-htm/plugins/AcornReporting/assets/images/glyphicons/glyphicons-37-file.png" alt="Report Templates" /></a></li><li><a href="/acorn/acorn-htm/http://ift.tt/1IM4O1X"><img src="/acorn/acorn-htm/plugins/AcornReporting/assets/images/glyphicons/glyphicons_323_calculator.png" alt="Maturity Levels" /></a></li><li><a href="/acorn/acorn-htm/http://ift.tt/1DRy1th"><img src="/acorn/acorn-htm/plugins/AcornReporting/assets/images/glyphicons/glyphicons_043_group.png" alt="Customers" /></a></li></ol>        
        
    </nav>    
    <ul class="nav pull-right acorn-dropdown-menu" style="width:160px" id="yw0">
<li class="dropdown user"><a class="dropdown-toggle" data-toggle="dropdown" href="#"><i class="icon-user"></i><span class="username">Development</span> <i class="icon-angle-down"></i></a>
<ul class="dropdown-menu">
<li><a href="/acorn/acorn-htm/http://ift.tt/1IM4O21"><i class="icon-road"></i>Unit Test controller</a></li>
<li><a href="/acorn/acorn-htm/http://ift.tt/1IM4O23"><i class="icon-warning-sign"></i>EM in action</a></li>
<li><a href="/acorn/acorn-htm/http://ift.tt/1DRy0FK"><i class="icon-thumbs-up"></i>Unit Test EM</a></li>
<li><span></span></li>
<li><a href="#"><i class="icon-tasks"></i>Task</a></li>
</ul>
</li>
</ul>    

    
    <div class="container acorn-content">
            </div>
</div>

            </div>
            <div id="ajaxprogress" title="Ajax request in progress" style="text-align: center">
                <img src="/acorn/acorn-htm/styles/gringegreen//images/ajax-loader.gif"/>
            </div>
        </div>
        <div class='footer'>
    <div style='float:left;width:110px;text-align:left;'>
        <a href='http://ift.tt/1IM4PmG'><img alt='LimeSurvey - Online manual' title='LimeSurvey - Online manual' src='/acorn/acorn-htm/styles/gringegreen/images/docs.png' /></a>
    </div>
    <div style='float:right;'>
        <a href='http://ift.tt/1DRy0FM'><img alt='Support this project: Donate to LimeSurvey' title='Support this project: Donate to LimeSurvey!' src='/acorn/acorn-htm/styles/gringegreen/images/donate.png'/></a>
    </div>
    <div class='subtitle'><a class='subtitle' title='Visit our website!' href='http://ift.tt/qwV5um' target='_blank'>LimeSurvey</a><br />Version 2.05+ Build 150211</div>
</div>    <script type="text/javascript" src="/acorn/acorn-htm/tmp/assets/7165e62e/js/notify.js"></script>
<script type="text/javascript" src="/acorn/acorn-htm/tmp/assets/5dcd5e76/js/select2.js"></script>
<script type="text/javascript">
/*<![CDATA[*/
jQuery(function($) {
jQuery('a[rel="tooltip"]').tooltip();
jQuery('a[rel="popover"]').popover();
jQuery('#surveyid').select2({'minimumResultsForSearch':10,'placeholder':'Please choose...'});
});
/*]]>*/
</script>
</body>

</html>

Due to that, the dropdown list can not be updated.

What went wrong and how do I fix this?



via Chebli Mohamed

POST String From Android To Php

I'm having trouble posting a String from android to php. I'm trying to post a username since I was to exclude the current users username from the query. In Java I have an AsyncTask with the code below in the doInBackground(String... params)

ArrayList<NameValuePair> data_to_send = new ArrayList<>();
    data_to_send.add(new BasicNameValuePair("Username", username));

    HttpParams httpRequestParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpRequestParams, ServerRequests.CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpRequestParams, ServerRequests.CONNECTION_TIMEOUT);


    HttpClient client = new DefaultHttpClient(httpRequestParams);
    HttpPost post = new HttpPost(ServerRequests.SERVER_ADDRESS + "TestQuery.php");

    try {
        post.setEntity(new UrlEncodedFormEntity(data_to_send));
        client.execute(post);
    } catch (Exception e) {

        e.printStackTrace();
    }

And this is in my php:

$origLat = 45.6215349;
$origLon = 18.6951613;
$dist = 30; 
$username = $_POST["Username"];

$sql = "SELECT ID, Username, Name, Age, City, Gender, Latitude, Longitude, 3956 * 2 * 1.609344 * 1000 *
      ASIN(SQRT( POWER(SIN(($origLat - abs(Latitude))*pi()/180/2),2)
      +COS($origLat*pi()/180 )*COS(abs(Latitude)*pi()/180)
      *POWER(SIN(($origLon-Longitude)*pi()/180/2),2))) 
      as distance FROM users WHERE Username != '$username'
      AND Longitude BETWEEN ($origLon-$dist/abs(cos(radians($origLat))*69)) 
      AND ($origLon+$dist/abs(cos(radians($origLat))*69)) 
      AND Latitude BETWEEN ($origLat-($dist/69)) 
      AND ($origLat+($dist/69))
      HAVING distance < $dist ORDER BY distance limit 30;"; 

Well the query works when I input the String directly by changing the Username != 'Jawe' but I'm not sure why it doesn't work when posted from Android. Anyone know the problem?



via Chebli Mohamed

How to set a permission in FTP after creating a directory using PHP?

I have a problem with my code. In my code there is a part that can generate a directory in the server and when I checked the directory in the FTP the initial folder is generated but the subfolders are not and when I try to open the main folder there is a log that says:

esponse:    550 /httpdocs/ecommerce/image/catalog/sellers/826: Permission denied
Error:  Failed to retrieve directory listing

In my code I have this:

public function addUser($data) {

    $this->db->query("INSERT INTO `" . DB_PREFIX . "user` SET username = '" . $this->db->escape($data['username']) . "', shop_name = '" . $this->db->escape($data['shop_name']) . "', user_group_id = '" . (int)$data['user_group_id'] . "', salt = '" . $this->db->escape($salt = substr(md5(uniqid(rand(), true)), 0, 9)) . "', password = '" . $this->db->escape(sha1($salt . sha1($salt . sha1($data['password'])))) . "', firstname = '" . $this->db->escape($data['firstname']) . "', lastname = '" . $this->db->escape($data['lastname']) . "', email = '" . $this->db->escape($data['email']) . "', image = '" . $this->db->escape($data['image']) . "', status = '" . (int)$data['status'] . "', date_added = NOW()");
    $get_customer_id = $this->db->getLastId();

    $directory = DIR_IMAGE . 'catalog/sellers/' . $get_customer_id;

    if(!file_exists($directory)) {

        mkdir($directory, 777);

        mkdir($directory . '/profile', 777);
        mkdir($directory . '/banner', 777);
        mkdir($directory . '/products', 777);

    }

}

In my localhost it is working properly but when I upload it has an error. Can you help me with this?



via Chebli Mohamed

How do I reverse engineer an existing browser based application to create my own version?

I am using an existing browser based application that is being obsoleted by the company which owns it and will no longer be supported. I want to capture and copy as much of the functionality as possible before it goes away. How can I copy the basic funcionality of the html, php, etc. by accessing the source files and reverse engineering the site?



via Chebli Mohamed

Javascript validate human field for contact form

OK, I have tried getting my contact form to work trying to update the php - with no success. Thank you to those of you who attempted to help with my previous question. I now think I should be able to get this to work by updating the JS, but of course I know about as much JS as I do PHP!

So here we go again...

I have a contact form I am using in a Bootstrap responsive single-page site. The form works just fine and sends the emails just fine. My site does not get a whole lot of traffic and I dislike the Captcha fields, so I wanted to insert a simple field for users to enter to ensure they are human. I added a simple math question. Now, I need to know how to validate that the user entered the correct math answer before the email is processed.

My form uses a contact_me.js file in combination with the jqBootstrapBalidation.js file to validate and send the form to the contact_me.php to process the email. I tried updating the PHP (with some suggestions from here) but I could not get it to work. It will always send the email through even if the math answer was entered incorrectly.

It is important to note that I did not write the code for this, I am very new to js. The form and code was supplied by startbootstrap.com templates.

Looking at the contact_me.js field, I can see that it starts off validating the fields with the jqBootstrapBalidation.js. I see it then moves down to a preventDefault and has a comment stating "prevent spam click and default submit behaviour. Is this code already preventing SPAM emails here?

If it is not, I want to force the user to input the correct answer to the math question. I added this field myself. I added the variable for the human field to the contact_me.js file (I assume I needed to do this) to get the value from the form.

Further down on the .js file it then uses ajax to post to the contact_me.php to process the email. Below this is where it looks like it further validates the fields and displays the success/error messages. Is there someplace here I can verify if the user entered the correct math equation (answer should be =5) and if it is correct, then to process the email via the contact_me.php and if the answer is incorrect then to display an error message without sending to the php and ask to try again? Below is the html, contact_me.js and the contact_me.php. Thank you so much for your help with this!

HTML:

 <form name="sentMessage" id="contactForm" novalidate>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Name</label>
                            <input type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">
                            <p class="help-block text-danger"></p>
                        </div>
                    </div>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Email Address</label>
                            <input type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
                            <p class="help-block text-danger"></p>
                        </div>
                    </div>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Phone Number</label>
                            <input type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">
                            <p class="help-block text-danger"></p>
                        </div>
                    </div>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Message</label>
                            <textarea rows="5" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>
                            <p class="help-block text-danger"></p>
                        </div>
                    </div>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Human</label>
                            <input type="text" class="form-control" placeholder="Two + 3 = ?" id="human" required data-validation-required-message="Please solve math equation to prove you are human">
                            <p class="help-block text-danger"></p>
                        </div>
                    </div>
                     <br>
                    <div id="success"></div>
                    <div class="row">
                        <div class="form-group col-xs-12">
                            <button type="submit" class="btn btn-success btn-lg">Send</button>
                        </div>
                    </div>
                  </form>

contact_me.js:

  $(function() {

$("input,textarea").jqBootstrapValidation({
    preventSubmit: true,
    submitError: function($form, event, errors) {
        // additional error messages or events
    },
    submitSuccess: function($form, event) {
        // Prevent spam click and default submit behaviour
        $("#btnSubmit").attr("disabled", true);
        event.preventDefault();

        // get values from FORM
        var name = $("input#name").val();
        var email = $("input#email").val();
        var phone = $("input#phone").val();
        var message = $("textarea#message").val();
        var human = $("textarea#human").val();
        var firstName = name; // For Success/Failure Message
        // Check for white space in name for Success/Fail message
        if (firstName.indexOf(' ') >= 0) {
            firstName = name.split(' ').slice(0, -1).join(' ');
        }
        $.ajax({
            url: "././mail/contact_me.php",
            type: "POST",
            data: {
                name: name,
                phone: phone,
                email: email,
                message: message,
                human: human
            },
            cache: false,
            success: function() {
                // Enable button & show success message
                $("#btnSubmit").attr("disabled", false);
                $('#success').html("<div class='alert alert-success'>");
                $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                    .append("</button>");
                $('#success > .alert-success')
                    .append("<strong>Your message has been sent. </strong>");
                $('#success > .alert-success')
                    .append('</div>');

                //clear all fields
                $('#contactForm').trigger("reset");
            },
            error: function() {
                // Fail message
                $('#success').html("<div class='alert alert-danger'>");
                $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                    .append("</button>");
                $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                $('#success > .alert-danger').append('</div>');
                //clear all fields
                $('#contactForm').trigger("reset");
            },
        })
    },
    filter: function() {
        return $(this).is(":visible");
    },
});

$("a[data-toggle=\"tab\"]").click(function(e) {
    e.preventDefault();
    $(this).tab("show");
});
});

// When clicking on Full hide fail/success boxes
$('#name').focus(function() {
$('#success').html('');
});

contact_me.php:

<?php
// Check for empty fields
if(empty($_POST['name'])        ||
empty($_POST['email'])      ||
empty($_POST['phone'])      ||
empty($_POST['message'])    ||
empty($_POST['human'])  ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}

//Check if simple anti-bot test is correct
if ($human !== 5) {
   $errHuman = 'Your anti-spam is incorrect';
}   

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$message = $_POST['human'];

// Create the email and send the message
$to = 'info@mysite.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Portfolio Website Message:  $name";
$email_body = "You have received a new message from your portfolio website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@mysite.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address"; 
mail($to,$email_subject,$email_body,$headers);
return true;            
?>



via Chebli Mohamed

How do I verify that a update message is successful in MySQL with PHP?

I am having no issue running a select statement but I keep having issues running this update statement, even without where criteria being specified. I have tried everything from defining the sql statement with single quotes, concatenation, calling the sql statement via mysqli and etc but I don't get any error messages that let me know what the actual problem is. The login user has privileges to select, update, and insert so as to separate from the root user and autocommit has been turned off via mysqlworkbench. The html of course is a one page app that submits the form to itself with a select element named p_game, with one of the options being Game A.

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    echo 'Posted.';
    if ( !empty($_POST['p_game'])) {
        echo 'Got here';
        $p_game = $conn->real_escape_string(trim($_POST['p_game']));
        $sql = "UPDATE db_name.football_games set home_score = 50, away_score = 100 where name = ''$p_game''";

        try{
            $result = $conn->query($sql);
            echo $sql;
            $conn->commit();
            echo 'Commit worked.';
        }

        catch(Exception $e) {
            echo $e->getMessage();
        }

    }
    else {
        echo 'Game name not found';
    }
}



via Chebli Mohamed

jquery return error msg from php server not showing in div

i have a simple code for js on my side and wanted to return the error msg from my php json server side if there is an error such like custom msg

php

<?php
header('Content-Type: text/html; charset=utf-8');
require_once('class/MysqliDb.php');
$db = new Mysqlidb();
$cols = array("card_id","card_os");

$cards = $db->get("cards",null,$cols);
if($db->count >0){
$cards['status'] = 'success';
} else {
$cards['status'] = 'fail';
$cards['error'] = 'fail to insert';
}
echo json_encode($cards);
?>

as for my js

 $(document).ready(function() {
 $.post('./get_cards.php',$(this).serialize(),function(msg){


 if(msg.status == 'success'){
 $('#cardlist').html(format(msg));                        
 }
 else if(msg.status == 'fail') {
  console.log(msg.error);
 $('#cardlist').html(msg.error);
 }
 },'json');

 } );

i am trying to have my #cardlist div to have this error msg 'fail to insert' from my server side. It is not showing the msg in the div but instead when is there is data is populating correctly.



via Chebli Mohamed

Wordpress, creating a different website on a subdirectory

I got a wordpress website on the main domain and in a subdirectory I want got another third-party web application I would like to run.

Eg. www.example.com <-- stores the main Wordpress website http://ift.tt/1sHWriz <-- runs a third party web application.

Is this possible or should I host the web application in a subdomain instead?



via Chebli Mohamed

PHPMailer MySQLi multiple email addresses

I am at the end of my rope and would really really appreciate any help you could spare...

I have the following code and although it works on an individual basis, I can for the life of me not make it work so that all email addresses are sent at the same time using PHPMailer.

I have scoured StackOverflow for the past few months, trying an exhaustive amount of combinations without success. There are a number of discussions on this forum and although I have tried all the solutions on here, I can still not make it work. If I offend anyone by potentially duplicating the question, please accept my apologies in advance.

// Require the form_functions to process the form
    require('databaseConnect.php');

    // Require the Email Class Functions
    require("class.phpmailer.php");
    require("class.smtp.php");

    // User Not Purchased               
        $result = mysqli_query($databaseConnect, "SELECT fname, email FROM table WHERE condition = 'condition' LIMIT 50");

        /* fetch associative array */
        while($row = $result->fetch_array()){
            $rows[] = $row; 
        }

        foreach($rows as $row) {
            $userFname = $row["fname"];
            $userEmail = $row["email"];
        }

$mail = new PHPMailer();

$mail->IsSMTP(); // Telling the Class to use SMTP

$mail->SetFrom("No_Reply@girrawaagames.com", "Girrawaa Games"); // Valid email address from sender and Company name. Only Company name will be displayed

//$mail->AddAddress("$userEmail");

$addr = explode(',',$userEmail);

foreach($addr as $ad) {
$mail->AddAddress(trim($ad));
}

$mail->Subject='CASH Trader'; // This adds the subject title in the subkect line field

$mail->AddAttachment('attachement.doc'); // This adds the file to be attached to the email 

$mail->Body="<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://ift.tt/kkyg93\">
<html xmlns=\"http://ift.tt/lH0Osb\">
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<title>CASH Trader</title>
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />

</head>

<body yahoo bgcolor=\"#ccffff\" style=\"margin:0; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px;\">
        <tr>
            <td bgcolor=\"#ffffff\" style=\"padding-top:40px; padding-right:30px; padding-bottom:20px; padding-left:30px;\">
                <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">
                    <tr>
                        <td align=\"center\" style=\"color:#153643; font-family:Arial, Helvetica, sans-serif; font-size:24px;\">
                        <b>Hi " . $userFname . "</b>
                        </td>
                    </tr>
                </table>
              </td>
         </tr>

</body>
</html>";

            if($mail->send()){
                $updateCampaign = "UPDATE table SET row = 'value' WHERE email = '$userEmail'";
                $result = mysqli_query($databaseConnect, $updateCampaign);
                }           

        mysqli_free_result($result);

    mysqli_close($con); 



via Chebli Mohamed

update multiple json item based in ids

I'm trying to do some work with php and json, so.. i'm doing and live score app, basically i write the data that come from the api to a json file, i have two different methods to get data from the api, one gives me the full list of games for an entire day, for example today, i can request this method every 5 minutes, what is too long for an live score app, the second method only show me the live games and i can request every 25 seconds, that's cool for me, so what i do right now is:

  • I request the 5 minutes method in the first minutes of every day to get the full list, and write the data to a file with the day date.

the json file for every day looks like this

{
Match: [
{
Id: "353516",
Date: "2015-08-14T19:30:00+00:00",
League: "Primeira Liga",
Round: "1",
HomeTeam: "Tondela",
HomeTeam_Id: "1304",
AwayTeam: "Sporting",
AwayTeam_Id: "539",
Location: "Estádio João Cardoso",
LeagueFlag: "Portugal.png",
PhotoAds: "no ads",
AwayTeamShort: "SCP",
HomeTeamShort: "TON"
},
{
Id: "356795",
Date: "2015-08-14T19:00:00+00:00",
League: "Süper Lig",
Round: "1",
HomeTeam: "Fenerbahce",
HomeTeam_Id: "223",
AwayTeam: "Eskisehirspor",
AwayTeam_Id: "209",
Location: "Şükrü Saracoğlu Stadium",
LeagueFlag: "Turkey.png",
PhotoAds: "no ads"
}

The data for live games that i can request every 25 seconds it's like the json above but with a few more items like , Time (game time), hometeamgoals, awayteamgoals , so what i want to do is request data every 25 seconds to this live method and compare the match id and update with time, hometamgoals, awaysteamgoals all the games that are live.

Correct me if you found a better way ... Right now i have a live.php file that is requesting data for live games, and store that info in a live.json file, after that i want to compare the data in the live.json with the full list of games for today and update the one that match the live.json.

My code in live.php :

 $result=$soccer->GetLiveScore();
$fp = fopen( "/var/www/live.json","w+");
        fwrite($fp,json_encode($result));
        fclose($fp);

 $datacinco = "/var/www/live.json";
    $json = file_get_contents($datacinco);
    $links = json_decode($json, TRUE);



    foreach($links["Match"] as $key=>$val) {

    //right now i'm not doing anything here, it's right here that i need your help



    }

    $fp = fopen( "/var/www/$filedate.json","w+"); // i write the info checked above in a file with the day date where is the full list of games
    fwrite($fp,json_encode($links));
    fclose($fp);



via Chebli Mohamed

My php contact form does not send

It is a simple mailing list. I added various emails to the list for testing and it does not send to any of them. It used to work at one stage. It is really old code as you can see. Any ideas how to get this working. Thanks in advance.

    <?
require_once("../conn.php");
require_once("access.php");

include_once("LeftStyles.php");

if(isset($_POST[s1]))
{
    //get the subscribers info
    $q1 = "select * from re2_agents where news = 'y' ";
    $r1 = mysql_query($q1) or die(mysql_error());

    while($a1 = mysql_fetch_array($r1))
    {
        $to = $a1[email];
        $subject = $_POST[subject];

        $headers = "MIME-Version: 1.0\n"; 
        $headers .= "Content-type: text/$a1[NewsletterType]; charset=iso-8859-1\n";
        $headers .= "Content-Transfer-Encoding: 8bit\n"; 
        $headers .= "From: $_SERVER[HTTP_HOST] <$aset[ContactEmail]>\n"; 
        $headers .= "X-Priority: 1\n"; 
        $headers .= "X-MSMail-Priority: High\n"; 
        $headers .= "X-Mailer: PHP/" . phpversion()."\n"; 

        if($a1[NewsletterType] == "plain")
        {
            $message = strip_tags($_POST[message]);
            $message .= "\n\n========================\nTo unsubscribe, use this link:\n";
            $message .= "$site_url/u.php?id=$a1[AgentID]";
        }
        else
        {
            $message = $_POST[message];
            $message .= "<br><hr width=\"100%\" size=1 color=black>Click <a href=\"$site_url/u.php?id=$a1[AgentID]\">here</a> to unsubscribe.";
        }

        $message = stripslashes($message);

        mail($to, $subject, $message, $headers);

        $i++;
    }

    //add the message to the mail archive
    $t = time();
    $q1 = "insert into re2_mail_archive set 
                    subject = '$_POST[subject]',
                    message = '$_POST[message]',
                    MailDate = '$t' ";
    mysql_query($q1) or die(mysql_error());

    echo "<center><b>$i emails was sent!</b></center><br>";
}


//get the subscribers number
$q1 = "select count(*) from re2_agents where news = 'y' ";
$r1 = mysql_query($q1) or die(mysql_error());
$a1 = mysql_fetch_array($r1);

if($a1[0] == '0')
{
    echo "<br><center><font face=verdana size=2 color=red><b>You have no subscribers at your mailing list!";
    exit();
}

?>



via Chebli Mohamed

Call to undefined method Uni_Fileuploader_Helper_Data::getProductAttachments()

I am having the following error while trying to display product attachment:

Call to undefined method Uni_Fileuploader_Helper_Data::getProductAttachments() in www\app\design\frontend\my_theme\default\template\catalog\product\list.phtml on line 51

The way I'm calling the method is:

<?php $attachments = Mage::helper('fileuploader')->getProductAttachments($_product->getId(), 1);
if (count($attachments) > 0): ?>
    <?php foreach ($attachments as $_attachment): ?>
        <?php echo $_attachment['file']; ?>
    <?php endforeach; ?>
<?php endif; ?>

Please help!

Thanks



via Chebli Mohamed

PHP + PayPal: make payment by PayPal without screen login

I have a new question. This is my context:

I want to make my own API REST, where I can call this method with information about my product as parameters. My backend method do the typical purchased process but it doesn't show the PayPal screen which show information about my product, just do the process directly and I receive an answer. Is it possible?

I'm using the PayPal SDK for PHP, and looking for at Google I just have gotten that the PayPal page shows, but I'm new in this. Your answer will be so good!



via Chebli Mohamed

PHP 5.5.27 Opcache not working on Apache 2.4 CentOS 7

I've using PHP 5.5.27 installed on Apache 2.4 on CentOS 7. Opcache is showing on a phpinfo() page as:

Opcode Caching: Disabled

Yet below opcache.enable shows 'On'. I verified the proper php.ini is being used (/etc/php.d/opcache.ini) and it shows that it is loading up above in the list of loaded config files. I tried replacing zend_extension=opcache.so with the full path to the file, but that didn't work either. I even restarted apache after each of the changes.

I feel like I must be missing something simple, but I have no idea what it is.



via Chebli Mohamed

Having trouble executing the user id session after user logs in

Here is the following codes i have so far for the sign up page login page and homepage. note i am only posting the php I know everything is working except for the user id session. I am connected to my database and row 1 is id and is the primary key.

here is the signup php

<?php
require ("func/insert.php");

if(isset($_POST['Submit']))
    {
        $first_name = mysqli_real_escape_string($con, $_POST ['first_name']);
        $last_name= mysqli_real_escape_string($con, $_POST ['last_name']);
        $email= mysqli_real_escape_string($con, $_POST ['email']);
        $password= $_POST ['password'];

        $StorePassword= password_hash($password, PASSWORD_BCRYPT, array('cost' => 10));

        $sql = $con->query("INSERT INTO users ( first_name, last_name, email, password)
                    VALUES ( ' {$first_name} ' , ' {$last_name} ' , ' {$email} ' , ' {$StorePassword} ' )");
        header('Location: login.php');
    }
?>

HEre is the login php

<?php require ("func/insert.php"); ?>
<?php
    if(isset($_POST['Login']))
    {
    $email= mysqli_real_escape_string(htmlentities($con, $_POST ['email']));
    $password= mysqli_real_escape_string(htmlentities($con, $_POST ['password']));

    $result = $con->query(" select * from users where email='$email' AND password='$password' ");

    $row = $result->fetch_array(MYSQLI_BOTH);

    session_start();

    $_SESSION['UserID'] = $row['id']; //thinking this is the problem
    header ('Location: home.php');
    }

And here is the home php

<?php require ("func/insert.php"); ?>
<?php
session_start(); 
    if (isset($_SESSION['UserID'])) {
}
else {
echo "This session is not working.";
}
?>



via Chebli Mohamed

.PHP form submit not working

I have been trying to figure this stupid PHP thing for 2 days now. I am designing a website for my wife who is a personal trainer. I would like people to be able to submit their contact info to her via a form I have on the site. I have no clue how to code PHP myself, so I snagged a "working model" and made some edits to fit my site. Here is the HTML code:

<form name="contact" method="post" action="formsubmit.php">             
<li>

<input name="first_name" type="text" value="first name (Required)" onfocus="if(this.value == 'first name') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'first name'; }" />

<input name="last_name" type="text" value="last name (Required)" onfocus="if(this.value == 'last name') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'last name'; }" />

<input name="email" type="text" value="email (Required)" onfocus="if(this.value == 'email (Required)') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'email (Required)'; }" />

<input name="telephone" type="text" value="phone" onfocus="if(this.value == 'phone (Required)') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'phone'; }" />

<input name="comments" type="text" value="What are your goals?" onfocus="if(this.value == 'What are your goals?') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'What are your goals?'; }"  />

 <div class="g-recaptcha" data-sitekey="I am using site key here, just wasn't sure if the public should be privy to that info or not"></div>

 </li>
 </form>

 <li>
 <input type="submit" value="SUBMIT" class="submitbtn" form="contact" />
 </li>

And here is the .php

<!doctype html>
<html>
<head>

<!-- CSS -->
<link href="main.css" rel="stylesheet" type="text/css" />

<meta charset="UTF-8">
<title>We Will EnduroFit</title>
</head>

<body>
<?php

if(isset($_POST['email'])) {



    // EDIT THE 2 LINES BELOW AS REQUIRED

    $email_to = "jasmine@freedomseed.org";

    $email_subject = "Message from EnduroFit visitor";        

    function died($error) {

        // your error code can go here

        echo "I am sorry, but there were error(s) found with the form you submitted.";

        echo "These errors appear below.<br /><br />";

        echo $error."<br /><br />";

        echo "Please go back and fix these errors.<br /><br />";

        die();

    }  

    // validation expected data exists

    if(!isset($_POST['first_name']) ||

        !isset($_POST['last_name']) ||

        !isset($_POST['email']) ||

        !isset($_POST['telephone']) ||

        !isset($_POST['comments'])) {

        died('I am sorry, but there appears to be a problem with the form you submitted.');       

    }  

    $first_name = $_POST['first_name']; // required

    $last_name = $_POST['last_name']; // required

    $email_from = $_POST['email']; // required

    $telephone = $_POST['telephone']; // not required

    $comments = $_POST['comments']; // required     

    $error_message = "";

    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';

  if(!preg_match($email_exp,$email_from)) {

    $error_message .= 'The Email Address you entered does not appear to be valid.<br />';

  }

    $string_exp = "/^[A-Za-z .'-]+$/";

  if(!preg_match($string_exp,$first_name)) {

    $error_message .= 'The First Name you entered does not appear to be valid.<br />';

  }

  if(!preg_match($string_exp,$last_name)) {

    $error_message .= 'The Last Name you entered does not appear to be valid.<br />';

  }

  if(strlen($comments) < 2) {

    $error_message .= 'The Comments you entered do not appear to be valid.<br />';

  }

  if(strlen($error_message) > 0) {

    died($error_message);

  }

    $email_message = "Form details below.\n\n";  

    function clean_string($string) {

      $bad = array("content-type","bcc:","to:","cc:","href");

      return str_replace($bad,"",$string);

    }

    $email_message .= "First Name: ".clean_string($first_name)."\n"; 
    $email_message .= "Last Name: ".clean_string($last_name)."\n"; 
    $email_message .= "Email: ".clean_string($email_from)."\n"; 
    $email_message .= "Telephone: ".clean_string($telephone)."\n";
    $email_message .= "Comments: ".clean_string($comments)."\n";


// create email headers

$headers = 'From: '.$email_from."\r\n".

'Reply-To: '.$email_from."\r\n" .

'X-Mailer: PHP/' . phpversion();

@mail($email_to, $email_subject, $email_message, $headers);  

?> 

<!-- include success html here --> 

<h2>Thanks! I will respond to you soon :)</h2>

<?php

}

?>
</body>
</html>

If anyone can take a look at that and tell me what I am missing. I am about to throw something (or just delete the stupid form altogether and say screw it). The submit button just acts like its dead. It does nothing at all. I know it was working as a model, so I have no idea what I did/did not change to break the stupid submit button. Thanks a million!



via Chebli Mohamed

Codeigniter, Message: Undefined variable: params Filename: libraries/tmdb.php

I have problem when load a libraries with array $params

=> file libraries 'libraries/tmdb.php'

public function movie_similar($id, $page = 1, $language = NULL, $append = NULL)
{
    $params = array(
        'page'          => $page,
        'language'      => $language,
        'append_to_response'    => $params
    );

    return $this->_call('movie/' . $id . '/similar_movies', $params);
}

=> file controller 'controller/Movie.php'

public function id($id)
{
    if((int)$id > 0){
        $id = $this->uri->segment('3');
        $data['similar'] = $this->tmdb->movie_similar($id,$page=1);
        $this->load->view('movie_view',$data);
    }


}

And I have errors:

A PHP Error was encountered
Severity: Notice
Message: Undefined variable: params
Filename: libraries/tmdb.php
Line Number: 172

Backtrace:

File: E:\xampp\htdocs\master\application\libraries\tmdb.php
Line: 172
Function: _error_handler
File: E:\xampp\htdocs\master\application\controllers\Movie.php
Line: 113
Function: movie_similar
File: E:\xampp\htdocs\master\index.php
Line: 292
Function: require_once

how to fix my problem ?



via Chebli Mohamed

Destroy cookie button

I think there might be something I don't get about cookies. I'm trying to destroy a cookie when I click on a button but the cookie stays. I know that instructions for cookies must be before html codes, so I created a new php page with no html code, logout.php:

<?php

if (isset($_COOKIE['pseudocookie'])) {
    setcookie('pseudocookie', '', time()-300); 
}

if(session_id() == '') {
    session_start(); 
}

session_destroy();
session_unset();

header('Location: ../index.php'); ?>

And I'm calling the page from index.php with a simple button :

<input type="button" id="ButSignout" value="Sign out" onclick="window.location.href='pages/logout.php'" />

I did some test, the php page is well loaded, if I try to delete the cookie directly from index.php, it works. What am I missing? Thanks in advance.


The cookie was created with:

setcookie('pseudocookie','Pseudo cookie',time()+$expire, null, null, false, true);



via Chebli Mohamed

Dynamic fields only updating first row


I have a dynamic form (with dynamically adding rows).
This form has 2 normal input fields which send data to table 'orcamen'
and 4 dynamic fields which are stored in table 'tbl_orderdetail'.
When I try to update the dynamically added fields, the table stores only the first row.

This is my edit page that fetches correctly the values from both tables:

<?php 

mysql_connect("localhost","root");
mysql_select_db("alpha");



$id = $_GET["id"];
settype($id, "integer");

    $resultado=mysql_query("SELECT * FROM orcamen WHERE id = $id");

    $orcrow=mysql_fetch_object($resultado);

//This is the table that gets the dynamic rows          
$query = mysql_query( "SELECT * FROM tbl_orderdetail WHERE order_id=$id");

mysql_close();
?>

And here is the html code of the dynamic rows:

<form   method="post" action="salva_orc.php">   
<input type="hidden" name="id" id="id" value="<?php echo $id;?>" />

            <thead>
                <th>No</th>
                <th>Qtde</th>
                <th>Descrição</th>
                <th>Unitário</th>
                <th>Desc.(%)</th>
                <th>Valor</th>
                <th><input type="button" value="+" id="add" class="btn btn-primary"></th>
            </thead>


            <tbody id="orderdetail" class="detail">
            <?php
                while ($result = mysql_fetch_object($query)){
            ?>
                <tr>
                    <td width="2%" class="no">1</td>
                    <td width="10%"><input type="text" class="form-control quantity" name="quantity[$result->id]" value="<?php echo $result->quantity ?>"></td>
                    <td width="60%"><input type="text" class="form-control productname" name="product_name[$result->id]" value="<?php echo $result->product_name ?>"></td>
                    <td width="8%"><input type="text" class="form-control price" name="price[$result->id]" value="<?php echo $result->price ?>"></td>
                    <td width="4%"><input type="text" class="form-control discount" name="discount[$result->id]" value="<?php echo $result->discount ?>"></td>
                    <td width="10%"><input type="text" class="form-control amount" name="amount[$result->id]" value="<?php echo $result->amount   ?>"></td>
                    <td width="6%"><a href="#"  class="remove">Excluir</td>
                </tr>
            <?php } ?>  
</tbody>

            <tfoot>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th style="text-align:center;" >Total  R$</th>
                <th style="text-align:center;" class="total">0</th>
            </tfoot>

        </table>
        <input type="submit" class="btn btn-primary" name="update" id="update" value="Salvar">
        </form> 

<script type="text/javascript">
    $(function(){
        $('#add').click(function(){
        addnewrow();
        });
        $('body').delegate('.remove','click',function(){
            $(this).parent().parent().remove();
        });
        $('.detail').delegate('.quantity,.price,.discount','keyup',function(){
            var tr = $(this).parent().parent();
            var qty = tr.find('.quantity').val();
            var price = tr.find('.price').val();
            var dis = tr.find('.discount').val();
            var amt = (qty * price) - (qty * price * dis)/100;
            tr.find('.amount').val(amt);
            total();
        });
    });

    function total()
    {
    var t = 0;
    $('.amount').each(function(i,e)
    {
        var amt = $(this).val()-0;
        t += amt;
    });
    $('.total').html(t);
    }

    function addnewrow()
    {
        var n = ($('.detail tr').length-0)+1;
        var tr = '<tr>'+
                    '<td class="no">' + n + '</td>'+
                    '<td><input type="text" class="form-control quantity" name="quantity[]"></td>'+
                    '<td><input type="text" class="form-control productname" name="product_name[]"></td>'+
                    '<td><input type="text" class="form-control price" name="price[]"></td>'+
                    '<td><input type="text" class="form-control discount" name="discount[]"></td>'+
                    '<td><input type="text" class="form-control amount" name="amount[]"></td>'+
                    '<td><a href="#" class="remove">Excluir</td>'+
                '</tr>';
        $('.detail').append(tr);        
    }
</script>

And now the update file that is called from the upper form.

<?php 
@ini_set('display_errors', '1');
error_reporting(E_ALL);

mysql_connect("localhost", "root", "");
mysql_select_db("alpha");


$razao     = $_POST["razao"];
$local      = $_POST["local"];
$condicao     = $_POST["condicao"];
$estado         = $_POST["estado"];
$material       = $_POST["material"];
$obs        = $_POST["obs"];
$id         = $_POST["id"];
mysql_query ("UPDATE orcamen SET razao='$razao' , local='$local' , condicao='$condicao' , estado='$estado' , material='$material' , obs='$obs' WHERE id=$id");


foreach ($_POST['quantity'] as $ord_det_id => $quantity) {
$product_name = $_POST['product_name'][$ord_det_id];
$price = $_POST['price'][$ord_det_id];
$discount = $_POST['discount'][$ord_det_id];
$amount = $_POST['amount'][$ord_det_id];

mysql_query ("UPDATE tbl_orderdetail SET product_name='$product_name',  quantity='$quantity', price='$price', discount='$discount', amount='$amount'    WHERE order_id = $id");
}


mysql_close();
header("Location: consulta_orc.php");

?>

I hope someone can help me solve this.

The new html code:

<?php
    while ($result = mysql_fetch_object($query)){
?>
<tr>
    <td width="2%" class="no">1</td>
    <td width="10%"><input type="text" class="form- control quantity" name="quantity[<?php echo $result->id ?>]" value="<?php echo $result->quantity ?>"></td>
    <td width="60%"><input type="text" class="form-control productname" name="product_name[<?php echo $result->id ?>]" value="<?php echo $result->product_name ?>"></td>
    <td width="8%"><input type="text" class="form-control price" name="price[<?php echo $result->id ?>]" value="<?php echo $result->price ?>"></td>
    <td width="4%"><input type="text" class="form-control discount" name="discount[<?php echo $result->id ?>]" value="<?php echo $result->discount ?>"></td>
    <td width="10%"><input type="text" class="form-control amount" name="amount[<?php echo $result->id ?>]" value="<?php echo $result->amount ?>"></td>
    <td width="6%"><a href="#" class="remove">Excluir</td>
</tr>
<?php } ?>  

And the php code with var_dump:

<?php 
@ini_set('display_errors', '1');
error_reporting(E_ALL);

mysql_connect("localhost", "root", "");
mysql_select_db("alpha");


$razao     = $_POST["razao"];
$local      = $_POST["local"];
$condicao     = $_POST["condicao"];
$estado         = $_POST["estado"];
$material       = $_POST["material"];
$obs        = $_POST["obs"];
$id         = $_POST["id"];
mysql_query ("UPDATE orcamen SET razao='$razao' , local='$local' , condicao='$condicao' , estado='$estado' , material='$material' , obs='$obs' WHERE id=$id");


foreach ($_POST['quantity'] as $ord_det_id => $quantity) {
$order_id = $_POST['order_id'][$ord_det_id];    
$product_name = $_POST['product_name'][$ord_det_id];
$price = $_POST['price'][$ord_det_id];
$discount = $_POST['discount'][$ord_det_id];
$amount = $_POST['amount'][$ord_det_id];



mysql_query ("UPDATE tbl_orderdetail SET product_name='$product_name', quantity='$quantity', price='$price', discount='$discount', amount='$amount' WHERE order_id = $id");



}



header("Location: consulta_orc.php");
?>



via Chebli Mohamed

Discern 'echo'd returned data from PHP script to Ajax response function

I need a way to discern returned values from a PHP processing script to an Ajax return response function so that I can do different things if the response is positive vs negative.

I'm aware of indexOf (which seems to be deprecated) as well as inArray. The problem is my returned data is not an array, they are simple 'echos'.

I also want to avoid encoding the echo statements into JSON. It seems extraneous to do so.

How can I discern the returned data?

if(!mysqli_num_rows($result)){
    // Insert data into database...
        if($result){
            echo "Thanks for Registering!";
            $_SESSION['username'] = $userName;
        } else {
            echo "Something went wrong with your registration. Please try back later.";
        }
    } else {
        echo 'It seems that your email has already been registered.';
        // return false;
    }

I thought about adding a 'return false' to "mimic" a failed Ajax response, but that doesn't work.

$.ajax({
        url:'includes/register.php',
        type:'POST',
        data: formData,
        success: function(data){
             $("#register-form #message p").html(data);
         }
    }); // $.ajax
    // if registration was successful, show the message and redirect
    $('#register-form img').addClass('hide');
    $("#register-form div + div").addClass('hide');
    $("#register-form #message").removeClass('hide');
    setTimeout(function(){
        $('#overlay, form#register-form').fadeOut('slow');
        $(".register").off();
        window.location.href = 'sandbox/workshop.php';
    },2000);

    // if registration was not successful, do something else...

Thanks in advance for your replies.



via Chebli Mohamed

Laravel query delays and 'session' queries despite database 'file' driver used

I'm currently using Laravel for a project I'm working on, and my web-server has recently started performing very slowly upon page load, whereby each page can take up to eight seconds until loaded.

Thus far, I've determined that the slowness is not caused by the following:

  • DNS issue; issue occurs when I navigate directly to the server's IP
  • Apache issue; a blank PHP file with 'phpinfo()' loads instantly without any delay
  • Load; Server's CPU usage is never above 20%

Following the above steps, the issues only occur on the live environment, where my development environment shows no signs of delay.

After analysing some cachegrind logs, I found that the PDOStatement->execute call appears to take up the largest amount of delay.

I then enabled long_query_time logging in MySQL to further determine the issue. My findings show that most of my queries are being executed quickly, well under one second; however, I've found that any site_session queries executed are taking up to six seconds to be executed.

As a further troubleshooting step, I attempted to temporarily change my sessions drive to file instead of database; however, I'm finding that the following queries are still being executed after each page load:

# Time: 150813 23:37:12
# User@Host: root[root] @ localhost [127.0.0.1]
# Query_time: 3.035622  Lock_time: 0.000022 Rows_sent: 0  Rows_examined: 1
SET timestamp=1439509032;
update `site_sessions` set `payload` = 'YTo1OntzOjY6Il90b2tlbiI7czo0MDoibHk0YVo2MG16c09acTBTSnVnYUlJVTFNM0VrU3B2ekdiRFJyYmRzWiI7czo5OiJfcHJldmlvdXMiO2E6MTp7czozOiJ1cmwiO3M6MjY6Imh0dHA6Ly93d3cuY29ycGxlYWd1ZXMuY29tIjt9czo1OiJmbGFzaCI7YToyOntzOjM6Im9sZCI7YTowOnt9czozOiJuZXciO2E6MDp7fX1zOjM4OiJsb2dpbl84MmU1ZDJjNTZiZGQwODExMzE4ZjBjZjA3OGI3OGJmYyI7czoxOiIxIjtzOjk6Il9zZjJfbWV0YSI7YTozOntzOjE6InUiO2k6MTQzOTUwOTAyODtzOjE6ImMiO2k6MTQzOTQ5Nzc5MjtzOjE6ImwiO3M6MToiMCI7fX0=', `last_activity` = '1439509029' where `id` = 'ba62f70745c5455611c3fe3bf008fa213c22a7f9';
# Time: 150813 23:37:27
# User@Host: root[root] @ localhost [127.0.0.1]
# Query_time: 1.071487  Lock_time: 0.000026 Rows_sent: 0  Rows_examined: 1
SET timestamp=1439509047;
update `site_sessions` set `payload` = 'YTo1OntzOjY6Il90b2tlbiI7czo0MDoiOGhiVVVobTFjTERrU1ZXR25weTdMWHlQRlMzTmtkOWhIZzFSdHQ1QSI7czo5OiJfcHJldmlvdXMiO2E6MTp7czozOiJ1cmwiO3M6MjY6Imh0dHA6Ly93d3cuY29ycGxlYWd1ZXMuY29tIjt9czo1OiJmbGFzaCI7YToyOntzOjM6Im9sZCI7YTowOnt9czozOiJuZXciO2E6MDp7fX1zOjM4OiJsb2dpbl84MmU1ZDJjNTZiZGQwODExMzE4ZjBjZjA3OGI3OGJmYyI7czoxOiIxIjtzOjk6Il9zZjJfbWV0YSI7YTozOntzOjE6InUiO2k6MTQzOTUwOTA0NjtzOjE6ImMiO2k6MTQzOTUwNDQzODtzOjE6ImwiO3M6MToiMCI7fX0=', `last_activity` = '1439509046' where `id` = 'c3e95cf7c317ad340aa28c61bf323e008eaa5ff0';

Can anyone shed some light on this issue, or equally, provide additional troubleshooting steps that will help me determine the root cause?

Any feedback is greatly appreciated!



via Chebli Mohamed

How to pass Javascript date object (formatted datetime) from Laravel API

My Laravel 5 API pulls regular datetime columns from my MySQL db. My JSON datetime output looks like this:

2015-08-13 13:45:00

but the widget reading my JSON expects a JavaScript Date Object? What would be the syntax to pass my datetime as a JavaScript Date Object?

My current Laravel method looks like so:

public function transform($events)
{
    return [
        'startdt' => $events['event_start'],
        'enddt'   => $events['event_end'],
    ];
}

This is the code I have in my widget JS file:

'use strict';

angular
  .module('demo', ['mwl.calendar', 'ui.bootstrap', 'ngTouch', 'ngAnimate'])
  .controller('MainCtrl', function ($modal, moment, $http) {

var vm = this;
vm.calendarView = 'month';
vm.calendarDay = new Date();

$http.get('http://ift.tt/1Wnooc0').success(function(events) {    
    vm.events = events.events;
}); 



via Chebli Mohamed

SMTP won't send mail suddenly

So, I have a Windows Server with extJS customized app, one of apps features were mail responding, it worked perfectly until few days, then all of a sudden it stopped delivering emails, I tested with simple phpMailer it delivers, tested the "pickup" folder also delivers, but but won't deliver emails sent from this app.

I ran through settings, everything is as the MS official site says it should be, including Relay and everything - as I've said it workd already.

Now I really need a way to reset SMTP Virtual Server #1, I tried stoping and starting through PowerShell, tried adding second SMTP Virtual Server, and disabling the first one but it still won't go.

I can't post you code of mailer of the app cuz developer that wrote it secured it with SourceGuardian, but nevertheless it worked until few days ago.



via Chebli Mohamed

Azure VM does not serve external website

  • I spun up a Windows 2012 R2 Datacenter VM.
  • Endpoints have ports 21,80,443 successfully added to the dashboard.
  • Installed Wordpress/PHP on the VM using the Web Platform Installer.

Wordpress site works fine using localhost.

Trying to hit the DNS (mysite.cloudapp.net) or the public IP, shows just the generated version of the site below. Clicking links results in an "unable to connect" error.

Anyone know what I might be doing wrong?

enter image description here



via Chebli Mohamed

How to fix a layout error in Checkout when using Pay with Amazon with WooCommerce on my wordpress website?

I am trying to set up a woo commerce store for my website and I want to use amazon as the payment method. Everything was going fine until I tried to test it and order something myself with my own amazon account. When I am in the checkout page, the Billing Method and Address are displayed wrong. It's like they are over to the left to far and cut off in the middle of the amazon content. My wordpress theme is woo commerce compatible. Please help!



via Chebli Mohamed

PHP Filter FlateDecode PDF stream returning offset characters

I have code that extracts text from a PDF using a filetotext class. Worked until last week when something changed in the pdf's being generated. Weird thing is that it appears the characters are there and correct once I add 29 to the ord of the character.

Example response debug printout: /F1 7.31 Tf 0 0 0 rg 1 0 0 1 195.16 597.4 Tm ($PRXQW)Tj ET BT

The code uses gzuncompress on the stream section of the pdf. The $PRXQW is Amount, and adding 29dec to the ord of each character gives me this. But sometimes a character will not be this exact translation, such as what should be a ) in the text appears to be two bytes of 5C66.

Just wondering about this code ring type of character coming out of PDF's now and if anyone has seen this kind of thing?



via Chebli Mohamed

Placing a slash in a string

In PHP we have tried to use str_replace to do this.

We have stored in the database <img src="images/dogtopic.jpg" and need to insert a / before the word images to set the correct path to the image.

We have tried all sorts of combinations to achieve this but to no avail.

Any ideas - would really be appreciated

Cheers Rich



via Chebli Mohamed