I have three files conn.php
, func.php
and index.php
in the conn.php
i have my connection to the database and in index.php
I've included the connection file while in func.php
I've a function that counts the number of columns
func.php
<?php
function countusers($connection, $column, $table)
{
$stmt = mysqli_prepare($connection, "
SELECT
COUNT($column)
FROM
$table");
if($stmt)
{
mysqli_stmt_bind_result($stmt, $num);
mysqli_execute($stmt);
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
}
return $num;
}
But it doesn't seem to work I've tried adding the connection file in the function and it worked.
here is my index file
index.php
<?php
require_once "conn.php";
include "func.php";
echo countusers($conn, "id", "mods");
conn.php
<?php
$conn = mysqli_connect("localhost", "root", "", "test", 3306);
if(!$conn)
{
echo "An Error Occurred";
}
A quick read up in php.net states that the bind_result must occur after the execute... I have not run this so its a suggestion only.
So you could try...
//... SNIP...
if($stmt)
{
mysqli_stmt_execute($stmt); // Changed this to mysqli_stmt_execute
mysqli_stmt_bind_result($stmt, $num);
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
}
else {
$num = 0;
}
return $num;
// ... SNIP ...
Also what is your default value for $num in the case that $stmt is false? You need to decide and set that.
UPDATE: The default value for $num has been added in the case the stmt fails for any reason. I have since run this code and it works.
The changes suggested in the code snippet DOES provide a value for $num, whereas the original code did not.
As to the validity of the actual method/implementation used is another matter, this answer directly addressed the question at hand.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments