I'm trying to generate the top 10 tags, I think it's pretty straightforward.
//generate 10 top tags
$tagSQL = mysql_fetch_array(mysql_query("SELECT * FROM tags"));
$topArray = array();
foreach($tagSQL as $poland)
{
if($poland["tagID"] == 1)
{
$topArray[0] = $topArray[1] + 1;
}
if($poland["tagID"] == 2)
{
$topArray[1] = $topArray[2] + 1;
}
if($poland["tagID"] == 3)
{
$topArray[2] = $topArray[3] + 1;
}
if($poland["tagID"] == 4)
{
$topArray[3] = $topArray[4] + 1;
}
}
function printTopTags()
{
$n = 0;
foreach($topArray as $buddha)
{
$n = $n + 1;
if(sizeOf($topArray) > $n)
{
$hersheyBar = " ";
}
else
{
$hersheyBar = "";
}
$finalFinalEndArray = mysql_fetch_array(mysql_query("SELECT tagName FROM tags WHERE tagID = '$buddha'");
foreach($finalFinalEndArray as $waterBottle)
{
echo $waterBottle . $hersheyBar;
}
}
}
The only problem I'm having is that it thinks I have a syntax error somewhere in the code, but no matter which lines I omit the syntax error stays.
Also, is there an easier way to do my if statements for 10 different array spots, rather than the four?
You are missing a ")" at the end of this statement
It should be
$finalFinalEndArray = mysql_fetch_array(mysql_query("SELECT tagName FROM tags WHERE tagID = '$buddha'"));
optimystique is right about the syntax error.
Regarding your second question, shmeeps' method works for this example, but if you happen to have another situation where you need to compare one variable to a number of different values, then you can use a switch statement instead of a whole bunch of ifs. For example (From the above linked PHP manual page):
<?php
if ($i == 0) {
echo "i equals 0";
} elseif ($i == 1) {
echo "i equals 1";
} elseif ($i == 2) {
echo "i equals 2";
}
?>
is the same as:
<?php
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
?>
The if-then statements should be able to be generalized as
$topArray[($poland["tagID"] - 1)] = $topArray[$poland["tagID"]] + 1;
with no if-then statements at all.
I don't see any syntax errors. Is there more to this script?
Edit: Saw the error now, this line
$finalFinalEndArray = mysql_fetch_array(mysql_query("SELECT tagName FROM tags WHERE tagID = '$buddha'");
Should be
$finalFinalEndArray = mysql_fetch_array(mysql_query("SELECT tagName FROM tags WHERE tagID = '$buddha'"));
Note the extra )
Related
I am working on a bit of PHP and I've come upon a bit of issues.
I am using PHP to randomly choose a number from 1-360. I am trying to compare the answer to a list of value determined by range.
$NumberA = rand(0,180);
$NumberB = rand(0,180);
$NumberC = $NumberA + $NumberB;
if ($NumberC = range(0,21) {
$result = "Orange";
}
elseif ($NumberC = range(22,42) {
$result = "Red";
}
elseif ($NumberC = range(43,63) {
$result = "Blue";
}
//This goes on for a while ...
else {
$result = "Green";
}
echo = $result;
Anytime i do this, the result always assigns the value of "Orange" to $result .
Im sure im doing something wrong here, please help!
First of all, you used just one '=' to compare while it should have been '=='. Second range() generates an array and you cannot compare an integer to an array. Third why generating the range every single time when you can check that $NumberC lies between the minimum and the maximum numbers of the range?
Change your code to:
$NumberA = rand(0,180);
$NumberB = rand(0,180);
$NumberC = $NumberA + $NumberB;
if ($NumberC >= 0 && $NumberC <= 21) {
$result = "Orange";
} elseif ($NumberC >= 22 && $NumberC <= 42) {
$result = "Red";
} elseif ($NumberC >= 43 && $NumberC <= 63) {
$result = "Blue";
} else {
$result = "Green";
}
echo $result;
Shall work. Hope this helps.
So, I have code like this at the start of a bigger set of loops
for ($k=1;$k<=60-$jrow['blocks'];$k += $jrow['blocks'])
{
for ($j=0;$j=(count($sarray)-1);$j++)
{
The size of $sarray is 2
Now, when I apply this:
if (isset($j) AND $k == 1)
{
echo "<h1>".$j."</h1>";
}
I get an output of 1. Now clearly $k is still in it's first iteration, but it seems like $j has somehow skipped onto it's second and isn't starting at 0. What am I doing wrong.
Whole code, if required:
for ($k=1;$k<=60-$jrow['blocks'];$k += $jrow['blocks'])
{
for ($j=0;$j=(count($sarray)-1);$j++)
{
if (isset($j) AND $k == 1)
{
echo "<h1>".$j."</h1>";
}
for ($l=$k;$l=($k+$jrow['blocks']-1);$l++)
{
$uid = $sarray[$j];
$staffquery = $hsdbc->prepare("SELECT * FROM user WHERE userID = :uid");
$staffquery->bindParam(':uid',$uid);
$staffquery->execute();
$staffid = $staffquery->fetch(PDO::FETCH_ASSOC);
if (isset($staffid['userid']))
{
echo "<h1>staff query orking</h1>";
die();
}
if ($staffid['complevel'] > $jrow['complevel'])
{
if ($l + ($jrow['blocks'] - 1) < 20 * $i)
{
$schedquery = $hsdbc->prepare("SELECT * FROM schedule WHERE slot = :sn");
$schedquery->bindParam(':sn',$l);
$schedquery->execute();
$schedrow = $schedquery->fetch(PDO::FETCH_ASSOC);
if ($schedrow['jobID'] == 0)
{
for ($m=$l;$m=($l+$jrow['blocks']-1);$m++)
{
$setquery = $hsdbc->prepare("UPDATE schedule SET jobID = :jid WHERE userID=:uid AND slot = :sn");
$setquery->bindParam(':jid',$jrow['jobID']);
$setquery->bindParam(':uid',$staffid['userid']);
$setquery->bindParam(':sn',$m);
$setquery->execute();
}
$cjobquery = $hsdbc->prepare("UPDATE job SET statusID = 1 WHERE jobID = :jid");
$cjobquery->bindParam(':jid',$jrow['jobID']);
$cjobquery->execute();
Break 6;
}
}
}
}
}
}
I think you meant to write. This is probably a typo.
for ($j=0;$j<=(count($sarray)-1);$j++)
$j = (count($sarray)-1)
this is an assignment, use the == operator for equality comparison, or <=, >= for order comparison.
I'm asking MySQL for data, but it slows down the whole script. Yet I have no idea how to get this out of a loop. I tried converting it to PHP array but honestly after day of tries I failed.
<?php
$id = '1';
include_once 'include_once/connect.php';
for ($x = 1; $x <= 5; $x++) {
for ($y = 1; $y <= 5; $y++) {
$xy = $x."x".$y;
$pullMapInfo = "SELECT value FROM mapinfo WHERE id='".$id."' AND xy='".$xy."'";
$pullMapInfo2 = mysql_query($pullMapInfo) or die('error here');
if ($pullMapInfo3 = mysql_fetch_array($pullMapInfo2)) {
#some code
} else {
#some code
}
}
}
?>
How to get MySQL query $pullMapInfo2 out of loop to shorten loading it by asking once?
If you want to fire script on your localhost you can c&p whole thing :-)
I'm not sure what you have in your table, but considering you are basically looping through virtually everything in it, I'd say do a single query for the given Id and then sort out what you need from the larger dataset.
Especially if you are always pulling back essentially the complete dataset for each id, there's no reason to even bother with the IN query, just pull it all back into a single PHP array, and then iterate through that as needed.
Use a MySQL IN clause
<?php
$id = '1';
include_once 'include_once/connect.php';
// first we create an array with all xy
$array = array();
for ($x = 1; $x <= 5; $x++) {
for ($y = 1; $y <= 5; $y++) {
$xy = $x."x".$y;
$array[] = $xy;
}
}
$in = "'" . implode("', '", $array) . "'";
$pullMapInfo = "SELECT xy, value FROM mapinfo WHERE id='".$id."' AND xy IN ({$in})";
$pullMapInfo2 = mysql_query($pullMapInfo) or die('error here');
// we create an associative array xy => value
$result = array();
while (($pullMapInfo3 = mysql_fetch_assoc($pullMapInfo2)) !== false) {
$result[ $pullMapInfo3['xy'] ] = $pullMapInfo3['value'];
}
// we make a loop to display expected output
foreach ($array as $xy)
{
if (array_key_exists($xy, $result)) {
echo '<div class="castle_array" style="background-image: url(tiles/'.$result[$xy].'.BMP)" id="'.$xy.'">'. $result[$xy] .'</div>';
} else {
echo '<div class="castle_array" id="'.$xy.'"></div>';
}
echo '<div class="clear_both"></div>';
}
?>
I'm trying to implement something like facebook's like widget which says something like:
You, Name1, Name2 and 20 other people like this
I fetched all my data to be able to display this HTML, but I can't seem to find the right algo to form the HTML string.
My main problem is that I don't know when to put the and string or the , (comma) string. If I just had to put names, it would work, but the problem is that the You string always has to be first.
I'm going to paste my code here and the output I'm getting for some special cases (it's PHP).
$current_user = 0;
$html = "";
$count = count($result);
$key = 0;
foreach($result as $liked){
if($key + 1 > $limit)
break;
if($liked->uid == $user->uid){
$current_user = 1;
continue;
}
$html .= "<a href='".$liked->href."'>".$liked->name."</a>";
if($key < $count - 2)
$html .= ", ";
elseif($key == $count - 2 && $key + 1 != $limit)
$html .= " and ";
$key++;
}
if($current_user){
$userHtml = "You";
if($count > 2)
$userHtml .= ", ";
elseif($count > 1)
$userHtml .= " and ";
$html = $userHtml.$html;
}
$html = "♥ by ".$html;
if($count > $limit){
$difference = $count - $limit;
$html .= " and ".$difference." ".format_plural($difference,"other","others");
}
return $html;
And in the special case where the current user is the last one to like this, it will show:
♥ by You, admin, edu2004eu and
Notice the and word doesn't have anything after it, because You should have been after it, but I put it at the beginning. Any help? I just need the logic, not the actual code.
You can try something like this:
$likedBy = array('admin', 'eduard', 'jeremy', 'someoneelse');
// check if I like it and if so move me to the front
if (in_array($currentUsername, $likedBy)) {
$me = array_search($currentUsername, $likedBy);
unset($likedBy[$me]);
array_unshift($likedBy, 'You');
}
// remove anything after the limit
$extra = array_splice($likedBy, 3);
// the comma list
$html = implode(', ', $likedBy);
// any extras? if so, add them here, if not rewrite the list so
// it's "You, Eduard and admin"
if (!empty($extra)) {
$html .= ' and '.count($extra);
} else {
$lastguy = array_splice($likedBy, 1);
$html = implode(', ', $likedBy).' and '.$lastguy;
}
$html .= ' like this';
Eduard,
You can fix this simply by putting $key++; at the top of the loop and taking out all the places where you have $key + 1 in the loop.
I think what's happening is that $key + 1 is assuming that there is a current user.
This line would also not display the current user if they are not in the first $limit number of entries
if($key + 1 > $limit)
break;
You can fix this by putting this after the code that looks for the current user.
In Java (I know, but its what I had running) it would look something like:
List<String> users = Arrays.asList("Brian","Tom","Jack","John");
int key = 0;
String html = "";
String currentUser = "Brian";
int limit = 3;
boolean foundCurrentUser = false;
for (String user : users) {
key ++;
if (currentUser == user) {
foundCurrentUser = true;
continue;
}
if (key > limit) {
continue;
}
html += user;
if (key < users.size() - 1) {
html += ",";
} else if (key == users.size() - 1 && key != limit) {
html += " and ";
}
}
if (foundCurrentUser) {
String userHTML = "You";
if (key > 2) {
userHTML += ", ";
} else if (key == 1) {
userHTML += " and ";
}
html = userHTML + html;
}
html = "Likeed by " + html;
if (users.size() > limit ) {
html += " and 3 other people";
}
System.out.println(html);
edit
Thought i need to add more info. This first query is MySQL, the latter two are PGSQL, and its located on a seperate server. When i disable the second query in the second part of this, its still just as slow.
SELECT n.id, n.number, n.assigned, n.btn, n.status as stat, s.status
FROM numbers n
LEFT JOIN status s on n.status=s.id
where number like '239333%'
LIMIT $start, $limit
I have the following query, this pulls a range of numbers from a DB, this is a pretty quick query, as I have it limited to 50 or 100.
This lists the output in a while loop in PHP..
Within this while loop, there is a second connection to a seperate server (postgres) to do additional checks on this number which is done through a function, so in the loop i have for example $mq = addition_checks($number);
$query = "SELECT count(baseinformation_directorynumber) as count FROM \"public\".\"meta_subscriber\" WHERE baseinformation_directorynumber = $number";
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
$row = pg_fetch_assoc($result);
$did = "0";
if ($row['count'] == '0') {
$query2 = "SELECT count(lastdirectorynumber) as count FROM \"public\".\"meta_pbx_directinwardcalling\" where firstdirectorynumber <= $number and $number <= lastdirectorynumber";
$result2 = pg_query($query2) or die('Query failed: ' . pg_last_error());
$row2 = pg_fetch_assoc($result2);
if ($row2['count'] == '1') {
$did = $row2['count'];
$row['count'] = "0";
}
}
pg_free_result($result);
// Closing connection
$line = $row['count'];
$match = array('line' => $line, 'did' => $did);
return $match;
After this I do a couple more checks to display the information as needed.
The problem is that when I added the additional_checks query, it takes about 30 seconds to load 50 items. Im asking (due to lack of knowledge) how I can increase the speed of this to be a little more acceptable.
If it helps, here it my main while look
while ($q->getrow()) {
$number = $q->field('number'); $assigned = $q->field('assigned'); $btn = $q->field('btn'); $id = $q->field('id'); $status = $q->field('status'); $stat = $q->field('stat');
$nc++; //Start Counter
$now = time();
$diff = $now - $time;
if ($alternate == "1") {
$color = "#EFEFEF";
$alternate = "2";
} else {
$color = "#DFDFDF";
$alternate = "1";
}
$match = meta_query($q->field('number'));
if ($match['line'] == '1' and $match['did'] == '0') {
$numcolor = "green";
$did = "";
} elseif ($match['did'] == '1' AND $match['line'] == '0') {
$did = "[DID]";
$numcolor = "green";
} else {
$did = "";
if ((!$assigned) AND (!$btn) AND ($stat == '1' OR $stat == '4')) {
$numcolor = "";
} else {
$numcolor = "red";
}
}
//if ($numcolor = "red" AND $assigned == '' AND $btn == '' AND $stat == '1') {
// $numcolor = "";
//}
//print_r($match);
if ($stat == '4') { $color = "C2FACB"; }
elseif ($stat == '2') { $color="FCFBEA"; }
// else {
$ajaxedits .= "EditInPlace.makeEditable({ id: 'btn:$id' });\n";
$ajaxedits .= "EditInPlace.makeEditable({ id: 'assigned:$id' });\n";
$ajaxedits .= "EditInPlace.makeEditable({
id: 'status:$id',
type: 'select',
save_url: 'optionedit_eip.php',
options: {
1: 'Free',
2: 'In use',
3: 'Disconnected',
4: 'Ported Out'
}
});";
//}
//<span class="red" id="status:$id">Dark Green</span>
//
if (isset($right[admin])) {
$clear = " (Clear)";
}
eval("\$list_numbers .= \"".addslashes($TI[5])."\";");
}
$q->free;
the following
$match = meta_query($q->field('number'));
is the function where it calls to do the additional postgres checks which is listed above. Yes my code is ugly, im still a noob. :)
SQL queries within loops can be avoided. One way is to collect all $numbers in a php array and then run a single query after the loop.
..WHERE baseinformation_directorynumber IN ($num1, $num2, ...);
You'll get counts of all numbers in a single go. This will speed up the execution.
I've found a blog post containing more ways to avoid sql in loops. check article
Look into using a JOIN on the two tables. Then you can compare the speeds, but depending on the number of rows that you have, a JOIN should be quicker than two queries.