0

So i have here a function that i created. It worked when i used a postgres database but once i switched over to mysqli, for some reason, it doesn't return the id. Here is my function:

function getAccID($connection, $username){
    $res = mysqli_query($connection, "SELECT accounts_id FROM people WHERE people.username ='$username'");
    if ($res){
        $row = mysqli_fetch_assoc($res);
        if ($row){
            return ($row[0]);
        }
    }else{
        //handle the error
    }

}

And here is how i declare the function:

$accountID = getAccID($connection, $user);
$p->addContent("Account ID: $accountID");
if (!$accountID) $p->addContent('Error: ' . mysqli_error($connection) . "<br>");

PS: If anyone says anything about me using mysqli_query instead of prepare statements, i will murder some babies :L. I'm using it to test, and once everything works, it's easy to switch to prepared statements.

FIXED

Problem with this was with Postgres i could use the id of the fields, but with mysqli, i have to use the name.

Therefore this will not work

$row[0];

It'll have to be:

$row["name_of_field"];
6
  • (If you are going to "test" something, why not test the actual something that will be used?) Commented Oct 3, 2013 at 23:25
  • because i like to test as i go along. It's just the way i work. Commented Oct 3, 2013 at 23:26
  • and it's easier to test with queries than it is with prepared statements. Commented Oct 3, 2013 at 23:27
  • (If you're going to switch to something else, you're not testing it; this is an inappropriate mock scenario.) Commented Oct 3, 2013 at 23:27
  • 1
    Anyway, 1) do something in "handle the error" and; 2) verfify the result of mysqli_fetch_assoc is what you think it is - i.e. that there are results and that you're returning the desired value within said row (I see a suspicious-looking if, not a traditional while, and no $row["accounts_id"]). As it is now, either-or could be "failing" which would result in an unexpected result - mainly, no useful return value - due to incomplete execution flow pathing. Commented Oct 3, 2013 at 23:34

1 Answer 1

1

As you are using mysqli_fetch_assoc

the $row should have the name of the field

use $row['id'] instead of $row[0]

Sign up to request clarification or add additional context in comments.

2 Comments

I literally just figured this out and was about to post the response. Haha thanks anyway.
To anyone else having this problem, this is the correct answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.