I’ve got two recursive functions:
1)
function getCategories($id)
{
global $con;
$select = $con->prepare('SELECT * FROM categories WHERE parent_category_id = :parent_category_id OR (parent_category_id IS NULL AND :parent_category_id IS NULL)');
$select->bindValue(':parent_category_id', $id, PDO::PARAM_NULL || PDO::PARAM_INT);
$select->execute();
// fetching.........
for() ... getCategories(.......);
}
2)
$select = $con->prepare('SELECT * FROM categories WHERE parent_category_id = :parent_category_id OR (parent_category_id IS NULL AND :parent_category_id IS NULL)');
function getCategories($id)
{
global $select;
$select->bindValue(':parent_category_id', $id, PDO::PARAM_NULL || PDO::PARAM_INT);
$select->execute();
// fetching.........
for() ... getCategories(.......);
}
Which is better/faster?
Is it better to preapre the statment one time only?
Second one should be faster because you don’t call not needed statements. The idea of prepared statements is that you must prepare it once. But the best way to find out is profiling.
Here’s simple way: