Skip to main content
Topic: How to get the number of rows in a table (Read 580 times) previous topic - next topic

How to get the number of rows in a table

Hello everyone
I am failing to get all records(Rows) from my “learners” table to be inserted into the “attendance” table. Please help!
My first query is not returning the number of rows from the table.
Help... How to get the number of rows in a table
Code: [Select]
$line = $db->rawQueryValue("SELECT COUNT(*) FROM learners");

for ($i = 1; $i <= $line; $i++){

//query the database and return a single field value
$db->where("Project_ID", $modeldata['Project_ID']);
$db->where("Learner_ID", $i);
$value = $db->getValue("learners", "Learner_ID");

$table_data = array(
    "Learner_ID" => $value,
    "Project_ID" => $modeldata['Project_ID'],
    "Class_ID" => $rec_id
);

$db->insert("attendance", $table_data);

};

Re: How to get the number of rows in a table

Reply #1
@Goto‍ you are using the wrong query function. $db->rawQueryValue(); only returns a single field value from the database, it is similar to $db->getValue();
If you want to get multiple records, use the FetchRecords or RawQuery snippet.
If you want to get a single record, use the FetchOneRecord or RawQueryOne snippet.
If you want to get a single value from a database record, use the FetchRecordFieldValue or RawQueryValue snippet, in his case you specify the particular field you want the query to return.

Re: How to get the number of rows in a table

Reply #2
Thank you.

I had finally managed to do it.
Code: [Select]

//query the database and return the results
$params = array($modeldata['Project_ID']);
$arr    = $db->rawQuery("SELECT Learner_ID FROM learners WHERE Project_ID = ?", $params);
foreach ($arr as $row){
$table_data = array(
"Learner_ID" => $row['Learner_ID'],
    "Project_ID" => $modeldata['Project_ID'],
    "Class_ID" => $rec_id
);

$db->insert("attendance", $table_data);

};