Quantcast
Channel: PHP Freaks: PHP Help
Viewing all articles
Browse latest Browse all 13200

My 'Foreach' SQL query build is not working

$
0
0

So, I am trying to build a SQL query dynamically from user input. The mysql_real_escape_string seems to be the problem. When I reun this I get the 'No fields entered' echo message. Can someone help me understand what's wrong here?

$FName = $_POST['fname'];
$LName = $_POST['lname'];
$Email = $_POST['email'];

$Organization = $_POST['organization'];
$Supervisor = $_POST['supervisor'];
$SuperEmail = $_POST['superemail'];
//$Class = $_POST['courseID'];
//$PGrade = $_POST['gs'];
//$OccSeries = $_POST['occseries'];
//$MilGrade = $_POST['milgrade'];
//$MilSpec = $_POST['milspec'];
$MajCom = $_POST['majcom'];

//$LName = "FILLER";
echo "Here you are: " . $LName . "<br />" . $FName . "<br />";



//$tsql = "select ID,CourseID,lastname,firstname,email,paygrade,organization,supervisor,superemail,milgrade,milspec,majcom from Registrations";

// List of possible form fields. (The "name" attributes of the <input> elements.)
$expectedKeys = array($LName, $FName, $Email, $Organization, $Supervisor, $SuperEmail, $MajCom);

// A list to be populated with the "key=value" pairs you want in your WHERE clause.
$fields = array();

// Loop through the keys and add the field to the list if needed.
foreach ($expectedKeys as $key)
{
    if (!empty($_POST[$key]))
    {
        $fields[] = sprintf("`%s` = '%s'", $key, mysql_real_escape_string($_POST[$key]));
    }
}

// Make sure there were actually some fields you can use.
if (count($fields) > 0)
{
    // Construct the WHERE clause by gluing the fields together with a " AND " separator.
    $whereClause = "WHERE " . implode(" AND ", $fields);

    // And then create the SQL query itself.
    $sql = "select ID,CourseID,lastname,firstname,email,paygrade,organization,supervisor,superemail,milgrade,milspec,majcom from Registrations " . $whereClause;
	
	echo $sql;
}
else
{
    echo "No fields entered!";
}

Viewing all articles
Browse latest Browse all 13200

Trending Articles