DevStud DevStud - 1 year ago 71
MySQL Question

Undefined variable if count 0

i have a little bit problem with my following code. I am trying to make a star raiting system and following code is showing raiting details. But i am getting

undefined variable rate_db notice

What i missing here anyone can tell me please ?

full code is here:

$query = mysqli_query($db,"SELECT ryid,r_type FROM profileRaiting WHERE rp_uid='$profile_uid'");
while($data = mysqli_fetch_assoc($query)){
$rate_db[] = $data;
$sum_rates[] = $data['r_type'];
$rate_times = count($rate_db);
$sum_rates = array_sum($sum_rates);
$rate_value = $sum_rates/$rate_times;
$rate_bg = (($rate_value)/5)*100;
} else {
$rate_times = 0;
$rate_value = 0;
$rate_bg = 0;

Answer Source

It's better to initialize your both arrays at top as:

$rate_db = array(); 
$sum_rates = array();

And i don't know where you define this variable $profile_uid, if it's user input or session value, than your code is open for SQL Injection, you can use Prepared Statement to prevent SQL attack. And this post will help you to understand: How can I prevent SQL injection in PHP?

Side Note & Suggestion:

One more thing, you can also get the sum of r_type as:

$sum_rates += $data['r_type'];

In this case, you need to initialize $sum_rates as:

$sum_rates = 0;

And just remove this line from IF condition:

$sum_rates = array_sum($sum_rates);

Benefit, no need to use extra method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download