SpecialSnowflake
SpecialSnowflake

Reputation: 995

Mysql insert statement and passing parameters to PHP

I am trying to execute various statements/queries in my PHP file, depending on what variables are received (moreover, is there a way to send variables and choose what kind of query I want to do, as opposed to making one query for each set of variables received? This is my first time writing in PHP so please forgive the possible stupid question).

In this case its a Username, Password, and UserID. I'd like an insert to occur when these 3 variables are received. However, I keep on receiving an error: java.net.ProtocolException: method does not support a request body: GET (this is when conn.setDoOutput isset to true). If I have it set to false, I get a IO URL error which states my URL cannot be found. What am I doing wrong? Below are both my php script and the java code used for GET requests.

<?php
$con=mysqli_connect("logindetailsgohere");

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

if (isset($_GET['Username']) && isset($_Get['Password']) && isset($_GET['UserID'])){
$uname = mysql_real_escape_string($_GET['Username']);
$pass = mysql_real_escape_string($_GET['Password']);
$uid = intval($_GET['UserID']);
$sql = "INSERT IGNORE INTO Users (id, Username, Password) VALUES ('$uid', '$uname', '$pass')";
if(mysqli_query($con, $sql){
    echo "Values have been inserted";
}
}

mysqli_close($con);
?>

Java code:

public String connect() {

    try {
        /*URL url = new URL("phpfilelocation.php");*/
        String data = URLEncoder.encode("un", "UTF-8") + "=" + URLEncoder.encode(un, "UTF-8");
        data += "&" + URLEncoder.encode("pw", "UTF-8") + "=" + URLEncoder.encode(pw, "UTF-8");
        data += "&" + URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode(Integer.toString(uid), "UTF-8");

        URL url = new URL("phpfilelocation.php");
        URLConnection conn = url.openConnection();

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

        wr.write(data);
        wr.flush();

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while((line = reader.readLine()) != null)
        {
            sb.append(line);
            break;
        }
        return sb.toString();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "fail";
}

Upvotes: 0

Views: 3595

Answers (2)

Ali Gh
Ali Gh

Reputation: 700

PHP :

mysql_query("INSERT INTO Users(id, UserName, Password)
VALUES ('$uid', '$uname', '$pass')");

JAVA :

String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/dbname";
String unameDB="username";
String passDB="password";
Class.forName(driver);
Connection c=(Connection) DriverManager.getConnection(url,unameDB,passDB);
Statement s=c.createStatement();
s.executeUpdate("INSERT INTO `Users`(ID,UserName,Password) VALUE ('"+uid+"','"+uname+"','"+pass+"')");

Upvotes: 0

Daniel Nugent
Daniel Nugent

Reputation: 43322

Since this PHP script does an INSERT statement, it's strongly recommended that you use POST parameters.

Java code:

public String connect() {

    try {
    /*URL url = new URL("phpfilelocation.php");*/
        String data = "&" + URLEncoder.encode("un", "UTF-8") + "=" + URLEncoder.encode(un, "UTF-8");
        data += "&" + URLEncoder.encode("pw", "UTF-8") + "=" + URLEncoder.encode(pw, "UTF-8");
        data += "&" + URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode(Integer.toString(uid), "UTF-8");

        URL url = new URL("phpfilelocation.php");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.connect();

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while((line = reader.readLine()) != null)
        {
            sb.append(line);
            break;
        }
        return sb.toString();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "fail";
}

PHP script:

<?php
$con=mysqli_connect("logindetailsgohere");

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

if (isset($_POST['un']) && isset($_POST['pw']) && isset($_POST['uid'])){
$uname = mysql_real_escape_string($_POST['un']);
$pass = mysql_real_escape_string($_POST['pw']);
$uid = intval($_POST['uid']);
$sql = "INSERT IGNORE INTO Users (id, Username, Password) VALUES ('$uid', '$uname', '$pass')";
if(mysqli_query($con, $sql){
    echo "Values have been inserted";
}
}

mysqli_close($con);
?>

As an aside, for a GET request, you just append the parameters to the end of the url when you create the URL object.

public String connect() {

    try {
    /*URL url = new URL("phpfilelocation.php");*/
        String data = URLEncoder.encode("un", "UTF-8") + "=" + URLEncoder.encode(un, "UTF-8");
        data += "&" + URLEncoder.encode("pw", "UTF-8") + "=" + URLEncoder.encode(pw, "UTF-8");
        data += "&" + URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode(Integer.toString(uid), "UTF-8");

        String urlString = "phpfilelocation.php" + "?" + data;
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setDoOutput(false);
        conn.setRequestMethod("GET");
        conn.connect();

        //remove:
        //OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        //wr.write(data);
        //wr.flush();

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while((line = reader.readLine()) != null)
        {
            sb.append(line);
            break;
        }
        return sb.toString();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "fail";
}

Upvotes: 1

Related Questions