2

I've been trying to do this for a while but to no avail basically I have a function SelectRowByName that returns the mysql array result and I want to validate if it returns a record or not but it's not working. My code is:

$fileInfo = selectRowByName("SELECT ID,Mime,IconIMG FROM tblattachment_filetypes WHERE Active=1 AND Extension = '".$extension."'");

// I want to validate that $fileInfo got filled before trying to fill the below variables to avoid errors

$fileType = $fileInfo[1];
$fileTypeID = $fileInfo[0];
$fileIcon = $fileInfo[2];

I have tried using empty, isset and array count functions but they don't seem to work. Basically the query might not return any records and $fileInfo might not be filled and I want to validate that.

SelectRowByName code is:

      function selectRowByName($query)
      {
          global $server,$dbusername,$dbpassword,$db,$connection,$dbCon;
          $theQuery = mysql_query($query);
          $result = mysql_fetch_array($theQuery) or die(mysql_error());
          return $result;   
      }
2
  • Is $fileInfo always an array? Commented Jul 19, 2013 at 12:10
  • As you can see, it is filled by 3 fields from a db record. but it won't be an array if it doesn't return a record, which is what im trying to do here. I tried using the is_array function but it also didn't work Commented Jul 19, 2013 at 12:12

2 Answers 2

1

Inside your SelectRowByName function you may use one of the following (depending on the way you access MySQL):

mysql_num_rows()
mysqli_stmt_num_rows()
PDOStatement::rowCount()

to get number of rows returned.

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

4 Comments

Can't I simply validate the returned variable?
"Simply" is not the word I would use in that case. You want working solution or your question is theoretical?
:) I want a working solution, but I want the best solution that doesn't require additional db hits if possible
mysql_num_rows() and others do not make any additional calls to RDBMS. They are working on PHP's buffer.
1

This should do the trick:

function selectRowByName($query){
      $q=mysql_query($query);

      if($q!=false){
          $result=mysql_fetch_array($q);

          if(is_array($result)&&count($result)>0){
              return $result;
          }
          else{
              return false;
          }
      }
      else{
           return false;
      }
  }

I wouldn't exactly advise using this code though. Firstly the mysql_ functions are now deprecated so you would be better off using mysqli or PDO. The other thing is that this function is only able to return a singular row from the query.

Either way, hope this helps.

Ryan

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.