Matching my form string with condition in database in php? - php

This is coming from my form field :
$subject="physics with maths";
This is in my database :
$keywordsindatabse="(physics && electronics) || (electronics & communication) || (electronics and communication)";
On submission of form I want to match the condition $keywordsindatabse with $subject.
Any Ideas?
Any help will be appreciated.
Code:
<form id="myform" name="myform">
<select name="sselect" id="itmn">
<option value="">Select</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
</select>
<input type='text' name='gmajorsub' id=""" value="" onblur="chkdegree(document.getElementById('itmn').value,this.value);">
</form>
<script>
function chkdegree(item_id,keyword)
{
$.ajax({
type: "GET",
url: "degree_match.php",
dataType: 'html',
data: {item_id : item_id,keyword : keyword},
success: function(data){
if(data=="0")
{
alert("Dear Applicant, You are not allowed to register.You Subject not matching our essential qualification requirements.");
document.getElementById("gmajorsub").value="";
document.getElementById("gmajorsub").focus();
return false;
}
}
});
}
</script>
degree_match.php:
<?php
include("../../lib/dbc/dbConnection.php");
require('../../lib/dbc/commonFunc.php');
require('../../lib/dbc/dbHandler.class.php');
$dbObject = new dbHandler();
$dbObject->connect();
$query="select * from advt_110_post_details where recNo='".$_REQUEST['item_id']."'";
$result=mysql_query($query);
$num=mysql_fetch_array($result);
$keyword=strtolower($_REQUEST['keyword']);
$degree=$num['subject_keywords'];
$degree1=explode("|",$degree);
$max = array(null, 0); // category, occurences
/*foreach($degree1 as $k => $v) {
$replaced = str_replace($v, '##########', $keyword);
preg_match_all('/##########/i', $replaced, $matches);
if(count($matches[0]) > $max[1]) {
$max[0] = $k;
$max[1] = count($matches[0]);
}
}
if($max[1]>=count($degree1))
{
echo"1";
}
else{
echo"0";
}
*/
/*foreach($degree1 as $k => $v) {
if ( strstr( $membership, "member" ) )
{
}
}
*/
?>

Note: You're code is subject ot SQL injection. Look at using PDO prepared statements or mySQLi prepared statements. At the very least, wrap string input into hte database in mysql_real_escape_string.
Looking at your code, you're getting items from a database and then filtering. I'm assuming mySQL.
You might be better doing this withing the database end. Check out "full text search". This only works with MyISAM tables, so change that if needed. Then add a FullText index to the table on the 'subject_keywords' and you'll need to set up a boolean seaerch using full text. Details on the boolean search are here.
(Failing that, Rishi's answer above has introduced the loops you need - that was missing from your attempt.)

As far as i understood from your post, the below code might help..
$subject="physics with maths";
$keywordsindatabse="(physics && electronics) ||
(electronics & communication) ||
(electronics and communication)";
$pieces = explode(" ", $subject);
$piecesDB = explode("||", $keywordsindatabse);
$subsDBv=array();
foreach($piecesDB as $key=>$subsDB){
$subsDBv[$key] = str_replace(array("(",")"),"",explode(" ", $subsDB));
}
foreach($subsDBv as $subslvd){
foreach($subslvd as $subslv){
$ao = next($subslvd);
foreach($pieces as $subs){
if((strpos($subslv,$subs) !== false) AND (strpos($ao,$subs) !== false)){
echo "Match found..<br />";
}
else{
echo "Sorry, no match found..<br />";
}
}
}
}

Related

Showing multiple PHP tables with different SQL statements suggestions

I'm working on a school project and i need some suggestions. It is a HTML/PHP/SQL project where users can give their input about gaming experiences. As an admin you have to be able to see the names of the users that chose for certain gaming categories. This needs to be showed in tables using PHP and MySQL.
I have now finished this page, it is working like a charm and i can see all the users input. But the problem is that i have about 600 lines of code since i have 12 different div's with MySQL statements and tables.
Currently my code is seperated into 3 parts, the html select dropdown, 12 different div's with query's that generates tables, and jquery to show / hide the tables based on the select dropdown
I am hoping someone could give me a suggestion on how to shorten my code, since 600 lines of code is crazy and i am aware that it could be shorter but i just can't figure out how.
The HTML Select:
<select name="type" id="type" style="margin-left:57px; width:153px;">
<option name="select" value="select">Selecteren..</option>
<optgroup label="Hoe spelen mensen?">
<option name="alleen" value="alleen">Meestal alleen</option>
<option name="fysiek" value="fysiek">Meestal samen fysiek</option>
<option name="online" value="online">Meestal samen online</option>
</optgroup>
<optgroup label="Categorieën bordspellen">
<option name="alleen" value="kaartspellen">Kaartspellen</option>
<option name="fysiek" value="strategische">Strategische bordspellen</option>
<option name="online" value="fantasy">Fantasy bordspellen</option>
<option name="online" value="klassiek">Klassieke gezelschapspellen</option>
</optgroup>
<optgroup label="Categorieën computergames">
<option name="alleen" value="sport">Sport games</option>
<option name="fysiek" value="adventure">Adventure games</option>
<option name="online" value="war">War games</option>
<option name="online" value="strategischegames">Strategische games</option>
</optgroup>
<optgroup label="Gebruikers">
<option name="alle" value="alle">Alle gebruikers</option>
</optgroup>
1 div with a table (as example, since there are 12 different of these)
<div class="row" id="wargames">
<?php
$war = "SELECT * FROM form where categorie = 'wargames'";
$querywar = mysqli_query($conn, $war);
if (!$querywar) {
die('SQL Error: ' . mysqli_error($conn));
}
?>
<table class="data-table">
<caption class="title">Deze mensen spelen meestal de categorie War
games</caption>
<thead>
<tr>
<th>Naam</th>
<th>Woonplaats</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_array($querywar)) {
echo '<tr>
<td style="text-align:center">' . $row['naam'] . '</td>
<td style="text-align:center">' . $row['woonplaats'] .
'</td>
<td style="text-align:center">' . $row['email'] . '</td>
</tr>';
}
?>
</tbody>
</table>
my jquery
$(function() {
$('#row_dim').hide();
$('#type').change(function(){
if($('#type').val() == 'alleen') {
$('#alleen').show();
} else {
$('#alleen').hide();
}
if($('#type').val() == 'fysiek') {
$('#fysiek').show();
} else {
$('#fysiek').hide();
}
if($('#type').val() == 'online') {
$('#online').show();
} else {
$('#online').hide();
}
if($('#type').val() == 'kaartspellen') {
$('#kaartspellen').show();
} else {
$('#kaartspellen').hide();
}
if($('#type').val() == 'strategische') {
$('#strategische').show();
} else {
$('#strategische').hide();
}
if($('#type').val() == 'fantasy') {
$('#fantasy').show();
} else {
$('#fantasy').hide();
}
if($('#type').val() == 'klassiek') {
$('#klassiek').show();
} else {
$('#klassiek').hide();
}
if($('#type').val() == 'sport') {
$('#sportgames').show();
} else {
$('#sportgames').hide();
}
if($('#type').val() == 'adventure') {
$('#adventure').show();
} else {
$('#adventure').hide();
}
if($('#type').val() == 'war') {
$('#wargames').show();
} else {
$('#wargames').hide();
}
if($('#type').val() == 'strategischegames') {
$('#strategischegames').show();
} else {
$('#strategischegames').hide();
}
if($('#type').val() == 'select') {
$('#selected').show();
} else {
$('#selected').hide();
}
if($('#type').val() == 'alle') {
$('#gebruikers').show();
} else {
$('#gebruikers').hide();
}
});
$( document ).ready(function() {
if($("#type").attr("selectedIndex") !== 0) {
$('#selected').show();
$('#strategischegames').hide();
$('#wargames').hide();
$('#adventure').hide();
$('#sportgames').hide();
$('#klassiek').hide();
$('#fantasy').hide();
$('#strategische').hide();
$('#kaartspellen').hide();
$('#online').hide();
$('#fysiek').hide();
$('#alleen').hide();
$('#gebruikers').hide();
}
});
});
One think to shorten would be $('#type').change(...) handler:
$('#type').change(function () {
const map = {
'alleen': 'alleen',
'fysiek': 'fysiek',
'online': 'online',
'kaartspellen': 'kaartspellen',
'strategische': 'strategische',
'fantasy': 'fantasy',
'klassiek': 'klassiek',
'sport': 'sportgames',
'adventure': 'adventure',
'war': 'wargames',
'strategischegames': 'strategischegames',
'select': 'selected',
'alle': '#gebruikers',
};
Object.keys(map).forEach(key => {
if ($('#type').val() == key) {
$('#' + map[key]).show();
} else {
$('#' + map[key]).hide();
}
});
});
As you can see, I declaratively map values to IDs, then process all of them in a cycle.
Next step would be generalizing that show/hide functionality:
function show(type) {
const map = {
'alleen': 'alleen',
'fysiek': 'fysiek',
'online': 'online',
'kaartspellen': 'kaartspellen',
'strategische': 'strategische',
'fantasy': 'fantasy',
'klassiek': 'klassiek',
'sport': 'sportgames',
'adventure': 'adventure',
'war': 'wargames',
'strategischegames': 'strategischegames',
'select': 'selected',
'alle': '#gebruikers',
};
Object.keys(map).forEach(key => {
if (type == key) {
$('#' + map[key]).show();
} else {
$('#' + map[key]).hide();
}
});
}
With that function, your change and ready event handlers can be shortened like this:
$('#type').change(function () {
show($('#type').val());
});
$(document).ready(function () {
if ($("#type").attr("selectedIndex") !== 0) {
show('select');
}
});
Re PHP part, I see only one piece, so, I don't know what is common with others, but as a general rule:
Note common things
Note differences, e.g. different values passed to same pieces of code
Move differences to variables before common things
Now you can easily transform piece of code into a function -- just make a function with things from p.3 as parameters
Call that function as many times as needed, or maybe in a loop -- this is exactly what I did with your JS code at the top of my answer
And, of course, your HTML screams "extract data structure from me and format it into tags". In other words, separate data from presentation, e.g.:
<?php
$data = [
[
'value' => 'select',
'text' => 'Selecteren..',
'childrenCaption' => 'Hoe spelen mensen?',
'children' => [
'alleen' => 'Meestal alleen',
'fysiek' => 'Meestal samen fysiek',
'online' => 'Meestal samen online',
],
],
];
function formatOptions($data) {
foreach ($data as $section) {
echo "<option name=\"$section[value]\" value=\"$section[value]\">$section[text]</option>\n";
echo "<optgroup label=\"$section[childrenCaption]\">\n";
foreach ($section['children'] as $value => $text) {
echo " <option name=\"$value\" value=\"$value\">$text</option>\n";
}
echo "</optgroup>\n";
}
}
formatOptions($data);
And sample output looks like this:
<option name="select" value="select">Selecteren..</option>
<optgroup label="Hoe spelen mensen?">
<option name="alleen" value="alleen">Meestal alleen</option>
<option name="fysiek" value="fysiek">Meestal samen fysiek</option>
<option name="online" value="online">Meestal samen online</option>
</optgroup>
As you can see, modifying $data variable is much easier than maintaining that much of HTML code.
There is more room from improvement, but this is a good start, I guess.

PHP multiple select form how to use: if (taskOption[0] is selected)

HTML:
<select name="taskOption[]" multiple>
<option>first<br /></option>
<option>second<br /></option>
<option>third</ option>
</select>
PHP:
<?php
foreach ($_GET['taskOption'] as $selectedOption){
echo "lesson:".$selectedOption."<br>";}
?>
This php code simply prints the selected options.
How can i separately do something if an option is selected ? for example
if (taskOption[0] is selected){
$x="1";
if (taskOption[1] is selected){
$y="1";
What i have tried with partial success so far is this:
$options = array("", "", "");
foreach ($_GET['taskOption'] as $selectedOption)
echo "".$selectedOption."<br>";
if($selectedOption == 'first'){
$options[0] = "11";
echo $options[0];
}
elseif($selectedOption == 'second'){
$options[1] = "22";
echo $options[1];
}
elseif($selectedOption == 'third'){
$options[2] = "33";
echo $options[2];
}
but i still have problem when i choose 2+ option..
(it only echo the last option)
You should add values to the options in the select tag first, so you can easy identify each one.
<select name="taskOption[]" multiple>
<option value="one">first<br /></option>
<option value="two">second<br /></option>
<option value="three">third</ option>
</select>
After it, you should remove the "elseif" and simply do ifs for all
$options = array("", "", "");
foreach ($_GET['taskOption'] as $selectedOption)
echo "".$selectedOption."<br>";
if($selectedOption == 'one'){
$options[0] = "11";
echo $options[0];
}
if($selectedOption == 'two'){
$options[1] = "22";
echo $options[1];
}
if($selectedOption == 'three'){
$options[2] = "33";
echo $options[2];
}
Im mantaining your code but it can be improveed a lot. Im not sure why are you adding the values to an array ($options).
You should add the value attributes to your option elements
<option value="first">first<br /></option>
<option value="second">second<br /></option>
<option value="last">third</option>
You are not wrapping your logic inside of the foreach.
foreach ($_GET['taskOption'] as $selectedOption){
echo "selected: ".$selectedOption;
if($selectedOption === 'first'){
$options[0] = "11";
echo $options[0]."<br>";
}
elseif($selectedOption ==='second'){
$options[1] = "22";
echo $options[1]."<br>";
}
elseif($selectedOption ==='third'){
$options[2] = "33";
echo $options[2]."<br>";
}
echo"end";
}
You need to put the swirly brackets around your logic to make sure everything beneath runs.

multiple attribute form output

i have had made a number of changes to the below program but am really stumped on my last task- i need a multiple attribute to pull multiple 'teams' data (points,goal difference etc) with php form. i can get single teams to work but not multiple. see screen attached and heres my code below.
![enter image description here][1]
<html>
<head>
<style>
.red {color: red}
</style>
<title>Table</title>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" ){
$tablesPage = "http://www.bbc.com/sport/football/tables";
if(!empty($_POST["team"])){
$teamData= getTeamData($_POST["team"] , $tablesPage); //get associative array of team data
if(!empty($_POST["data"]) && $_POST["data"] == "results"){
echo getResults($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "position"){
echo getPosition($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "two points for a win"){
echo getPoints($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "goal difference"){
echo getDifference($teamData);
}
}
}
function getPosition($teamData){
/*This function takes an array of team data and returns a string containing the name of the team and its position in the leauge */
return "Team ". $teamData["team"] ." are currently number " . $teamData["position"] . " in the league " ;
}
function getResults($teamData){
/*This function takes an array of team data and returns a string containing the results of the team */
return $teamData["team"] ." have won " . $teamData["won"] . " , drawn " . $teamData["drew"] . " , and lost " . $teamData["lost"] . " games to date " ;
}
function getPoints($teamData){
/*This function takes an array of team data and returns a string containing the points and calculates the old two points system */
$oldpoints = $teamData["won"] * 2 + $teamData["drew"];
return $teamData["team"] ." have " . $teamData["points"] . " points under the current system " . "<br> Under two points for a win they would have " . $oldpoints ;
}
function getDifference($teamData){
/*This function takes an array of team data and returns a string containing the name of the team and its goal difference in the leauge */
return $teamData["team"] ." goal difference is " . $teamData["difference"] . " at the moment " ;
}
function getTeamData($team, $tablesPage){
/* This function takes a webpage url and the name of a team as two string arguments. e.g. getTeam(""http://www.bbc.com/sport/football/tables", "liverpool")
It returns an array of data about the team.
You don't need to understand what this function does just that it returns an array which contains keya and values. The values map to the following keys:
"position", "team", "played", "won", "drew", "lost", "for", "against", "difference", "points"
*/
$html = new DOMDocument();
#$html->loadHtmlFile($tablesPage); //use DOM
#$xpath = new DOMXPath($html); //use XPath
$items = $xpath->query('//td/a[text()="' . $team . '"]/../..'); //get the relevant table row
$values[] = array();
foreach($items as $node){
foreach($node->childNodes as $child) {
if($child->nodeType == 1) array_push($values, $child->nodeValue); //KLUDGE
}
}
$values[2] = substr($values[2], -1); //KLUDGE
$values = array_slice( $values, 2, count($values)-4); //KLUDGE
$keys = array("position", "team", "played", "won", "drew", "lost", "for", "against", "difference", "points");
return array_combine($keys, $values);
}
?>
<br>
Select a team and a data item about that team
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<select name="team[]" multiple="multiple" size="3">
<option value=""></option>
<option value="Everton">Everton</option>
<option value="Arsenal">Arsenal</option>
<option value="Chelsea">Chelsea</option>
<option value="Man Utd">Man Utd</option>
<option value="Liverpool">Liverpool</option>
</select>
<select name="data">
<option value="position">position</option>
<option value="results">results</option>
<option value="two points for a win">two points for a win</option>
<option value="goal difference">goal difference</option>
<select>
<input type="submit" value="Get Data"></input>
</select>
</form>
</body>
</html>
Here is the code that you need to replace. I have left the 'debug' code in so you can see what is happening. just delete it when you are done.
Removed debug code.
Tested code: PHP 5.3.18 on windows xp.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" ){
$tablesPage = "http://www.bbc.com/sport/football/tables";
if(!empty($_POST["team"])){
// remember that the $_POST['team'] is an array of team names
foreach($_POST['team'] as $currentTeam) {
$teamData= getTeamData($currentTeam , $tablesPage); //get associative array of team data
if(!empty($_POST["data"]) && $_POST["data"] == "results"){
echo getResults($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "position"){
echo getPosition($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "two points for a win"){
echo getPoints($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "goal difference"){
echo getDifference($teamData);
}
echo '<br />';
} // end currentTeam
}
}

Interactive Form depending on Select List not working

So I am trying to make this clip submission form interactive in the following way:
I want the second Select list choices to change according to which city is selected in the first select list.
Here is my script function code:
<script>
function spotListChange(s1, s2) {
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if(s1.value == ""){
var optionArray = ["|"];
}
<?php
while ($cityList = $cityListDB->fetch()) {
$city = $cityList['city'];
$spotList = $db->query("SELECT * FROM spots WHERE city='$city' ORDER BY name");
?>
else if(s1.value == "<?php echo $city; ?>"){
var optionArray = ["|"
<?php
while ($spot = $spotList->fetch()) {
echo ", \"" . $spot['city'] . "|" . $spot['city'] . "\"";
}
?>
];
}
<?php
}
?>
for(var option in optionArray){
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
}
</script>
Here is the part of the form with the two select lists. (I'll get rid of most city options available just to make the code shorter)
<select id="city" name="city" style="margin-left: 135px;" onChange="spotListChange('city', 'spotSelectList')" required>
<option value="" selected="selected">Ville...</option>
<option value="Albanel">Albanel</option>
<option value="Alma">Alma</option>
<option value="La Doré">La Doré</option>
<option value="Saint-Félicien">Saint-Félicien</option>
<option value="Mashteuiatsh">Mashteuiatsh</option>
</select><br />
<select id="spotSelectList" name="spot" style="margin-left: 135px;">
</select>
If I change the PHP inside the else if by fix/text values, it works fine, so the issue must be there, but I don't get where the issue is.
Do yourself a favor and use jquery for it, it makes your code more simple and is a plenty of tutorial out there.
I recomend you make a json response from php to an ajax call from jquery (javascript).
Can you see this as reference:http://simpleweb.github.io/jquery-dependent-selects/
also this:http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html
Hope this helps you.

Using select and option and remembering after POST

Using select and option HTML tags, I pass information through using $_POST.
When reloading the page however, the select resets back to the original values.
I am looking to get it to remember what has been passed through.
<?php
foreach($data as $value => $title)
{
foreach($ag as $first)
{
foreach($af as $second)
{
echo"<option value='$value-$first-$second'>$title - $first - $second</option>";
}
}
}
?>
As you can see, I use 3 foreach loops to populate whats in it.
How can I achieve my selection being remembered?
Thanks for reading.
You'll need to use the name of your select field in place of "your_select_field_name" in my change below:
<?php
foreach($data as $value => $title)
{
foreach($ag as $first)
{
foreach($af as $second)
{
echo "<option value='$value-$first-$second'";
if( $_POST['your_select_field_name'] == "$value-$first-$second" ) {
echo ' selected="selected"';
}
echo ">$title - $first - $second</option>";
}
}
}
?>
The output for the selected option on the new page needs to look like:
<option value='foo' selected>...<option>
HTML does not have memory. The item that's selected by default in a <select> form element is the one with the selected attribute (or the first one if none). Simply use the information contained in $_POST to generate the appropriate markup:
<select name="foo">
<option value="v1">Label 1</option>
<option value="v2">Label 2</option>
<option value="v2" selected="selected">Label 3</option>
<option value="v4">Label 4</option>
</select>
You need to set the selected tag on the correct option. Something like this:
<?php
$postedValue = $_POST['select_name'];
foreach($data as $value => $title)
{
foreach($ag as $first)
{
foreach($af as $second)
{
$computedValue = $value . '-' . $first . '-'. $second;
if ( $computedValue == $postedValue) {
$selected = "selected";
} else {
$selected = ''
}
echo "<option value='$computedValue' $selected>$title - $first - $second</option>";
}
}
}
?>
It could probably be written cleaner but this is the general idea.

Categories