Deleting Database Records With a checkbox? - php

I just finished my news posting system and I need help to make the news deletion system.
Right now I have this code to load the each post ID and TITLE into a table as well as a checkbox beside it.
<?php
$news = mysql_query('SELECT `id`,`title` FROM news');
if (!$news)
{
exit('<p>Error retrieving news from database!<br />'.
'Error: '.mysql_error().'</p>');
}
while ($new = mysql_fetch_array($news))
{
$id = $new['id'];
$title = $new['title'];
echo "<tr style='background: #3D3D3d; width: 400px; font-family: Century Gothic; font-size: 15px;'>";
echo "<td style='padding-left: 5px'><input type='checkbox' name='id' value='$id' /></td> <td style='padding-left: 15px'>$id</td> <td style='padding-left: 15px'>$title</td>";
echo "</tr>";
}
?>
I want to know how to delete each database record by id using checkboxes.

First i would recommend an Archive system over Deleting just so that the data is stored for any reason you would have to call on it, no matter how little importance the entry has.
an idea would be to break up the code so that it makes it easy to read:
All styles into a CSS file or CSS script takes and use classes and
IDs to set up style (its a bit hard to read your code)
Have SQL procedures call to manage the SQL data to make your code
able to change from PHP to something else if you ever need to
to add my idea to the code
<?php //deletenews.php
//....
$result = $mysql_query("Call Delete_news_Entry($id)");
if (!$result)
{
die("Error deleting record from news" . mysql_error);
}
//.... end of php
?>
SQL Procedure
DELIMITER $$
DROP PROCEDURE IF EXISTS $$
CREATE PROCEDURE DB.Delete_news_entry(in_ID INTEGER)
BEGIN
DELETE FROM news WHERE id=in_ID;
END $$
DELIMITER ;
(if you want it to be live over submit button)
javascript
<Script type='text/javascript'>
//depends on jquery
function deletenews(id)
{
var spanid = "#span"+id;
$.get("deletenews.php",
null,
function(){
Alert("Complete") //this is more or less for you to put your required code here
$(spanid).hide();
},
"html")
.error(function(){
Alert("error") // for your own code to go here
});
}
</script>
sorry, just modifying your code
//in your php code, for the event, try onclick or onchange to trigger the delete
echo "<span id='span$id'><td class='left'><input type='checkbox' name='id' value='$id' onclick='deletenews($id)' /></td><td class='left'>$id</td> <td class='left'>$title</td></span>";
Having everything a part makes it easy to read.
i have been practicing breaking my code up for a long time now, i even draw maps of how all my files relate instead of having a page of php 1000 lines of code or more.

Right now it seems that you're only creating the table rows, but I'm gonna go ahead and assume these are within in the table element. If this table is also within a form element, you can delete all the records with a checked checkbox on submit.
You need to use the PHP isset function in the form's action reference to check if the checkbox is set and a foreach loop to run through them all. Something like this:
<?php
foreach($_POST as $key =>$value){
if(isset($_POST[$key])){
$value = mysql_real_escape_string($value);
mysql_query("DELETE FROM table WHERE id = $value");
}
}
?>

Related

Creating tr value filter

I creating filer for website data. I have created value attribute for <tr>which means that the row belongs for specific company. And now i want to make that table would show rows depending which value i will choose. And i really dont have idea how to do that. $currentCompany is that value number of company id. Here is my script:
if($row["type"] != "Staff Comment")
{
print("<tr value=". $currentCompany ." style='height:25px;'>\n");
for ($loop = 0; $loop < count($fields["headings"]); $loop++) {
print("<td bgcolor='white' align=" . $fields["aligns"][$loop] . ">\n");
//translate some information, some not
if ($fields["headings"][$loop] == "Status") {
print($AppUI->_(format_field($row[$fields["columns"][$loop]], $fields["types"][$loop], $row[$fields["columns"][0]])) . "\n");
}
else {
print(format_field($row[$fields["columns"][$loop]], $fields["types"][$loop], $row[$fields["columns"][0]]) . "\n");
}
print("</td>\n");
//print("<tr>" . var_dump($fields) ."</tr>\n");
}
print("</tr>\n");
And here is how it looks like in website:
Hope you can help me guys. For example if i would choose value 25 it would print all tr which has that value.
You want to hide rows, or just not print them? If hide - You have to use JS - PHP cannot modify site dynamically. If just don't print them - use simple if, and possibly You want to pass this information via simple form and POST request.
Create form, which action point to Your script, and have text field where you can specify which company have to be shown. Then, in Your code something like this:
if($currentCompany == $_POST['company'])
{
print("<tr value=". $currentCompany ." style='height:25px;'>\n");
//More code....
}
With JS it will be more complicated - but easy, too. It will have to be done in this way:
Get all TR's
Check every TR value. If value not corresponds to Your needs - add "display: none" CSS attribute.
Concrete JS implementation depends on way you want to code in JS - pure JS, jQuery, other JS framework.

Update record with AJAX without refreshing form

I'm trying to update records in DB without refreshing Form. I have grid.php page with the form to display and update records. Then, I have the file update.php with the UPDATE query. The third file is js1.js with AJAX code. If I map the grid.php to update.php through action=update.php, the update query works great. But as soon as I try to include js1.js file to prevent form refreshing, it stops working.
The code is as following:
grid.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="j1.js"></script>
<?php //query.php
require_once 'header.php';
if (!$loggedin) die();
$query = "SELECT SpringMgmt.SpringMgmtID,
SpringMgmt.SpringMgmtActiveYear,
SpringMgmt.PoolID,
SpringMgmt.Notes,
SpringMgmt.SOIEstSubmitted,
SpringMgmt.EstAdditional,
SpringMgmt.SOIMeetingScheduled,
Pool.Pool,
Pool.AreaManager,
Employees.EmployeeID,
Employees.FirstName
FROM SpringMgmt
INNER JOIN Pool ON SpringMgmt.PoolID = Pool.PoolID
INNER JOIN Employees ON Employees.EmployeeID = Pool.AreaManager ";
$result = mysql_query($query);
echo "OK</div>";
if (!$result) die ("Database access failed0: " . mysql_error());
//TABLE AND ITS HEADING
echo '<table id="header" cellpadding="0" cellspacing="0" border="0" >';
echo "
<tr>
<th>Pool</th>
<th>Notes</th>
<th>SO Sent</th>
<th>Est</th>
<th>Meet Date</th>
</tr>
";
while($record = mysql_fetch_array($result)){
echo "<form id='myForm' name='myForm' method=post>";
echo "<tr>";
echo "<td >$record[Pool]</td>";
echo "<td ><textarea size=4 name=Notes rows=3 cols=22>$record[Notes]</textarea> </td>";
echo "<td style=background-color:><input type=text size=3 name=SOIEstSubmitted value='$record[SOIEstSubmitted]' /></td>";
echo "<td ><textarea size=4 name=EstAdditional rows=3 cols=12>$record[EstAdditional]</textarea></td>";
echo "<td style=background-color:><input type=text size=3 name=SOIMeetingScheduled value='$record[SOIMeetingScheduled]' /></td>";
echo "<td>
<input type=hidden name='SpringMgmtID' value=$record[SpringMgmtID] />
<input type=submit name='submit' id='submit' value='Submit' />
</div></td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
?>
update4.php:
<?php
require_once 'header.php';
if (!$loggedin) die();
if(isset($_POST['submit'])){
$UpdateQuery = "UPDATE SpringMgmt
SET Notes='$_POST[Notes]',
SOIEstSubmitted='$_POST[SOIEstSubmitted]',
EstAdditional='$_POST[EstAdditional]',
SOIMeetingScheduled='$_POST[SOIMeetingScheduled]'
WHERE SpringMgmtID='$_POST[SpringMgmtID]'";
mysql_query($UpdateQuery);
};
?>
js1.js
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'update4.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
Disclosure: I may sound incredibly patronizing and even mean in my response, please note that it is not my intention. I will show you how to fix the issue, but let me first add some comments about the code above along with some suggestions:
The structure of your HTML is not good: a form shouldn't be wrapping each tr, you should consider using div instead of a table, or a "table inside a form inside a cell" (the code looks as ugly as it sounds). You can read more about a similar case here: Create a HTML table where each TR is a FORM
Your SQL statement is subject to SQL injection. This is bad. Really, really bad. As I mentioned in the comments, consider changing to MySQLi or PDO and using parameterized queries. You can read more about it here: How can I prevent SQL injection in PHP?
Your HTML code is not clean. In general, your page will work because the browser will help, but trust me, that is bad programming: you'll eventually change the code, forget about it, and it will be a mess. From what I see:
There are multiple elements with the same ID (all the forms created by the loop).
There is incomplete inline CSS (background-color:).
Quotes are missing in many places.
There are a couple of closing </div> without an opening <div> (this could be OK if the opening div comes from header.php; but even if that was the case, the code would be difficult to maintain)
Finally, the solution. I hope you didn't skip all the text above and jump directly here, because it will really help you not only now but in the future.
Change these two things and your code will work (both in js1.js):
Wrap the function in a $(document).ready so it is executed when the page finishes loading.
Change the data from $("form").serialize() to $(this).serialize(), this way you will be sending only the information from the form with the button that you clicked on (instead of all the forms).
The final code for js1.js would look like this:
$(document).ready(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'update4.php',
data: $(this).serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
Okay, so a few things I'm going to try and help you out with quickly.
Query
Your query is complicated, but I feel needlessly so. I've been doing things with MySQL for quite some time now and I can't recall a situation where I used INNER JOIN in the method you are. A much shorter syntax for your query would therefore be: SQL Aliases
$query = "SELECT s.*, p.Pool, p.AreaManager, e.EmployeeID, e.FirstName
FROM SpringMgmt as s, Pool as P, Employees as E
WHERE s.PoolID = p.PoolID AND e.EmployeeID = p.AreaManager ";
HTML
Assuming the HTML in your script is the way you want for it to be shown, here's a few things: you can escape double quotes so that they do not break your code. I would change the code inside your loop to this: Click Here to understand the ".$variable." statements I put in your code
echo "<form id=\"myForm\" name=\"myForm\" method=\"post\">";
echo "<tr>";
echo "<td data-field-id=\"pool\">".$record['Pool']."</td>";
echo "<td ><textarea data-field-id=\"notes\" size=\"4\" name=\"Notes\" rows=\"3\" cols=\"22\">".$record['Notes']."</textarea> </td>";
echo "<td style=\"background-color:\"><input data-field-id=\"submitted\" type=\"text\" size=\"3\" name=\"SOIEstSubmitted\" value=\"".$record['SOIEstSubmitted']."\" /></td>";
echo "<td ><textarea size=\"4\" data-field-id=\"additional\" name=\"EstAdditional\" rows=3 cols=\"12\">".$record['EstAdditional']."</textarea></td>";
echo "<td style=\"background-color:\"><input data-field-id=\"meetingScheduled\" type=\"text\" size=\"3\" name=\"SOIMeetingScheduled\" value=\"".$record['SOIMeetingScheduled']."\" /></td>";
echo "<td>
<input type=\"hidden\" name=\"SpringMgmtID\" value=\"$record[SpringMgmtID]\" />
<input type=\"submit\" name=\"submit\" id=\"submit\" value=\"Submit\" />
</div></td>";
echo "</tr>";
echo "</form>";
AJAX/Javascript Calls
This is a bit more complicated to explain. The jQuery ajax object success function can accept a few parameters to help you in your request. See this link for more explanation. Jump the section about the .done() function. One of them is the data returned FROM the request. This means that in your update4.php file, if you would output the data to the browser as a JSON object, you could then use that data back on your original page.
$(document).ready(function(){
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'update4.php',
data: $(this).serialize(),
success: function (data,successText) {
for(var x in data){
//Use tree traversing to find the input/text elements that have the data-field-id option equal to the x variable; I can't test it right now so I don't want to have this here.
}
}
});
});
});
Update4.php
As another user pointed out in the comment section, your query here is very prone to SQL Injection. Please follow the link they provided to read more.
Now, assuming you want all of the data returned back, the very last set of lines in your update4.php file should be something close to :
<?php
require_once 'header.php';
if (!$loggedin) die();
if(isset($_POST['submit'])){
$UpdateQuery = /*"UPDATE SpringMgmt
SET Notes='$_POST[Notes]',
SOIEstSubmitted='$_POST[SOIEstSubmitted]',
EstAdditional='$_POST[EstAdditional]',
SOIMeetingScheduled='$_POST[SOIMeetingScheduled]'
WHERE SpringMgmtID='$_POST[SpringMgmtID]'";
Don't do this, please use a prepared statement or mysql(i)_real_escape_string() on the data.*/
$result = mysql_query($UpdateQuery);
if($result!==false){
echo json_encode(array(
'notes'=> $_POST['Notes'],
'submitted'=> $_POST['SOIEstSubmitted'],
'additional'=>$_POST['EstAdditional'],
'meetingScheduled'=>$_POST['SOIMeetingScheduled']
));
}
};
NOTE I do NOT recommend doing this. You should move these $_POST variables into other variables that you have properly sanitized. NEVER assume that your users have no knowledge of web technologies. Always, ALWAYS assume the user is someone who has the malicious intent to steal the data from your database. Therefore, ALWAYS check user-inputted data. The only reason I have set this up is because you seem like you are fairly new to these aspects of web development and with all of the other information I've presented I don't want to overload you and turn you off from web development/design.
Side Note
I would suggest looking up a template engine of some variety. It is generally a better practice to have your display (HTML) and data (PHP) as separate as possible. The only template engines I've used previously were a modified version of PhpBB 3's template engine, and Smarty (which the phpBB team based their template engine on).
Since beginning to type this I've seen another answer posted and read it quickly. I think both of us address slightly different portions of your overall problem, so I will give this post to you as a reference, though I think the other user's answer is a bit better than mine is. I repeat his sentiment though, if I sound condescending or mean, I don't mean to.
Also, as I'm sure someone will or has pointed out to you, get in the habit of using mysqli_* functions as mysql_ will be deprecated (no longer usable) in coming versions of PHP.

How to make an inline editable content?

I have a list of products that I wish to be editable. When a user hits the edit button, then the content of only the selected product needs to be changed (for example to a textbox so the user can edit the title on the fly). But how do I prevent php to echo for example a textbox to all the products- I guess it would do that automatically?
I also guess that i should use some Jquery stuff to make the content editable :P ?
The list is being looped like this:
$items = $mysqli->query("SELECT product_name, product_id FROM products");
while($products = $items->fetch_assoc(){
echo $products['product_name'];
echo 'Edit me';
}
As your first commenter pointed out, PHP alone is not enough here. You'll need on-page JS code that can communicate the changes in the browser, and a PHP script that can take those changes and work them back into the database. You can either write that yourself, or use proven libraries that exist specifically for this purpose, like http://backbonejs.org/ or http://angularjs.org/
These are model/view frameworks that let you show a view of your database data on a page, while keeping them editable, updating the database records when you update the entry online. But be warned: if you've never worked with MVC frameworks, you get to look forward to probably being very confused at first. The approach is completely different from the much simpler "get data from db with PHP, generate page content, send off to client, the end" approach.
Not necessarily the most efficient, but if there aren't a huge number of products how about including a simple form for each product but just hiding it until the 'Edit' link is clicked?
The list/forms:
$items = $mysqli->query("SELECT product_name, product_id FROM products");
while($products = $items->fetch_assoc(){
echo "<span>" . $products['product_name'] . "</span>";
echo "<a class='editButton'>Edit</a>";
echo "<form action='products.php' method='post' style='display: none;'>
<input type='hidden' name='product' value='" . $products['prodcut_id'] . "' >
<input type='text' name='title' value='" . $products['product_name'] . "' >
<input type='submit' value='Update' >
</form>";
echo "<br/>";
}
The jQuery:
$(".editButton").click(function(){
//Hide the text entry and the edit link
$(this).prev().hide();
$(this).hide();
//Show the form
$(this).next().show();
});
If you'd rather not reload the page to submit changes you could submit them via ajax too for a more dynamic user experience.

how to get an id of an element, which is returned from php code

I am trying to build a db driven web site in which the user selects from a drop down menu a
value and some Information from a database are returned. I use an ajax post cause i dont want the page to get refreshed:
$("#button").click(function(){
var datastr = ($('#act').val());
var datastr1 = ($('#loc').val());
$.ajax({
type:'POST',
url:'activities_code.php',
data: {datastr:datastr, datastr1:datastr1},
success:function(response){
$("#msg").html(response);
} });});
In the url parameter I have the following php file (this is a part of the php file):
$query = "SELECT PK,title,Information from activities where Activities='$category'";
$result = mysqli_query($dbcon, $query) or die('no available data');
echo "<table>";
$num_results = 0;
$t = 0; //title counter for the id of each title
while ($row=mysqli_fetch_array($result, MYSQLI_ASSOC)) {
// Here the columns of title and information are printed
echo "<tr><td>";
echo "<a href='test.php' id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
echo "<br>";
echo $x = $row['PK'];
echo "</td></tr>";
echo "<tr><td>";
echo $row['Information'];
echo "</td></tr>";
// Here I sum up the number of the results
$num_results=$num_results+1;
$t = $t+1;
}
}
As you can see, I have a while loop in which I echo each time a link with an id:
"<a href='test.php' id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
What I want to do is to use this id of each link later in my code by doing something like this:
document.getElementById("t1").value
My question is, how can I return this id's to the client side? I think I should write something in the success function but I have no idea what.
If you dont understand some part of the code or I didn't explain everything clear, please ask me.
Thanks
D.
This is what I get when I alert(response) in the success function.
<!DOCTYPE HTML>
<table id="container"><tr><td><a href='test.php' id="t0" target="_new" class='pickanchor'>Rafting in Voidomatis</a><br>1</td></tr><tr><td>
<img src="m.jpg" class="textwrap" height="120px" width="120px">
<p style="text-align:left;">Our experienced rafting instructors will show you the best way to enjoy Voidomatis, the river with the most clear waters inSouth Europe. You can also cross the Vikos Gorge by following Voidomatis river in an attractive one and a half hour long walk. Alternatively you can ask for the more demanding Aoos river rafting.</p>
<br>
<br>
<hr></td></tr><tr><td><a href='test.php' id="t1" target="_new" class='pickanchor'>Rafting in Lousios</a><br>4</td></tr><tr><td><img src="raf.jpg" class="textwrap" height="120" width="120">
<p>You will be surprised to know that Greece hides numerous, densely vegetated rivers offering amazing rafting opportunities. In the whole mainland, there is a company base awaiting you, for an amazing � off the beaten track experience!</p>
<br>
<br>
<br>
<hr></td></tr><div id="r2" align="center" id="result_2">2 results for rafting were found!
</div></table> <!-- End of PHP code-->
First, There is problem with ID of your anchor tag. here is correction
"<a href='test.php' id=\"t".$t."\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
Second, Give id to your table like
<table id="container">
Third, give class to your anchor tag.
"<a href='test.php' class='pickanchor' id=\"t.$t\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
Now write following code into your success handle after .html() statement
NEW EDIT
$("a.pickanchor").each(function(i){
alert(this.id);
});
In line you presentd you made mistake. In wrong place you have added ".
echo "<a href='test.php' id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
It should be
echo "<a href='test.php' id=\"t".$t."\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
As simplest solution you could add after the while loop
echo "<script> my_max_id_num=$t </script>"
This will give you knowledge about which ids are present on page. This should give your js script access to my_max_id_num variable. It's not considered best programming practice but is simple.
Second (better) way of solving problem could be returning json instead of html and rewriting your success method. This will be more work to be done:
Rewrite while loop so it returns something like:
{ "data":[
...
{ "id":"10", "target":"_new", "title":"one_of_your_link_titles" },
{ "id":"10", "target":"_new", "title":"one_of_your_link_titles" },
...
]}
Rewrite your ajax query so it will accept json, and rewrite success method so it will create your links on basis off data returned from server.
This way you will have both, ids and your links in one query. What's more in case of changing requirements it will be easier.
The simplest solution would be to give your elements a class, that way you don't need to select based on the elements id, but you can access it easily:
eg.
test 0
test 1
$('#msg').on('click', '.className', function() {
console.log(this.id);
});
I don't have enough rep points to ask for clarification, but what do you mean by 'return this id's to the client side'? Also what would the 'value' of the element 't1' be?
Lets say you wanted to get the link location it could be something like:
var value = $('#addButton').attr('href');
and then do something with the value (not sure what you mean by 'return this id's to the client side') but perhaps you want the value then to be visible to the client?
So if you have a div somewhere on the page where you want it to show you could populate it with you value, maybe something like:
HTML
<div id="valueBox"></div>
jQuery
$("#valueBox").html(value);

save data in form of arrays to mysql database using a foreach loop

I have a form that submits multiple values using php. code is below:
echo "<form action='?ud=".$ud."' method='post'>Name: <input type='text' name='fname' />";
$resultw = mysql_query("SELECT * FROM options where userid='$ud' ORDER BY priority ASC");
while($row = mysql_fetch_array($resultw))
{
echo "
<input type='hidden' name='widgetid[]' value='".$row['widgetid']."' />
<span id='".$row['widgetid']."' style='color:white;font-size:13px;'>".$row['items'] . "</span><br></div><div style='' class='portlet_content'>
Enabled <input title='Enabled/Disabled' type='checkbox' value='enable[]' name='enable[]' ".$checked." id='checkbox".$row['id']."' />
Height <input title='set height' name='height[]' value='".$row['height']."' type='text' name='textfield' id='textfield".$row['id']."' />
";
}
echo '<input type="submit" /></form>';?>
as you can see its a loop thats get the values from db and echoes a form. I made it as simple as possible it has more input boxes but i removed them and removed the styling to make it simpler to read. when I hit Submit I would like to be able to have all those values updated to the database through a loop.
I tried foreach and struggled. any suggestions
First of all, your code has a security bug in that you are directly putting a variable into a SQL query. That allows for SQL injection. Instead, you should put the variable $ud through mysql_real_escape_string before inserting into the query or, significantly better, use MySQLi/PDO and prepared statements.
Have you checked that the form is correctly echoed onto the page? View the source (or use Firefox and Firebug) to double check that it has been properly inserted.
Then you will need to have a code block that is initiated when it receives a POST request. That code will get an array back for each of your variables e.g.
$widget_ids = $_POST['widgetid']; #this will be an array
$enable = $_POST['enable'];
$height = $_POST['height'];
You can do this for each of your POSTed variables and then just loop round the widget ids doing an update query for each one e.g.
$i = -1;
foreach($widget_ids as $widget_id) {
$row_enable = $enable[++$i];
$row_height = $height[$i];
//DO THIS FOR THE REST AND THEN YOUR UPDATE QUERY
}
Just to be pedantic, your HTML is also a bit messy and incorrect. For a form I would use label elements for each label and don't use br's for new lines. You also have a div with no beginning and then a div with no ending.

Categories