PDA

View Full Version : PHP variables inside mySQL stmt


dcparham
08-31-2009, 06:52 PM
please note i have this working in one instance, and is not working in another very similar statement - frustrating! i will post working code first, then outline the problem with its own code:


...[working]...
$staffName = $_GET['staffName']; //example: Parham, David [me]
...
$sql1 = "SELECT DISTINCT(staffName),
position,
dateTime,
evaluatorName,
q1Extent,
q2Attitude,
q3Quality,
q4Comments from $tableName WHERE staffName='".$staffName."' ORDER BY staffName";
$resultSet1 = $dbObj->query($sql1);
//THIS WORKS FINE - takes $staffName, compares to table field "staffName"

note: works using $var name in the mySQL stmt.

the problem is where a similar mySQL stmt uses a variable and it gives no output. yet the same stmt when using literal values, works fine. i echo the literal values out to make sure they are in the table, and they are. so using them as literals works fine; yet when the SAME varname that echoed the literal is used in the mySQL stmt, it produces nothing:


echo $x."-".$staffFirst."-".$staffLast."<br />"; //output copied from screen[quotes added]: "raleigh-Parham-David"
$sql1 = "SELECT dateOfHire FROM $x WHERE LastName='".$staffLast."' AND FirstName='".$staffFirst."';";
$sql1 = "SELECT dateOfHire FROM `raleigh` WHERE FirstName='David' and LastName='Parham'";
//note: the first stmt does not work, the 2nd with literals does.
$resultSet1 = $dbObj->query($sql1);
while($row = mysql_fetch_array($resultSet1, MYSQL_ASSOC))

{//while BEGIN
$dateOfHire=$row['dateOfHire'];
echo $dateOfHire; //output copied from screen using literals in mySQL stmt[quotes added]:"2002-11-12"
}


also, this shows that mySQL stmt works in phpMyAdmin:

SELECT dateOfHire
FROM raleigh
WHERE FirstName = 'David'
AND LastName = 'Parham'
LIMIT 0 , 30

mySQL output is: dateOfHire "original date of hire": 2002-11-12.

so the problem is, even though the mySQL stmt works with the vars spelled out via literals, when using the vars themselves in the mySQL, does not work - no error, just produces nothing. any clues?? thx for your time and effort - meeting in 90 minutes to show the "working" model:?

dcparham
08-31-2009, 08:04 PM
i had not posted all my code, i apologize - i did not think it was relevant; the original variable $staffName has "Parham, David" with last then first. then i split the field into 2 variables, and proceeded to use in reverse order, trying to search for last name using first, and first name using last:


list($staffLast, $staffFirst) = split(',',$staffName);
$staffFirst = trim($staffFirst);
$staffLast = trim($staffLast);
//### ok, so first=LAST name; last=FIRST name ###//

then i proceed to search with the vars switched in wrong position:

$sql1 = "SELECT dateOfHire FROM $x WHERE LastName='".$staffLast."' AND FirstName='".$staffFirst."';";

you see? staffLast really has FIRST, and staffFirst has LAST.

sorry for "dud."