I, out of curiosity, liked to know the differences between 3 seemingly equal things to count (rows, lines) and get data from a table, in MySql / PHP:
1st: Return the number of rows first, and then work the data of those rows, EX with PDO:
function count_rows() {
$sql = ("SELECT * FROM '{$table}'");
$data = $this->_db->prepare($sql);
$data->execute();
$data_rows = $data->rowCount();
return $data_rows;
}
function select_data() {
$sql = ("SELECT * FROM '{$table}'");
$data = $this->_db->prepare($sql);
$data->execute();
return $data->fetchAll(PDO::FETCH_OBJ);
}
if(count_rows() > 0) {
//trabalhar dados
echo select_data[0]->id;
}
2nd: Only use the function to select the data, and then use them in PHP using the count
function to check for rows, which will make the count_rows function above less in this example), we also check if the returned array (rows) is empty:
function select_data() {
$sql = ("SELECT * FROM '{$table}'");
$data = $this->_db->prepare($sql);
$data->execute();
return $data->fetchAll(PDO::FETCH_OBJ);
}
if(count(select_data()) > 0) {
//trabalhar dados
echo select_data()[0]->id;
}
3rd: In this way we do not count, but we can see if the array (rows) returned from the select_data()
function is empty or not, which already causes us to work the data received:
function select_data() {
$sql = ("SELECT * FROM '{$table}'");
$data = $this->_db->prepare($sql);
$data->execute();
return $data->fetchAll(PDO::FETCH_OBJ);
}
if(!empty(select_data())) {
//trabalhar dados
echo select_data()[0]->id;
}
What I wanted to know with this question is whether there is any advantage / disadvantage in using any of them (knowing clearly that the latter is not meant to count, but already checks if there is information), or we can use any one according to our needs without any hindrance?