eignhpants
eignhpants

Reputation: 1771

Why does this PHP PDO function not return the value from the database?

I have a web application which accepts an Excel spreadsheet, parses the data, and adds that data to a MySQL database. Some of the sheets are fine, everything works as expected. However some sheets are not returning true when they should. Before data is entered I have a general purpose function which will check that table for the value and then return true or false. This function looks like this:

//Check if a sql will return with any values
function tableCheck($table, $column, $value){
  //PDO Connecttion
  $core = Core::getInstance();

  $sql = "SELECT * FROM $table WHERE $column = :value;";

  //Create a prepared statement
  $stmt = $core->dbh->prepare($sql);
  $stmt->bindParam(':value', $value, PDO::PARAM_STR);

  $stmt->execute();

  //return true if there is a hit on that value
  if($stmt->rowCount() > 0){
    return true;
  } else {
    return false;
  }

}

Like I said this works some of the time and some of the time it doesn't and I get tons of repeated values from that sheet. Obviously this seriously messes with my data.

At first I thought it had to do with special characters but I have since found sheets where this field does not have special characters have a similar problem. This problem only occurs on a single column as well. Other fields of the sheet parse perfectly fine in all cases.

Any idea on what could be causing this problem?

EDIT: I also want to note that if i copy/paste the data into MySQL workbench or the command line it does return the rows.

Upvotes: 0

Views: 124

Answers (2)

eignhpants
eignhpants

Reputation: 1771

The problem was that the data being entered was larger than the field would accept. The column was a VARCHAR and the incoming data was greater than 255 characters. I switched to a TEXT data type and the problem was solved.

Upvotes: 1

rjdown
rjdown

Reputation: 9227

This looks dangerous, but I'm sure you're doing some sort of filtering, right? :)

Sounds to me like some of your table or column names could be reserved words, for example AS and BY.

Put ticks around them in your query:

$sql = "SELECT * FROM `$table` WHERE `$column` = :value;";

Upvotes: 1

Related Questions