Reputation: 23
Okay first let me just say that my script works fine it just shows these warning when nothing is in the database. What I want is to make the warnings go away even when nothing is in the database.
How can correct this problem? And what part of my code do I need to change?
Here is the warnings.
Warning: ksort() expects parameter 1 to be array, null given on line 24
Warning: array_values() [function.array-values]: The argument should be an array on line 38
Warning: Wrong parameter count for min() on line 38
Warning: array_values() [function.array-values]: The argument should be an array on line 39
Warning: Wrong parameter count for max() on line 39
Warning: Invalid argument supplied for foreach() on line 49
Here is the full code below.
<?php
require_once ('./mysqli_connect.php');
$link = mysqli_connect("localhost", "root", "", "sitename");
function tag_info($link) {
$page = "3";
$query = "SELECT tags.tag,
COUNT(questions_tags.tag_id) 'num'
FROM questions_tags
JOIN tags ON tags.id = questions_tags.tag_id
WHERE questions_tags.users_questions_id = '$page'
GROUP BY tags.tag
ORDER BY num DESC";
if ($result = mysqli_query($link, $query)) {
while($row = mysqli_fetch_array($result)) {
$arr[$row['tag']] = $row['num'];
}
ksort($arr);
return $arr;
}
return array();
}
function tag_cloud($link) {
$min_size = .8;
$max_size = 1.5;
$tags = tag_info($link);
$minimum_count = min(array_values($tags));
$maximum_count = max(array_values($tags));
$spread = $maximum_count - $minimum_count;
if($spread == 0) {
$spread = 1;
}
$cloud_html = '';
$cloud_tags = array();
foreach ($tags as $tag => $count) {
$size = $min_size + ($count - $minimum_count) * ($max_size - $min_size) / $spread;
$cloud_tags[] = '<a style="font-size: '. $size . 'em'
. '" class="tag_cloud" href="http://www.example.com/tags/' . $tag .'/'
. '" title="\'' . $tag . '\' returned a count of ' . $count . '">'
. htmlspecialchars(stripslashes($tag)) . '</a>';
}
$cloud_html = join("\n", $cloud_tags) . "\n";
return $cloud_html;
}
?>
@Franz Now I get these warnings.
Warning: min() [function.min]: Array must contain at least one element on line 39
Warning: max() [function.max]: Array must contain at least one element on line 40
Upvotes: -1
Views: 1511
Reputation: 8459
Replace :
ksort($arr);
return $arr;
With :
if(empty($arr)){
return array();
}
ksort($arr);
return $arr;
Then, to be sure replace also this :
$tags = tag_info($link);
with :
$tags = tag_info($link);
if(empty($tags)){
return '';
}
Upvotes: 1
Reputation: 11553
This should work: You forgot the case when no rows are returned (in your code):
if ($result = mysqli_query($link, $query))
{
$arr = array();
while($row = mysqli_fetch_array($result))
{
$arr[$row['tag']] = $row['num'];
}
ksort($arr);
return $arr;
}
return array()
Upvotes: 1