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