I am new to programming and have some suspicions regarding the usage of global variables inside functions.
I am trying to separate the logic from the structure of my html form and here is where my question stems from.
The variable I have declared as global will only be used in one specific place from outside of the function, ie the html form.
function updatePosts(){
$query= "...";
$result= "...";
$rows= mysqli_fetch_assoc($result);
global $post_title;
$post_title = $rows['post_title'] ;
}
updatePosts();
<form action="">
//use of global variable outside function
<input type="text" name="" value="{$post_title}" class="form-control">
</form>
When i declared multiple global variables it raised some questions regarding what the impact of so many global variables might be. eg.
function updatePosts(){
$query= "...";
$result= "...";
$rows= mysqli_fetch_assoc($result);
global $post_title;
global $post_author;
global $post_content;
global $post_tags;
global $post_image;
global $post_status;
global $post_date;
$post_title = $rows['post_title'] ;
$post_author = $rows['post_author'] ;
$post_content = $rows['post_content'] ;
$post_tags = $rows['post_tags'] ;
$post_image = $rows['post_image'] ;
$post_status = $rows['status'] ;
//and so on..
}
updatePosts();
<form action="">
<input type="text" name="" value="<?php echo $post_title ?>" class="form-control">
<input type="text" name="" value="<?php echo $post_author ?>" class="form-control">
<input type="text" name="" value="<?php echo $post_tags ?>" class="form-control">
<input type="text" name="" value="<?php echo $post_content ?>" class="form-control">
<input type="text" name="" value="<?php echo $post_status ?>" class="form-control">
//and so on...
</form>
Is this considered to be an acceptable usage of functions and global variables?
If not, what might be a more efficient way to separate the logic from the structure. Rather than encapsulating in a function would includes would be better suited for this task?
Any advice would be very much appreciated and would go a long way in helping a beginner on his journey in programming / php.