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.
Related
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.
I have a PHP function, to write out my tables from MYSQL. I've made a button, to delete the selected rows (named torles).
How can I delete with my 'torles' button, the row in which I'm pressing it?
function munkalapok(){
kapcsolat(); //connect to mysql, and write out all rows
$sql="SELECT * FROM munkalap ORDER BY id DESC";
$vissza=mysql_query($sql);
mysql_close(kapcsolat()); //close mysql
print "<div class='datagrid'><center>";
print "<table border='1' align='center'>";
print "<thead><th>Módosítás</th><th>Munkalapszám</th></thead>";
$i='1'; //for count rows
while ($sor = mysql_fetch_array($vissza)) {
print "<tr><tbody>";
print "<form method='POST'>".
"<input type='submit' value='$i. Törlés' name='torles'>".
"</form>" . "</td>";
//Create the button
if(isset($_POST['torles'])){
kapcsolat(); //open mysql
$parancs="DELETE FROM munkalap WHERE munkalapszam = '$munka'";
mysql_query ($parancs);
mysql_close (kapcsolat());
header("Location: ./Munkalapok.php");
}
print "<td>" . $sor['munkalapszam'] . "</td>";
print "</tbody></tr>";
$i++;
}
print "</table>";
print "</center></div>";
}
what is $munka, how did you get this..may be it should be for id..
So you can have a hidden field in your form and make it value as row id(whatever you have)
just try as:
print "<tr><tbody>";
print "<form method='POST'><input type='hidden' name='id' value='$sor[munkalapszam]'><input type='submit' value='$i. Törlés' name='torles'></form>" . "</td>";
//Create the button
if(isset($_POST['torles'])){
kapcsolat(); //open mysql
$munka=(int) $_POST['id']; //i did this for id
$parancs="DELETE FROM munkalap WHERE munkalapszam = '$munka'";
mysql_query ($parancs);
mysql_close (kapcsolat());
may this help you
In your code, you do something like this:
connect to SQL, get rows and print them
while printing
show a button
if this button is pressed, delete a row and redirect
end while
This is your first error.
Instead, your code logic should look something like this:
if there is posted data
delete the data
connect to SQL, get rows and print
Your main problem, (the one you are asking about), is that you create buttons, but no way to identify which row the button was pressed in.
Instead of adding the $i variable in the value of the button, you can add another input, which is hidden:
print '<input type="hidden" name="row_id" value="'.$i.'"/>';
This way, you will be able to find out which row the button was pressed for:
if (isset($_POST['torles'])) {
$id = (int) $_POST['row_id'];
// delete where id = $id (assuming that $i is an id)
}
Are you using IDs to identify records on your database? You should associate an ID to each record with the autoincrement function. That will be your Primary Key. Then use the record ID to identify the table row, and do not use that $i variable.
You should check out Database's Normal Forms. http://www.1keydata.com/database-normalization/first-normal-form-1nf.php
I'm hoping you have an id for every element in your db. And that the id is a primary key.
Saying that, modify
print "<td>" . $sor['munkalapszam'] . "</td>";
to
print "<td>" . $sor['munkalapszam'] . "<span id='".$sor['id']."' >X</span></td>";
In this way, every row in your table can be uniquely identified.The X is the delete symbol.
Next step would be to use JS to handle the click and sent the id to the server using ajax to delete the row.
$( "td" ).click(function() {
//write the ajax code here to send the id to the server.
});
This is not the most secure way to do this. But this would give you a basic idea on how to get started.
you can read about jQuery ajax here : http://api.jquery.com/jQuery.ajax/
jQuery click event : http://api.jquery.com/click/
In the backend you need a file called as delete.php or soemthing.Write the logic to delete a row using id in this file.Pass the id as argument through ajax to this.
I am opening a file (formatted in rows and columns) with PHP, looping through the rows on the file and echoing out rows into a table that meet a certain criteria. On each row that I echo out I am wrapping it in form tags. Ultimately, if I echo out 20 rows I will echo out 20 forms, each of them having a button. I am also echoing out a column with a comments box. I want the end user to be able to go to this page, enter comments on each row, and then hit the submit button to store the results of the row into a database. I have 2 problems that I do not know how to overcome.
1.) When echoing out the results to the table I do not create a static variable to reference when I go to create my SQL insert statement. How do I label each piece of data so I can call it later?
2.) There are going to be multiple forms, and the user will only be using one at a time. How do I ensure that when the user clicks submit, it only submits the data fields from the same row?
Hopefully this makes sense. If not Im happy to add as much clarification as needed. Im definitely a newbie when it comes to PHP, so I'm certain this is a poor design but Im on a tight timeline and I just need a working product for now. Next week I can go back and perhaps implement a better solution I'm sure one you kind people will suggest:)
<?php
if (($handle = fopen("name of file to open here", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
if ($data[4] == $login){
$num = count($data);
echo "<form action='analyzer.php' method='post'>";
echo "<tr>";
echo "<td>";
echo $data[1];
echo "</td>";
echo "<td>";
echo $data[2];
echo "</td>";
echo "<td>";
echo $data[3];
echo "</td>";
echo "<td>";
echo $data[4];
echo "</td>";
echo "<td>";
echo $data[5];
echo "</td>";
echo "<td>";
echo $data[6];
echo "</td>";
echo "<td>";
echo $data[7];
echo "</td>";
echo "<td>";
echo $data[8];
echo "</td>";
echo "<td>";
echo "<input type='text' name='comments' />";
echo "</td>";
echo "<td>";
echo "<input class='mybutton' type='submit' name='#' value='Submit' />";
echo "</td>";
echo "</tr>";
echo "</form>";
}
fclose($handle);
}
}
?>
1.) When echoing out the results to the table I do not create a static variable to reference when I go to create my SQL insert statement. How do I label each piece of data so I can call it later?
You need some way of uniquely identifying the piece of data. You can do this using hidden input variables.
2.) There are going to be multiple forms, and the user will only be using one at a time. How do I ensure that when the user clicks submit, it only submits the data fields from the same row?
You can name the forms or assign them a sequence in an array. For example:
<input type="submit" name="form[5]" />
You can also simplify your code by using a loop like this:
foreach( $data as $key=>$val ) {
echo "<td>$val</td>";
}
I know there is already an accepted answer here, but I feel like suggesting another way of doing this. Having a bunch of forms on one page each with their own submit button and requiring a page load every time is kind of cumbersome from a UI perspective.
My suggestion is that you start the long, painful, and rewarding process of learning Ajax. I have been learning jQuery AJAX and I use it to do similar things.
Example:
I have a table with 30 rows, each of which represent a process.
Each row has a checkbox.
I have a submit button down at the bottom, where a user can submit all the rows with checked boxes.
But, I also have buttons in each row (right next to the checkboxes actually). The buttons are simply labeled "now", and when you click them, that row is processed in the background without a page reload.
So I have allowed users to submit many rows with the normal form submit button if they want, OR to submit any individual row and not have to wait for the page to reload.
I can perhaps add some code here if anyone is ever interested.
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.
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.