1

I have a php script that includes a $sql = SELECT FROM WHERE = $variable query. The query should produce a JSON list of itemids linked to a userid in a usersitems table. When I hard code the userID the query works but when I use the $variable the query $Result is No Records.

I have rewritten the script code and tried various punctuation variations numerous times. No joy.

//A missing prior code block establishes connection with database.

    $userID = $_POST["userID"];

    $conn = new mysqli($servername, $username, $password, $dbname);

    if ($conn->connect_error) 
    {
        die("Connection failed: " . $conn->connect_error);
    } 
    echo "Connected successfully". "<br>";
      //below testing that $userID holds correct value
    echo $userID. "<br>";

    //Below is commented line to test hard coded userID value.
    //$sql = "SELECT itemID FROM usersitems WHERE userID = '1' ";

    //Here's the SELECT line that's driving me batty.
    $sql = "SELECT itemID FROM usersitems WHERE userID = '" . $userID ."'";

    $result = $conn->query($sql);

    if ($result->num_rows > 0) 
    {
        // output data of each row
        $rows = array();
        while($row = $result->fetch_assoc()) 
        {
            $rows[] = $row;
        }

        echo json_encode($rows);
    }
    else
    {
        echo "No records.";
    }
    $conn->close();

If I use a hard coded userID value (in place of the $userID) then the script works and I get the json output expected. When I use the $userID I get a No Records result.

Obsidian
  • 3,719
  • 8
  • 17
  • 30
jamek
  • 11
  • 1
  • 1
    Is the user ID getting echo'd correctly from this line `echo $userID. "
    ";`?
    – atymic Jul 26 '19 at 22:27
  • Yup. The echo $userID line displays the correct userID number in the console. – jamek Jul 26 '19 at 22:33
  • 2
    It's probably because there is something else in `$userID` apart from the actual ID (Like a space, newline or similar). Since it's numerical, it actually shouldn't be quoted. Additionally your code is susceptible to MySQL injection attacks, which is a very serious security issue. I suggest reading up on it. You can start here: https://stackoverflow.com/a/60496/1106272 – Steen Schütt Jul 26 '19 at 22:34
  • I'll examine closely the $userID to see if there's something that shouldn't be in it, and get rid of the quotes. I also will look at the links re MySQL injection, as well as comments and formatting. Appreciate the help! – jamek Jul 26 '19 at 22:42
  • You were right about there being extra characters in the $userID. I was able to determine the set of characters and got rid of it with the code below. – jamek Jul 28 '19 at 18:48
  • @SteenSchütt: you were right about extra characters in $userID. I found extra characters in www.downloadHandler.text, specifically "Connected successfully
    ". I first tried to comment out every "Connected successfully
    " in my C# and php code but when I ran my code the characters still appeared in www.downloadHandler.text. Next thing I tried, which worked, was to strip out the characters with the code below. string result = www.downloadHandler.text; string newUserID = result.Replace("Connected successfully
    ", ""); Main.Instance.UserInfo.SetID(newUserID); Debug.Log(newUserID);
    – jamek Jul 28 '19 at 19:09
  • @atymic, It might be helpful to mention that my php, and C# code, is being done with a Unity game engine frontend. This should explain the Main.Instance.User.SetID(newUserID) line of code. Thanks again! – jamek Jul 28 '19 at 19:15

1 Answers1

1

Firstly, your code is vulnerable to SQL injection. You need to use prepared statements to ensure that malformed SQL cannot be passed via the $userID variable.

Please see: How can I prevent SQL injection in PHP?

I've updated your code to use a prepared statement, which should work correctly.

<?php

$userID = trim($_POST["userID"]);

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error)
{
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully". "<br>";
//below testing that $userID holds correct value
echo $userID. "<br>";

//Below is commented line to test hard coded userID value.
//$sql = "SELECT itemID FROM usersitems WHERE userID = '1' ";

//Here's the SELECT line that's driving me batty.
$stmt = $conn->prepare("SELECT itemID FROM usersitems WHERE userID = ?");
$stmt->bind_param("i", $userID);
$stmt->execute();

$result = $stmt->get_result();

if ($result->num_rows > 0)
{
    // output data of each row
    $rows = array();
    while($row = $result->fetch_assoc())
    {
        $rows[] = $row;
    }

    echo json_encode($rows);
}
else
{
    echo "No records.";
}
$conn->close();
atymic
  • 3,093
  • 1
  • 13
  • 26
  • I'm assuming that the point you're trying to make is, that the sanitization will fix the input variable (In addition to fixing the SQL injection vuln). If that is the case, that could be explained in more detail. – Steen Schütt Jul 26 '19 at 22:41
  • `$result->num_rows` is completely redundant and the while loop could be replaced with`fetchAll` – Dharman Jul 27 '19 at 00:06
  • Much thanks for the code to fix the SQL injection problem. I'll work on implementing it in my coding. – jamek Jul 28 '19 at 18:41
  • @atymic: Much thanks for the code to fix the SQL injection problem. I'll work on implementing it in my code. – jamek Jul 28 '19 at 19:09