I wrote a code that is meant to create tables if they are non-existent as a way for it to populate the database on the first launch.
Then I came to a part where I started writing the code that is meant to populate the tables with the default data but the problem is that I only need the code to execute if the table is empty (on the first launch) and I got the code to be either not populating at all or populating the table on each refresh.
I tried using a bunch of different ways to achieve what I want but I am stuck, overwhelmed and I have no idea If I'm headed in the right direction at all.
I tried using COUNT(*) like this
$check_roles_population = mysqli_query($mysqli,"SELECT COUNT(*) FROM roles");
$populate_roles = "INSERT INTO roles (role_name,role_description) VALUES ('administrator','This role has full privilege over the website')";
echo "Number of rows: ".$check_roles_population->num_rows."<br />";
print_r($check_roles_population);
echo "<br />";
if($check_roles_population->num_rows === 0){
mysqli_query($mysqli, $populate_roles);
echo "Action Successful";
}
else{
echo "Failed Attempt";
}
but it doesn't seem to be working since the num_rows value is always 1 no matter if the table has 0,1 or 21 rows so the entire if-else statement falls into the water since I am not getting the real value of the number of rows.
print_r says mysqli_result Object ( [current_field] => 0 [field_count] => 1 [lengths] => [num_rows] => 1 [type] => 0 )
no matter how many rows the table has
I've been also thinking about ways to achieve this with a boolean statement but I have no idea how to get it to show me any value different than 1
I've been also trying to do something with a while loop since this is an app that I've built, lost and am rebuilding now and I know that while building the app about 2 years ago, I've been using a lot of while loops but I can't remember if I used them for this specific function.
I've been also trying to use different variations as if($check_roles_population->num_rows !== 1)
, I've tried many different approaches and even slept over it but I still can't figure it out since most of my coding-related knowledge is faded.
I remember that I've been struggling and asking for help the last time I've been building this part of the code and I know that I found a bunch of posts related to this specific problem but I can't find them now, I guess i am using different terms...
I appreciate your help (don't laugh if I got the entire code wrong), Thank you!✌️