Creating a table search function with multiple variable PHP MySQL - php

I am trying to create a search function with multiple variables. Basically I have a standard style form, and each element has a name. Those names on submit are retrieved via POST then the search query is conducted. I have posted my code and I know I have probably gone about this a terrible way but I am looking for direction on how to make it suitable. Still very new to PHP so advice on better ways to structure this that I can then go and learn/implement would be appeciated. Currently it does search via the first variable $search but I'm not sure how to implement the rest. The user should be able to input 1 or multiple variables then the search is conducted. At this point it is only searching one table and I would like it to search multiple tables long term, all the columns in the different tables have the same name, just different data. Any guidance appreciated here. Cheers.
//define variables to be used
$table = 'aecm';
$search = #$_POST['search'];
$status = #$_POST['status'];
$repair = #$_POST['repair'];
$upgrade = #$_POST['um'];
$pm = #$_POST['pm'];
$nofault = #$_POST['nf'];
//Connect to database
include '/../connect.php';
//conduct a search
$result = mysql_query("SELECT * FROM $table
WHERE (part LIKE '%$search%')
OR
(serial LIKE '%$search%')
OR
(mac LIKE '%$search%')
OR
(ip LIKE '%$search%')
OR
(status LIKE '%$search%')
ORDER BY part ASC");
if (!$result) {
die("Query to show fields from table failed");
}
Added the form code showing the variables.
echo '<form ENCTYPE=multipart/form-data form name=benchsearch
action=benchsearchresults.php method=post>';
//search selection
echo '<table>';
echo '<tr><td>Standard Search </td>';
echo "<td><input type=text maxlength=30 name=search /></td>";
echo '<tr><td>Search Status of Equipment </td>';
echo "<td><select name=status>";
echo "<option> </option>";
echo "<option> SERVICEABLE </option>";
echo "<option> UNSERVICEABLE </option>";
echo "<option> BEYOND ECONOMICAL REPAIR </option></select></td>";
echo "<tr><td>Search Type of Repair :</td>";
echo "<tr><td>Repair </td>";
echo "<td><input type=checkbox name=repair value=rep /></td>";
echo "<tr><td>Updrade/Modification </td>";
echo "<td><input type=checkbox name=upgrade value=um /></td>";
echo "<tr><td>Preventitive Maintenance Check </td>";
echo "<td><input type=checkbox name=pm value=pm /></td>";
echo "<tr><td>No Fault Found </td>";
echo "<td><input type=checkbox name=nofault value=nf /></td>";
echo "</table>";
echo '<center><input type="submit" class="button" id="submit" value="Search"/> </center>';
echo "</form>";
My tables are as follows
Table aecm, aicm etc
Columns - part, serial, mac, ip, status
Table aecmhis, aicmhis etc
Columns - serial, repair, upgrade, pm, nofault
I want to use a form as above (or similair) to conduct a search and show results from all tables. The serial number is common between aecm-aecmhis and aicm-aicmhis etc. Status is only 1 of 3 options and the repair, upgrade, pm, nofault columns are either empty or have yes in them. Just looking for the best way to go about this.

why not take table as an argument too i mean use post to let the user specify the table they want to search the rest of the code can remain the same. I am not very sure i understood what you really needed so let me know if this is not what u wanted

If you want to be able to query multiple tables with multiple query terms on each search, sql my not be the best solution. Something like Apache Lucene may be a place to start looking. I know Zend Framework has a component that implements an indexed Lucene search engine and may be a place to start (you can use just the components you want with ZF).
P.S. This is not simple!
Good Luck.

Related

PHP - sending a complete row with one checkbox and POST

I have a table with rows that are in the form:
ID, Name, First Name, IntA, IntB, IntC, ...
The last columns are textfields.
I want to select multiple rows with a Checkbox and send the ID and the recorded integers with POST to another PHP-File.
This is my code-example (with a little bit German in it):
echo "<td><input type='checkbox' name='auswahl[]' value='$daten[0]'></td>";
echo "<td>" . $daten['ID'] . "</td>";
echo "<td><input type='number' name='Schr' value='".$punkte['PktSchr']."'></td>";
echo "<td><input type='number' name='Mdl' value='".$punkte['PktMdl']."'></td>";
So in the other PHP-File I want to SQL for all checked rows like this (in a Loop):
$Eintraege = $_POST['auswahl'];
$Schr = $_POST['Schr'];
$Mdl = $_POST['Mdl'];
foreach ($Eintraege as $i){
$sql = "INSERT INTO aufnahme (IDSchueler, PktSchr, PktMdl) Values ('$i', '$Schr', '$Mdl')";
}
My problem is this: $Eintraege contains only the IDs of the selected rows (because of value='$daten[0]').
$Schr and $Mdl contains the values of the textfields of the last row (doesn't matter, wich rows are selected).
So I tried to set value='$daten' and use it lika an array, but then I get an Exception.
I think I have to change value='$daten[0]', but don't know how.
Thanks for your help!
Change two other names to array type too and you will get all values.
So do like below:-
echo "<td><input type='number' name='Schr[]' value='".$punkte['PktSchr']."'></td>";
echo "<td><input type='number' name='Mdl[]' value='".$punkte['PktMdl']."'></td>";
And then you can do like below:-
foreach ($Eintraege as $k=> $i){
$sql = "INSERT INTO aufnahme (IDSchueler, PktSchr, PktMdl) Values ('$i', '$Schr[$k]', '$Mdl[$k]')";
}
As #Alive-to-Die mentioned, turn the names into arrays.
<input type='checkbox' name='auswahl[]' value='$daten[0]'>
This itself doesn't look good. Consider making it
<input type='checkbox' name='auswahl[]' value='{$daten[0]}'>
or
<input type='checkbox' name='auswahl[]' value='".$daten[0]."'>
These are two proper ways to use variables inside strings.

Using a option to hold a value in php

Using php I have manage to search and display the data i need. Now I wish for the user to be able to select a option from a drop down menu and click update. Now when I try this it doesn't update the data for some reason. Are you able to notice any errors in the code below? I have included small bits of relevant code from the php file. I'm using the 'value=1' so that when I click update the query updates using the number rather than the text as i want to update a different field than the output field. Any ideas?
if (isset($_POST['update'])) { //once the update is click this updates the gametable with the adjusted information
$updatequery = "
UPDATE
GameTable
SET
GameID='$_POST[gameid]',
GameName='$_POST[gamename]',
PubID='$_POST[Publisher]',
TimePeriodID='$_POST[TimePeriod]',
SettingID='$_POST[Setting]', //the field i want to update using the value of the named select option
MoodID='$_POST[Mood]',
GameWeaponID='$_POST[Weapon]',
GameCameraAngleID='$_POST[CameraAngle]',
GamePlayerTypeID='$_POST[PlayerType]',
GameDescription='$_POST[Description]'
WHERE
GameID='$_POST[gameid]'";
mysqli_query($dbcon, $updatequery);
echo "Record successfully updated";
};
//query that fetches data from a database and outputs.
while ($row5 = mysqli_fetch_array($result5)) {
echo "<tr> <th> Setting ID</th> </tr>";
echo "<td><select class='text-black input-button-rounded' name='Setting'>";
//the output is a different field to the one I want to update so that's why I want to use the value.
echo "<option disabled selected>" . $row5['SettingName'] . "</option>";
echo "<option class='text-black' type='text' value=1>Western</option> ";
echo "<option class='text-black' type='text' value=2>Space</option>";
echo "<option class='text-black' type='text' value=3>City</option>";
echo "<option class='text-black' type='text' value=4>Sea</option>";
echo "<option class='text-black' type='text' value=5>Apocalypse</option>";
echo "</select></td><br>";
//update button
echo "<td>" . "<input class=text-black input-button-rounded type=submit name=update value=Update" . " </td>";
I think your problem is that your select and submit button need to be wrapped in a <form> element, so that when the "Update" button is clicked, it POSTs the Setting data as well.
A few other things to note:
All the quotes for the values of the HTML attributes are missing from the line which has your button code. Also the quotes for the array keys of $_POST in your SQL statement e.g. you wrote$_POST[Mood] rather than $_POST['Mood'] Why is that?
You don't need type="text" for the option tags.
If you really want to build a secure website/app you shouldn't be using raw SQL statements. Rather, make use of either PDO or MySQLi prepared statements.

Need help creating a second drop down box of options based on what a user selects in the first drop down box

I need to have a selection box display options that are based off of the selection from the drop down box right above it. Once the user selects the Car Make, then I want the Car Models of the car make to be options to be selected.
I have been able to get the car makes options to be displayed from my mysql data base, but now I need the car models of only that make. My data base has two collumns, one for the Make and one for the Model.
The top section of PHP is the way i get the make from a seperate database, and the bottom is my attempt to get the model from a database with makes and models of all cars, but it displays hundreds of models, instead of just the few I want. I heard that AJAX or javascript can automatically upload the results, which would be nice. Any help is great. thanks!
</div>
<?php
mysql_connect('localhost', '*****', '******');
mysql_select_db('*************');
$sql = "SELECT Make FROM CarMakes";
$result = mysql_query($sql);
echo "<select name='carmake3'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['Make'] . "'>" . $row['Make'] . "</option>";
}
echo "</select>";
?>
<?php
mysql_connect('localhost', '******', '**********');
mysql_select_db('*************');
$sql = "SELECT Model FROM myTable";
$result = mysql_query($sql);
echo "<select class='modelbox' name='carmodel3'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['Model'] . "'>" . $row['Model'] . "</option>";
}
echo "</select>";
?>
<input type="text" maxlength="4" name="car3year" placeholder="year" class="WriteInBox"/>
<input type="text" maxlength="6" name="car3miles" placeholder="miles" class="WriteInBox"/>
</div>
Have you ever heard of JQuery. If not, it time for some education. Among a host of other things, JQuery makes it fairly easy to simpllify your AJAX calls -- Best time I ever invested in web development was learning JQuery. See http://api.jquery.com/jQuery.ajax/ for the JQuery docs for the AJAX method. There are some simple usage examples at the bottom of the page. There are also plugins that handle cascading dropdowns lists with simple code, like this one http://jquery-plugins.net/jquery-cascading-dropdown-plugin
Once you start using JQuery, you will discover the hardest thing is getting good lists of car makes and models -- hint they vary by model year too.

Deletion of rows from populated table

I'm currently facing a strange issue whereby I did not get any errors from my debugging page. My table consists of several rows and only the first row of the table can't be deleted.
Sample form:
$DB = new PDO('sqlite:database/Sample.db');
$result = $DB->query("select * from staff");
foreach ($result as $row)
{
$StaffNo= $row['StaffNo'];
$Name= $row['Name'];
$TelNo= $row ['TelNo'];
echo "<tr>";
//Go to remove.php to remove
echo "<form action=\"Remove.php\" method=\"post\">";
echo "<input type=\"hidden\" name=\"StaffNo\" value=\"$StaffNo\">";
echo "<input type=\"submit\" onclick=\"return confirm('Yes/No')\"/>";
echo "</form>";
echo "</td>";
echo '<td data-column-name="Name" char="data">'.$Name.'</td>';
echo '<td data-column-name="TelNo" char="data">'.$TelNo.'</td>';
</tr>
}
Remove.php:
$StaffNo= $_POST["StaffNo"];
$DB = new PDO('sqlite:database/Sample.db');
$DB->query("DELETE FROM Staff WHERE StaffNo=".$StaffNo);
#header("location:view.php");
From my code above, I can delete all my sample records except for the first row. It doesn't get deleted... Kindly advise if i did wrong somewhere....
I've tried your code and apart from the broken table code, everything seems fine. Make sure your table is correct (<table><tr><td>Content</td></tr></table>). In your question, you're missing an opening <td> on line 9 of the first file, as well as missing <table> tags. Some browsers don't handle broken tables very well and that might mess up your form.
Your query will also break if $StaffNo is an empty string, so double check that.
You can also try removing the header() call and print out errors using $DB->errorInfo().
To inject your variable i the hidden field you should type
".$StaffNo."
instead of
"$StaffNo".
probably it doesn't delete the first row of your table becouse it's the only one with a StaffNo defined.

Editing/Updating one of the results in a search query

I'm creating a page that searches for an item and then be able to edit/update it. I was able to do it when it returns just one result but when it gives me multiple results I could only edit the very last item. Below is my code:
.......
$dj =$_POST[djnum];
$sql= "SELECT * From dj WHERE datajack LIKE '$dj%'";
$result = mysql_query($sql);
//more code in here//
while ($info =mysql_fetch_array($result)) {
// display the result
echo "<form action=\"dj_update.php\" method=\"POST\"><input type=\"hidden\" name=\"djnumber\" value=\"".$info['datajack']."\">";
echo "<tr><td>DJ ".$info['datajack']."</td>";
echo "<td>".$info['building']." </td>";
echo "<td>Rm ".$info['room']." </td>";
echo "<td>".$info['switch']." </td>";
echo "<td>".$info['port']." </td>";
echo "<td>".$info['notes']." </td>";
echo "<td style=\"text-align:center;\"><input type=\"Submit\" value=\"Edit\" ></td></tr>";
}
// more code here //
Then this is the screen shot of the result:
The idea is the user should be able to click on "Edit" and be able to edit/update that particular item. But when I click any of the Edit button I could only edit the last item. What am I missing here? Is there an easier way to do this?
Thanks guys and Happy new year!
There's no form closing tag - it should be added after each "Edit" button.
Now, since forms are not closed, there are several hidden inputs with the same "djnumber" in each form, and I suppose, browser sends only one value - which is specified in your last row.
So, adding the following at the end of your loop:
echo "</form>";
should help.
What are the values for datajack?
If the values are datajack1, datajack2 etc then a LIKE will return the first one every time, you need to make your query more specific.
$sql = "SELECT * From dj WHERE datajack id ' " . mysql_escape_string($id) . "' LIMIT 1";
I have changed the query to match one row and also use an id field, using LIKE in this situation is bad, you want to edit a specific row, not a row that is potentially LIKE the row you thought you were editing.
Note the use of mysql_escape_string() too to stop MySQL Injection techniques.
Hope that helps.

Categories