0

I am very new to PHP. I have a function that should return a single record containing a single column, 1 or 0:

function is_pitcher($player_id)  {
  global $db;
  $query = 'SELECT IF (position = 1, 1, 0) AS is_pitcher FROM players WHERE player_id = :player_id';
  $statement = $db->prepare($query);
  $statement->bindValue(':player_id', $player_id);
  $statement->execute();
  $is_pitcher = $statement->fetchAll();
  $statement->closeCursor();
  return $is_pitcher;

On my control page, I have an IF statement that evaluates $is_pitcher for values 1 and 0:

if ($action == 'get_player') {
  $player_id = filter_input(INPUT_GET, 'player_id');
  $is_pitcher = is_pitcher($player_id);
if ($is_pitcher == 1) {...

Testing the value with echo $is_pitcher shows that it's an array, and thus can't be evaluated this way. I have tried the function with both fetch() and fetchAll() with the same result.

I can get the value of $is_pitcher with echo $is_pitcher['is_pitcher'] but doing so on the control page breaks it.

Is there a way to write the function that does not return an array? Or, is there a way to evaluate the variable as an array?

ETA: In answer to a comment, here's the structure of the array:

array ( 0 => array ( 'is_pitcher' => '0', 0 => '0', ), )
4
  • can you show us the structure of the array in $is_pitcher, use var_export($is_pitcher); Commented Nov 22, 2019 at 20:41
  • 6
    fetchAll always returns an array (array can be length of 1), try $is_pitcher[0] Commented Nov 22, 2019 at 20:43
  • You can reference $is_pitcher[0]['is_pitcher'] - i.e. if ($is_pitcher[0]['is_pitcher'] == 1) {... Commented Nov 22, 2019 at 21:02
  • A simple var_dump or print_r would’ve saved a lot of time Commented Nov 22, 2019 at 23:43

1 Answer 1

1

From https://www.php.net/manual/en/pdostatement.fetchall.php

PDOStatement::fetchAll — Returns an array containing all of the result set rows So, yes, it should be an array, even with one result.

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

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.