0
I, out of curiosity would like 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 only then work the data of these 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: Just use the function to select the data, and then use it in PHP using the function count
to check for data (Rows), which will make the count_rows function above dispensable (at least in this example), we also check whether 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: This way we don’t count, but we can see if the array (Rows) returned from the function select_data()
is empty or not, which already makes it possible to work the received data:
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 if there is any advantage/disadvantage in the use of any of them (knowing clearly that the latter is not used to count, but already checks if there is information), or we can use any one according to our needs without any hindrance?
Hello, I didn’t understand it very well, but advantages/disadvantages it will depend on how your script works and what it will do, for example if you do a query in db and this returns empty, and soon after you have a loop, it will probably display some error, then it is better to process the data before leaving by making a loop where there is no data. but could you explain your question better? now I’m curious.
– rafaelphp