Very new to PHP and ran into some trouble and was wondering if anyone could help. I'm having problems with an array of names that are looked up in a database. When I use just the array of names it gets processed correctly. When I try and read a file of those same names only the last name gets displayed. My question is how can I get all names displayed for the file array?
Please see examples and code below. Thanks for your time.
//This works -- Sample 1
$x = array("joe", "paul", "tom");
//This does not -- Sample 2
$x = file("name.txt"); //Same names from the array above are in this file
Here is the full code below.
<html>
<head>
<title>Name Check</title>
</head>
<body>
<?php
$con = mysql_connect("localhost", "xxxxxxxx", "xxxxxxxx");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xxxxxxxxxx", $c开发者_StackOverflow中文版on);
// $x=array("joe", "paul", "tom"); //displays all names correctly in Sample 1 below
$x = file("name.txt"); // only displays the last name in the file. Sample 2 below
foreach ($x as $test) {
$result = mysql_query("SELECT * FROM categories WHERE Name='$test' Limit 0, 1");
while ($row = mysql_fetch_array($result)) {
echo $row['Name'];
echo " " . $row['Sport'];
echo "<br />";
}
}
?>
</body>
</html>
Sample 1 output
joe basketball
paul basketball
tom baseball
Sample 2 output
tom baseball
Here is the contents of name.txt, that was requested. Thanks!
joe
paul
tom
file()
leaves in the newline character at the end of each line, which only the last one lacks. You could use rtrim($test)
to fix this.
You should also be escaping the name in case it contains characters like '
, so a complete solution would be (just before the query):
$test = mysql_real_escape_string(rtrim($test));
精彩评论