1

I'm new in programming and especially with php and MySQL. I have to create dynamic web site for homework. My problem is with the function below. I want it to return int value of tag by given tag name (string). But in my case the function returns every time '1'. Can anyone help me to solve this problem, thanks.

public function getTagIdByName(string $tagName) : int
    {
        $statement = self::$db->prepare("SELECT tags.id FROM tags WHERE tags.name = ? ");
        $statement->bind_param("s", $tagName);
        $result = $statement->execute();
        return $result;
    }

1
  • Using mysqli prepared statements, you'll need to bind_result to a variable before fetching. See the example here. Commented Aug 15, 2016 at 20:20

2 Answers 2

1

The problem is that you're returning the result of execute(), but that function doesn't actually give you your query result. You need to fetch results after making sure the execution was successful.

//don't forget to error-check before using query results
$statement->execute() or die($statement->error);
$result = $statement->get_result(); //retrieve results for processing

if(!$result->num_rows) return null;//if the id was not found in the DB    
else return $result->fetch_assoc()['id'];
Sign up to request clarification or add additional context in comments.

6 Comments

He's using mysqli, not PDO.
Let me know when you fix your answer and I'll remove my downvote.
@Barmar I made the change. How did you know that mysqli was used by the OP?
Because he's using $statement->bind_param(), not $statement->bindParam().
BTW, you can only use fetch_assoc() with a prepared statement if you're using the MYSQLND driver. Otherwise you need to use $statement->bind_result().
|
1

You can achieve easily with

$data = $result->fetch_assoc();
return $data['id']; // you can change with which you want to return with field name

And whichever you can use your returned values.

Comments

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.