Solved

Create array from DB then use of in_array tho check names

Posted on 2003-12-08
19
364 Views
Last Modified: 2009-12-16
Hi!

Im pulling out the three players with the highest scores from a table.
This is working as it should.


Then im trying to save these three players in an array within a while-loop.
Does not know how to do this exactly. When printing (print_r) the array
(look at first code snippet below) is showing up on the screen.


<?php
//------------------------------
$sqlScore = mysql_query("SELECT LCASE(name), MAX(score) FROM players GROUP BY name ORDER BY score DESC LIMIT 3");
while($row = mysql_fetch_array($sqlScore)){
//NOT SURE IF BELOW CODE THIS IS CORRECT
$strStars = array($row[0]);
print_r ($strStar);
}
//------------------------------
?>

Now im pulling out a lot of players from another table.
I now want to check the array from above if some of these
players is in the array. This is where im getting trouble.

<?php
$sql = mysql_query("SELECT player FROM other_tbl");
while($row = mysql_fetch_array($sql)){

$strPlayerName = $row[player];

foreach($strStars av $value){
$strChk = in_array($value, $strPlayerName);
if($strChk == 'TRUE'){
print "This player is on of the three best...";
}
}
}
?>


Hope you understand what im after here...

1. Get the three players with the highest score from a table
2. Save these three players in an array
3. Open another table and get players out of it
4. Check if some of these players exists in the array
5. If they exist, do something, set a string, true or false, anything to start with.

It would have been great if this is possible with modifiaction on the above code.
Just for teaching. The may be better solutions but I also want to learn this =)

Best regard and thanks in advance...
0
Comment
Question by:Aknot
  • 10
  • 9
19 Comments
 
LVL 13

Expert Comment

by:lozloz
ID: 9896564
this line is redefining the array each time, not adding to it:

$strStars = array($row[0]);

you want either $strStars[] = $row[0]; or array_push($strStars, $row[0]);

also this line: foreach($strStars av $value){  should be: foreach($strStars as $value){

cheers,

loz

0
 

Author Comment

by:Aknot
ID: 9899487
Hi loz and thanks for your answer =)
Sorry to have to say it did not worked out all the way...

The problem? It seems to displaying ico_isastar.gif (see below) in no particular order?
It almost seems random? It should only show up if you are onte af the stars =)

Im almost there tough =)

This is what im using right now:

<?php
//THIS PICE OF CODE IS NOT INSIDE ANY WHILE LOOP
//GET THE 3 FIRST STARS

$sqlRepStars = mysql_query("SELECT LCASE(username), MAX(starvalue) FROM members GROUP BY username ORDER BY starvalue DESC LIMIT 3");
while($row = mysql_fetch_array($sqlRepStars)){
$strRepArrStar[] = array($row[0]);
}
?>

If I print_r the var $strRepArrStar, this is showing up:
//---
Array ( [0] => Array ( [0] => kenzilla ) ) Array ( [0] => Array ( [0] => kenzilla ) [1] => Array ( [0] => tolkien_fan ) ) Array ( [0] => Array ( [0] => kenzilla ) [1] => Array ( [0] => tolkien_fan ) [2] => Array ( [0] => aknot ) )
//---
Is this correct? No keys?

<?php
//THIS CODE IS INSIDE A MYSQL DB WHILE LOOP
//THIS IS WHERE I AM FETCHING THE VAR $strRepUserName

//LOOP THE ARRY TO FIND USERS THAT ARE STARS
foreach($strRepArrStar as $strRepStar){
if (in_array(strtolower($strRepUserName), $strRepStar)){
$strReplayStar = "<img src=\"../images/ico_isastar.gif\">&nbsp;";
}
}
?>

If you not know what I am after, please ask =)
Im also increasing tho points with 200 to 350 =)
0
 
LVL 13

Expert Comment

by:lozloz
ID: 9900622
$strRepArrStar[] = array($row[0]); should be $strRepArrStar[] = $row[0]; you don't need the array() bit as i said

loz
0
 

Author Comment

by:Aknot
ID: 9902396
Oooh I didn't saw that =(
Alway to frustrated to se all the chars hehe...

Going to try it the first thing after work =)

Thanks again
0
 

Author Comment

by:Aknot
ID: 9905972
Does not work!
Have changed the code and removed the array() bit as u described to th following:

<?php
$sqlRepStars = mysql_query("SELECT LCASE(username), MAX(starvalue) FROM members GROUP BY username ORDER BY starvalue DESC LIMIT 3");
while($row = mysql_fetch_array($sqlRepStars)){
$strRepArrStar[] = $row[0];
}
?>

Getting:
Warning: in_array(): Wrong datatype for second argument in D:\www\Apache\Apache2\htdocs\forum\thread.php on line 214 (Win32 is devel environment )

line 214 => if(in_array($strRepUserName, $strRepStar)){ //See above

Thinking of skipping this feature soon, it makes me crazy. I have never worked with arrays in this way before. Does not know where to find the error. Maybe this type of function is impossible to do/make?

When printing the variable '$strRepArrStar' this is displayed on the screen:
Array ( [0] => Kenzilla )
Array ( [0] => Kenzilla [1] => Tolkien_Fan )
Array ( [0] => Kenzilla [1] => Tolkien_Fan [2] => Aknot )

Is this correct? What does it mean? Is the last line the complete full array?

Thanks...
0
 
LVL 13

Expert Comment

by:lozloz
ID: 9906508
yes the last line is the full one, basically you're getting 3 rows from a database and putting them into an array. so for your first line you have an array with 1 element, kenzilla. on the 2nd loop, you add another row from the database, so you have 2 items, and then finally 3. then to match against the other table you'd do:

$sql = mysql_query("SELECT player FROM other_tbl");
while($row = mysql_fetch_array($sql)){
  foreach($strRepArrStar as $value){
    if($value == $row["player"]){
      print "This player (" . $row["player"] . ") is one of the three best...";
    }
  }
}

this is how i would do it.. i wouldn't use in_array. try that out and tell me if it works,

cheers,

loz
0
 

Author Comment

by:Aknot
ID: 9906615
Hi agan loz!

Yes this works like a swiss made swatch =)

The code thats works looks like this (exactly):

<?php
$sqlRepStars = mysql_query("SELECT username, MAX(starvalue) FROM members GROUP BY username ORDER BY starvalue DESC LIMIT 3");
while($row = mysql_fetch_array($sqlRepStars)){
$strRepArrStar[] = $row["username"];
  foreach($strRepArrStar as $value){
    if($value == $row["username"]){
      print "This player (" . $row["username"] . ") is one of the three best...";
    }
  }
}
?>

And the result on the screen is (exactly):

This player (Kenzilla) is one of the three best...This player (Tolkien_Fan) is one of the three best...This player (Aknot) is one of the three best...

How do I continue from here? Do you have any tip on how to compare these names with names from another table/MySQL WhileLoop without an in_array function?
0
 

Author Comment

by:Aknot
ID: 9906635
Geeee now I see... My fault... This was the second db while... Sorry... My head (brain) is loosing it :/ I'll try again...
0
 
LVL 13

Expert Comment

by:lozloz
ID: 9908506
yes this is your second db, try this to see all your results from this 2nd db

$sqlRepStars = mysql_query("SELECT username, MAX(starvalue) FROM members GROUP BY username ORDER BY starvalue DESC LIMIT 3");
while($row = mysql_fetch_array($sqlRepStars)){
$strRepArrStar[] = $row["username"];
  foreach($strRepArrStar as $value){
    if($value == $row["username"]){
      print "This player (" . $row["username"] . ") is one of the three best...<br />\n";
    } else {
      print "This player (" . $row["username"] . ") is not in the top 3!<br />\n";
    }
  }
}
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 

Author Comment

by:Aknot
ID: 9910427
God morning!

Didn't work, I know that you for sure do not like to read this answer. Neither do I. Maybe there is

something else causing this errors/problems. Both with setting the array and extracting the data from it.

There may be a bug somewhere. A bug that occurs in some rare combination. Maybe a setting in php.ini, I do

not know.

I was thinking of a another way that I came up with yeasterday. When programming .asp, I was using a amazing

VB function called instr(). InString. Works like this:

<%
strHost = Request.ServerVariables("HTTP_REFERER")
IF InStr(strHost, "lozloz") OR InStr(strHost, "loz.com") THEN
Response.Write "Hey u must be from www.lozloz.com =)"
END IF
%>

Why dont merge all these names in to one big long and nasty string?
Like this:

<?php
//NAME FROM FIRST TABLE
$sqlRepStars = mysql_query("SELECT LCASE(username), MAX(starvalue) FROM members GROUP BY username ORDER BY

starvalue DESC LIMIT 3");
while($row   = mysql_fetch_array($sqlRepStars)){
$strStarUser = $row[0];
$strStarUser = ($strStarUser & $strStarUser);
}
?>

This is giving me the following string:
print $strStarUser;

Name1Name2Nam3

Now I would be able to to use a PHP function similar to instr().
Wouldnt I? Needle and Haystack.

I was searching for a similar function to instr and found a lot.
preg_match, ereg(i), strrpos...

strrpos seemed to be the right choice. Now to the new problem as
it did not worked as I tought.

I was testing this

<?
//ROW FROM SECOND TABLE
$strUserName = $row[username];

//THE CHECK
if ((strpos($strStarUser,$strUserName) ? strpos($strStarUser,$strUserName)+1 : 0))
{
print"This user ($strUserName) is a star...";
}else{
print"This user ($strUserName) is NOT a star...";
}
?>

As I expected, this does not work either. It only seems to be finding the last name, name3. It also seems

that strrpos is looking from right to the left, correct? What does +1 : 0 do?
Cant find anything about it in the php manual...

I was also trying to use the PHP function strlen() to calculate the length
of the string. The tell strrpos in wich interval to look in the string. Did
not work either...


You are my last hope Obi One Loz...
0
 
LVL 13

Expert Comment

by:lozloz
ID: 9911698
this is the wrong way to go about it - don't lose hope in your original method, it will work it just needs a bit of debugging. putting everything into a string and then doing a search is much worse coding technique. let's go back to my last post and add some debugging so we can see exactly what is happening


$sqlRepStars = mysql_query("SELECT LCASE(username), MAX(starvalue) FROM members GROUP BY username ORDER BY starvalue DESC LIMIT 3") or die(mysql_error());
while($row = mysql_fetch_array($sqlRepStars)){
$strRepArrStar[] = $row[0];
print "adding " . $row[0] . " to strRepArrStar<br />";
}
print "<br /><br / >";
$sqlRepStars2 = mysql_query("SELECT username, MAX(starvalue) FROM members GROUP BY username ORDER BY starvalue DESC LIMIT 3") or die(mysql_error());
while($row2 = mysql_fetch_array($sqlRepStars2)){
  foreach($strRepArrStar as $value){
    print "testing $value against " . $row2["username"] . "<br />;
    if($value == $row2["username"]){
      print "This player (" . $row2["username"] . ") is one of the three best...<br />\n";
    } else {
      print "This player (" . $row2["username"] . ") is not in the top 3!<br />\n";
    }
  }
}

can you give me the output from that and we'll see what's really happening

loz
0
 

Author Comment

by:Aknot
ID: 9913561
Hi there!

First of all, in my last post, not God Morning, Good morning *lol*
I always see all the typo-errors afterwords...

Ok, Ill stick with the first method =)
This is the exact output of your last code:

[OUTPUT]
adding kenzilla to strRepArrStar
adding tolkien_fan to strRepArrStar
adding aknot to strRepArrStar


testing kenzilla against Kenzilla
This player (Kenzilla) is not in the top 3!
testing tolkien_fan against Kenzilla
This player (Kenzilla) is not in the top 3!
testing aknot against Kenzilla
This player (Kenzilla) is not in the top 3!
testing kenzilla against Tolkien_Fan
This player (Tolkien_Fan) is not in the top 3!
testing tolkien_fan against Tolkien_Fan
This player (Tolkien_Fan) is not in the top 3!
testing aknot against Tolkien_Fan
This player (Tolkien_Fan) is not in the top 3!
testing kenzilla against Aknot
This player (Aknot) is not in the top 3!
testing tolkien_fan against Aknot
This player (Aknot) is not in the top 3!
testing aknot against Aknot
This player (Aknot) is not in the top 3!
[/OUTPUT]

0
 
LVL 13

Expert Comment

by:lozloz
ID: 9913647
hah well that was stupid of me.. you're using the mysql function LCASE on the column username in the first query but not in the second. therefore when it tests whether the two strings are the same, it fails because one has a capital letter and the other doesn't. so either make them both LCASE(username) or both username

i just realised we're using a different query there compared to when we started but the point probably still stands

$sql = "SELECT player FROM other_tbl";

was your original query, so i guess you'll want to swap that for the 2nd query

loz
0
 

Author Comment

by:Aknot
ID: 9913705

Hehe =) Didn't see that either... Used LCASE() to be sure that capital letters would not cause any of these errors. Now thay did =) Anyway, now displaying:


adding Kenzilla to strRepArrStar
adding Tolkien_Fan to strRepArrStar
adding Aknot to strRepArrStar


testing Kenzilla against Kenzilla
This player (Kenzilla) is one of the three best...
testing Tolkien_Fan against Kenzilla
This player (Kenzilla) is not in the top 3!
testing Aknot against Kenzilla
This player (Kenzilla) is not in the top 3!
testing Kenzilla against Tolkien_Fan
This player (Tolkien_Fan) is not in the top 3!
testing Tolkien_Fan against Tolkien_Fan
This player (Tolkien_Fan) is one of the three best...
testing Aknot against Tolkien_Fan
This player (Tolkien_Fan) is not in the top 3!
testing Kenzilla against Aknot
This player (Aknot) is not in the top 3!
testing Tolkien_Fan against Aknot
This player (Aknot) is not in the top 3!
testing Aknot against Aknot
This player (Aknot) is one of the three best...

Getting closer to a solution now?
0
 
LVL 13

Expert Comment

by:lozloz
ID: 9913810
well the debugging there simply shows Kenzilla, Tolkien_Fan and Aknot are in the top 3. you're then checking against these 3 again so obviously all 3 are going to be in the top 3. i guess that output isn't using other_tbl unless you have 3 records in other_tbl as well?

loz
0
 

Author Comment

by:Aknot
ID: 9914052
Yes of course, you are right =)
I used the same table twice :-/

But now there is a big dirrerence =)

[KENZILLA => MATCH]
testing Kenzilla against Kenzilla
---> This player (Kenzilla) is one of the three best...
testing Tolkien_Fan against Kenzilla
This player (Kenzilla) is not in the top 3!
testing Aknot against Kenzilla
This player (Kenzilla) is not in the top 3!
[/KENZILLA]




[TOLKIEN_FAN => MATCH]
testing Kenzilla against Tolkien_Fan
This player (Tolkien_Fan) is not in the top 3!
testing Tolkien_Fan against Tolkien_Fan
---> This player (Tolkien_Fan) is one of the three best...
testing Aknot against Tolkien_Fan
This player (Tolkien_Fan) is not in the top 3!
[/TOLKIEN FAN]




[AKNOT MATCH]
testing Kenzilla against Aknot
This player (Aknot) is not in the top 3!
testing Tolkien_Fan against Aknot
This player (Aknot) is not in the top 3!
testing Aknot against Aknot
---> This player (Aknot) is one of the three best...
[/AKNOT]




[NO MATCH, OTHER USER (NAME:SUPERSTAR)]
testing Kenzilla against Superstar
This player (Superstar) is not in the top 3!
testing Tolkien_Fan against Superstar
This player (Superstar) is not in the top 3!
testing Aknot against Superstar
This player (Superstar) is not in the top 3!
[/NO MATCH]

Better? hehe =)
0
 
LVL 13

Accepted Solution

by:
lozloz earned 375 total points
ID: 9914155
so the matching is working, it's just you want one message for each one?

then use this for the 2nd part of the code:

while($row2 = mysql_fetch_array($sqlRepStars2)){
  foreach($strRepArrStar as $value){
    $test = FALSE;
    print "testing $value against " . $row2["username"] . "<br />;
    if($value == $row2["username"]){
      $test = TRUE;
      break;
    } else {
      $test = FALSE;
    }
  }
  if($test) {
    print "This player (" . $row2["username"] . ") is one of the three best...<br />\n";
  } else {
    print "This player (" . $row2["username"] . ") is not one of the three best...<br />\n";
  }
}

i think that'll work, if it doesn't you might need to change break; to break 2;

loz
0
 

Author Comment

by:Aknot
ID: 9914270
Jihaaa it works =) Did some quick changes and its working =)

A megaBig thanks. You did it. My girlfriend just told me that I have occupied the computer for about 20 hours with this problem/function. (Time is not important, only proper functions) =)

Take a look at this picture, it shows the results. Look at the non formattet text. Its from the development of the new, non .asp page:
http://www.filmbetyg.nu/loz-aknot_exp-exc-php-fix_00001.gif

Put in an ok here when u have seen the screenshot...

Thanks again and have nice evening...
0
 
LVL 13

Expert Comment

by:lozloz
ID: 9914344
looks nice, shouldn't be too hard to format it properly, just a few tags around the text. glad to help anyway

cheers,

loz
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now