Home > OS >  Propper conversion of PHP and SQL data types [closed]
Propper conversion of PHP and SQL data types [closed]

Time:09-29

A seemingly minor problem are bothering me, something that should have a simple solution. I am currently running a server and a database, the database which contains data that I want to use in a PHP request on a website. I have created a function in PHP that does the following:

function getUserID($val){
     include("config.php");
     $conn = new mysqli($dbservername, $dbusername, $dbpassword, $dbname) or die($conn);
     $sql = "SELECT userid FROM users WHERE username=?";
     $stmt = $conn->prepare($sql);
     $stmt->bind_param("s", $val);
     $stmt->execute();
     $result = $stmt->get_result();
     if(getUserExist($val)){
          $rowdata = mysqli_fetch_assoc($result);
          $conn->close();
          return $rowdata['userid'];
     }
}

This works just fine.. HOWEVER. The returned data type, which is supposed to be an Integer ( 1, 2, 3, 4... etc. ), returns a value similar to an JSON object or int(1), depending on how I write it.

array(1) { ["userid"]=> int(4) }

I have tried:

  1. $rowdata['userid']
  2. $rowdata

How do I make the function return purely the integer value? When it is added to the database with following code-snippet:

...
        $stmt = $conn->prepare("INSERT INTO users (user1, user2, user3) VALUES (?, ?, ?)");
        $stmt->bind_param("isi", $user1, $user2, $user3);
        $user1 = $_POST[getUserID($username)];
        $user2 = $_POST['val2'];
        $user3 = $_POST['val3'];
        $stmt->execute();
        
        $stmt->close();
    }
    $conn->close();

As mentioned, it retrieves data just fine, it is just the value that acts in an odd way. When this code is executed, $user1 or rather the final value within database has the value of NULL. (database accepts only integers in that slot).

CodePudding user response:

It looks to me as if the problem does not lie in getUserID(), but in this line:

$user1 = $_POST[getUserID($username)];

What you're doing here is not setting $user1 to the value of getUserID() - instead, you're setting it to "the element in the $_POST array which has a key of whatever getUserID() returns". And there are very few scenarios where that makes sense.

I'm assuming the line you want to replace it with is

$user1 = getUserID($username);
  • Related