I’m trying to get two different numbers from two different text files, put them into one variable, and compare it to the MYSQL array. My problem is that when I define three variables like:
$num = 42;
$whichPlaylist = 2;
$joint = "$whichPlaylist $num"
and test with the array, it works. However, if I take the 2 and 42 from the text file, it doesn’t work. I’ve tried using $trim but that doesn’t seem to fix it. Why does it work when I define my variables but not work when I get them from the text file? They have the exact same thing (text file has a new line though).
Here’s my code:
//Connect to DB
$config = array(
'host' => 'localhost',
'username' => '******',
'password' => '******',
'dbname' => '******'
);
$db = new PDO('mysql:host='.$config['host'].';dbname='.$config['dbname'],$config['username'],$config['password']);
$query = $db->query("SELECT `recentlyplayed`.`numplayed`, `recentlyplayed`.`id` FROM `recentlyplayed`");
//Put numbers from text files into variables
$num = file_get_contents('/home/*****/num.txt'); // has the value "42" with new line
$whichPlaylist = file_get_contents('/home/*****/whichplaylist.txt'); // has the value "2" with newline
$playlist3_num = file_get_contents('/home/*****/playlist3_num.txt');
//$whichPlaylist = 2;
//$num = 42;
$joint = "$whichPlaylist $num";
$trimmed = trim("$joint");
echo $trimmed;
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
if (in_array($trimmed, $row)){
echo " In Array!"; //This does NOT work, but if I use the self-defined variables $whichPlaylist and $num (and comment out file_get_content variables) it DOES work.
}
}
You’ll need to trim the variables from file_get_contents before you join them; otherwise the newline will be in the resulting string. Trimming only takes whitespace from the beginning and end of the string and this would put it in the middle.