Issue
Hello please forgive my question ,
I am fairly new to programming and have confused myself somewhat.
I have created a public function and am trying to echo out a row count on another page which passes the user name value to the function I know this is working because if I print the result in the function itself I get the desired result.
here is the code from my page passing the variable and where I am trying to echo out the result..
which is the number of posts, $xcount
<?php $rez=$crud->postcount($pc); ?>
<div class="card mb-4">
<div class="card-header">Welcome <?php echo $_SESSION['user']?></div>
<div class="card-body">
<div>
<form action="" method="post">
<input type="submit" name="submit" id="submit" class="button" value="log out"/>
</form>
<image src = "<?php echo $_SESSION['user_image']?>" style="max-width:100px; max-height:100px<br>">
<p><?php echo 'Posts created: '.$xcount;?></p>
<p>Contenthere!</a></p>
</div>
</div>
</div>
$pc is defined already and is available in the function where if I print the the result it works.
However the value of $xcount in the code above is not printed and if I hover above it in vscode
it says unset. I know I must be doing something completely daft so please forgive me in advance.
Here is the code from my other page.
public function postcount($pc){
$sql=("SELECT count(*) from `posts` WHERE `created_by` =:pc ");
$res=$this->db->prepare($sql);
$res->bindParam(':pc',$pc);
$res->execute();
$xcount=0;
$xcount= $res->fetchColumn();
print ' number of posts:' .$xcount;
return $res;
}
Solution
When you only want to use the $xcount value in the HTML, you should use the variable $rez, where the functions return value is assigned to:
<?php echo 'Posts created: '.$rez;?>
You should remove the "print" line, else the number would show on top of the page.
The problem is, that $xcount is defined within the scope of the function. So it is not accessible from the outside and this shouldn’t be the case, because it is a unclean way of programming (in most cases).
Answered By – Kevin Glier
Answer Checked By – Marie Seifert (BugsFixing Admin)