-2

I have a function which counts the total of rows of data table. The problem is that this function is working well in localhost, but not in the server side.

In sever side it returns NULL all of the time which is not right.

I don't understand why it work in localhost but not in server(the same version of php)

this is the function:

function getTotal($mysqli, $table, $attribute, $val_id){
    $result=mysqli_query($mysqli,"SELECT count(*) as total from $table WHERE $attribute='$val_id'");
    $data=mysqli_fetch_assoc($result);
    
    $total = $data['total'];
    return $total;
        
}
$total_colis = getTotal($mysqli, '`colis_adr_euro`', 'id_client', $id_user);
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
mery
  • 23
  • 5
  • Add some [error handling](https://www.php.net/manual/en/mysqli.error.php) to your query to see if it fails for some reason (typo in some column name or similar). We don't really know anything about the differences in your two environment so it's hard for us to know what actually happens. You can also check if you see something in your web servers error log. – M. Eriksson Sep 03 '20 at 08:46
  • **Warning:** You are wide open to [SQL Injections](https://stackoverflow.com/a/60496/1839439) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Sep 03 '20 at 10:59
  • 1
    Does this answer your question? [mysqli\_fetch\_assoc() expects parameter / Call to a member function bind\_param() errors. How to get the actual mysql error and fix it?](https://stackoverflow.com/questions/22662488/mysqli-fetch-assoc-expects-parameter-call-to-a-member-function-bind-param) – Dharman Sep 03 '20 at 10:59

1 Answers1

-1
$sql = "SELECT COUNT(*) AS 'total' FROM `".$table."` WHERE `".$attribute."` = '".mysqli_real_escape_string($mysqli, $val_id)."'";

Please try with this query and when u select column from database do not use ' use tide key

Plamen Penchev
  • 357
  • 1
  • 5
  • 15