PDA

View Full Version : Display data if variable = data in a field


Crazydog
11-01-2006, 06:28 PM
First: Here's the script I'm testing it with
<?
$user="user";
$password="pass";
$database="db";

mysql_connect(localhost,$user,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM saved_info";
$result=mysql_query($query);
$person='crazy2';
$num=mysql_numrows($result);

mysql_close();

echo "<b><center>Database Output</center></b><br><br>";

$i=0;
while ($i < $num &&) {

$id=mysql_result($result,$i,"id");
$test=mysql_result($result,$i,"test");
$nickname=mysql_result($result,$i,"nickname");

echo $id . $test . $nickname;

$i++;
}

?>
What this is doing right now is just grabbing+displaying data from a DB.
As you can see, I have assigned the variable $person a value. Eventually, php will pull that value from elsewhere.
The field "nickname" contains usernames of registered members. I would want this script to (after grabbing the username and assigning it to the $person variable) only show records with their username in the nickname field.

guelphdad
11-01-2006, 09:56 PM
can you show some sample data as well as the output your are looking to achieve?

Beagle
11-02-2006, 06:55 AM
In PHP you can use the strpos or stripos functions to check if one string contains another. stripos is only available in PHP 5, so if you want a case-insensitive search, first use strtoupper on both strings and then use strpos, here's some code for you:


$nick = "My nick name is beagle";
$username = "beagle";

//Needs php 5 for this function! CASE-INSENSITIVE
if (stripos($username, $nick) !== false)
{
echo "The nick contains the username."
}
else
{
echo "the nick doesn't contain the username."
}

//PHP4 case-insensitive
if (strpos(strtoupper($username), strtoupper($nick)) !== false)
{
echo "The nick contains the username."
}
else
{
echo "the nick doesn't contain the username."
}


Of course, if you want case-sensitive matching, just drop the strtoupper calls and use strpos.

CFMaBiSmAd
11-02-2006, 07:09 AM
If I understand you correctly, set the $person variable prior to the query string and for an exact match, change your query -
// change this -
$query="SELECT * FROM saved_info";

// to this -
$query="SELECT * FROM saved_info WHERE nickname='$person'";For a wildcard match -
// change this -
$query="SELECT * FROM saved_info";

// to this -
$query="SELECT * FROM saved_info WHERE nickname LIKE '%$person%'";