I am a beginner in php.
I want to know how a particular row in a php session array can be deleted(not from the database, but from the page only).
I have a table namely, issues having columns issue_id & issue_descrp.
The page is displayed with a table in which each row contains issue and its corresponding id. Each row contain a delete button too. What I want is to delete the corresponding row from the page when I click the button.
This is my php code:
<?php
foreach($_SESSION['meeting_issues'] as $meeting_issues)
{
$query="select issue_id,issue from issues where issue_id='$meeting_issues'";
$result=$_SESSION['connection']->query($query) or die (mysql_error());
while($row = $result->fetch_assoc())
{?>
<?php $issue_id=$row['issue_id']; ?>
<tr><td><?php echo $row['issue_id']; ?></td><td><?php echo $row['issue']; ?></td><td><input type="button" name="<?php echo $row['issue_id']; ?>" id="button" value="Remove"/></td>
</tr>
<?php
}
}
?>
Hope my question is clear. Please help me. Thanks in advance.
use unset to delete array elements such as those in $_SESSION
http://php.net/manual/en/function.unset.php
do not delete the whole session this way, use this instead
http://php.net/manual/en/function.session-unset.php
To remove a row on the page itself, you will need Javascript or jQuery. jQuery is advised because of all the possibilities it gives and it is easier to use than normal Javascript.
jQuery:
$("#button").parents("tr:closest").remove();
Javascript:
document.getElementById('button').parentNode.parentNode.parentNode.removeChild(document.getElementById('button').parentNode.parentNode);
As you can see, jQuery is alot faster and more easy to type.
You are using an ID for the buttons, but the ID is always the same. I recommend using classes for this, because an ID should be unique on a page.
jQuery website
Related
I´ve been having a weird problem trying to create a php page that uses html forms to update mysql data.
The idea is to create a page that retrieves all the rows from a "news" table that I have, and inserts all the data into html forms as "default" values, so I can see what is already written before changing whatever I want in this form. Each form is generated exclusively for each row of data retrieved.
For that I use the POST method and two php files, one called "updateNews.php" which retrieves data and renders forms, and another one called "newsUpdater.php" which injects the updated data.
I have two problems here. One, the form doesn´t post the new data written in the form, but instead it posts the original data posted as "default". I guess this is a problem in my form code. I guess I´m not coding "default" values right.
The second problem is pretty strange. I retrieve rows from "news" table in reverse order, but when I "submit" the form associated with a particular row, it posts the data from the first row, not the row I´m interested in.
This is my code in the first php file, which retrieves data and renders forms:
<html>
<head>
<?php
include "connectToNews.php";
mysqli_set_charset($conToNews,"utf8");
$query = mysqli_query ($conToNews, "SELECT * FROM news ORDER BY id DESC");
?>
</head>
<body>
<?php
while ($newsArray = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
echo "<form action='newsUpdater.php' method='post' enctype='multipart/form-data'>";
echo "<p>".$newsArray['id']."</p><br>";
echo "<input name='Id' type='hidden' value='".$newsArray['id']."'>";
echo "<input class='input' name='Fecha' type='text' value='".$newsArray['fecha']."'><br>";
echo "<textarea class='textarea' name='Headline' type='text'>".$newsArray['headline']."</textarea><br>";
echo "<textarea class='textarea' name='Story' type='text'>".$newsArray['story']."</textarea><br>";
echo "<input type='submit' value='Actualizar'><br><br><br>";
echo "</form>";
}
?>
</body>
</html>
So, as you can see, I render a new <Form> for each existing row. I use 2 <input> tags and 2 <textarea> tags. One of the <input> tags is hidden and has he "Id" info associated with the particular row data. In anycase, I use "echo" with this Id data to verify that is retrieving ok (and it is). I use "value" attribute to set the retrieved text as default text in this <input> tags.
In the <textarea> tags, I use the space between the opening tag and the closing tag to locate the "default" text.
At this point, everything renders ok, I get as many forms as there are rows in "news" table and and when i press submit button, it takes me to the second php file.
The second php file is the "data updater". The code is the faollowing:
<html>
<head>
<?php
$Id=$_POST['Id'];
$Fecha=$_POST['Fecha'];
$Headline=$_POST['Headline'];
$Story=$_POST['Story'];
echo "<p>".$Id."</p><br>";
echo "<p>".$Fecha."</p><br>";
echo "<p>".$Headline."</p><br>";
echo "<p>".$Story."</p><br>";
include "connectToNews.php";
mysqli_set_charset($conToNews,"utf8");
$query=mysqli_query ($conToNews, "UPDATE news SET fecha='$Fecha' headline='$Headline' story='$Story' WHERE id='$Id'");
?>
</head>
<body>
<?php
echo "<p>News updated</p><br>";
echo "<p><a href='updateNews.php'>Go back to form</a></p>";
?>
</body>
</html>
As you can see, I´m saving the posted data "$_POST['whatever']" into 4 variables, just to have an easier time writting the future mySql query.
Then, I echo this variables to check what info is really been passed. And this is where it gets weird, because te rendered texts are the ones retrieved from to the first row in my "news" table, no matter which row am I editing in the form or what I´m writting in the form.
The other problem is that, regard of getting the "ok" message related to the updating process, the data never saves to "news" table. Although, I could be wrong, because I´m really injecting the original text from row 1 into row 1, no matter of which row I was really trying to edit.
Could you read my code and tell me if you guys see any problem.
Thanks!!!
In an UPDATE query the columns being updated must be seperated by commas, this explains why your data is not being updated.
The reason you didnt know for sure that the query was failing, and why, is that you are not testing that the query actually worked or not.
It is always a VERY good idea to test the results of all MYSQLI_ calls so I would add. This will then show you an error message that would help in bebugging
$query=mysqli_query ($conToNews,
"UPDATE news SET fecha='$Fecha',
headline='$Headline',
story='$Story'
WHERE id='$Id'");
if ( $query === FALSE ) {
echo mysqli_error($conToNews);
exit;
}
You have some SQL Injection issues in this code, you should read How can I prevent SQL injection in PHP?
I have like 6 tables in a page and I want to be able to read that page and pull all the tables
everything in between
I guess I just need to do this 1 time and add a while to do it until the end of the page.
I know how to use the data from a variable later or use it from an array
but I have no clue on how to attempt to grab the data from my webpage
I am going to build a page from that data with a different style but re-using the same tables
Well, using the following requires you to "know" those tables having class="class1" attribute, which you should :)
<?php
$doc = new DOMDocument();
$doc->loadHTMLFile("path/to/filename.html");
$tables = $doc->getElementsByTagName("table");
$validClasses = array("class1", "class2", "class3", "class4", "class5", "class6");
foreach ($tables as $table) {
if(in_array($table->getAttribute("class"), $validClasses)) {
// Here begins your journey :)
}
}
?>
*Now that I understand what you're after - someOne's answer seems a better starting point.
PHP can't 'pull' the data -- javascript can. If you are looking to use the data on the server side with PHP, you will need to send it to that page through POST or GET.
There are a few ways to do that, but perhaps the easiest is to set up a PHP loop on the data page that sets an input inside each field that you wish to send to your php script.
I might do it sorta like this in pseudo code -
echo <form method=post action="phpreader.php">
for ($x = 0 ; $ < $tables; $x++){
echo <table>
echo <tr><td> $data <input type=hidden name='data'.$x value = $data> </td></tr>
echo </table>
}
echo </form>
In the loop, you can put in as many table elements as you need and then attach the data to a form.
This will display your data programatically and also set it up to be send for post at the same time. You will need something to trigger this to go to post. Could be a Submit button, or javascript.
This could work, but I would maybe re-think your program method. If you are displaying this data to begin with, it has to come from somewhere. Might be a better way forward to pull the data from a database, display in the tables, and then you can re-pull the same data using the same query on your phpreader page.
I populated a textarea with database records using:
<textarea name="textarea" cols="200" rows="20"> <?php
echo "Player Id\t";
while($row = mysql_fetch_array($resourcebuilt)) {
echo stripslashes($row['playerid']);
....;
....;
} ?>
But this isn't exactly 100% what I need. I need to display records in what I believe is a textarea maybe not. But the records need to be clickable so I have functionality to those records (such as edit, delete, or even add a new record to database). Something like what admin panel contains.
I search SO and the web for something similar but with no luck. So does anyone know if this is possible with <textarea> </textarea> or do I need to using something like JavaScript or something related for the interactive functions? If possible provide examples. Thanks you.
I think what you are trying to do is populate a multiline select:
http://www.w3schools.com/tags/att_select_multiple.asp (sorry for w3 schools).
Your code for this would look more like:
<select multiple id="player-id-select">
<?php
while($row = mysql_fetch_array($resourcebuilt)) {
echo '<option>'.stripslashes($row['playerid']).</option>;
....;
....;
}
?>
</select>
Any other interaction (like clicking or whatnot) is done client side via javascript/jQuery:
http://jquery.com/
I have a feature on my users inbox that allows users to check/uncheck messages in their inbox that they want to make favourite.
I'm currently testing what happens when a user checks the box (clicks on the image and causes it to go from greyed out to colour meaning the box is checked).
Anyway as you can see from the code below when the box ischecked this url is suppose to be loaded: http://mysite.com/messages/favourite_checked
The message_id of the row the user has checked the box on is suppose to be added onto the end of the url this then loads my controller "messages" and method "favourite_checked" which then passes a variable that grabs the message_id from the url, stores it in a variable then sends it the my model and it is used in a mysql query.
Basically I update the favourites column of my messages table and set it to = 1 where the message_id from url matches the one in the messages table in my database. So yea, where the match is found the "favourite" column in that row is updated to 1. 1 = favourite 0 = not favourite.
Any I just thought I would make it clear what was happening..
My problem is nothing happens when I check the box, nothing is updated so I feel I must be doing something wrong where I try to add the id to the url in the javascript function.
I've tried $(post) also.. nothing happens then also.
Maybe someone can spot it because I really don't know what the problem is.
<script type="text/javascript">
// favourite check box
$('input.favourite:checkbox').simpleImageCheck({
image: '<?php echo base_url()?>images/messages/check.png',
imageChecked: '<?php echo base_url()?>images/messages/unchecked.png',
afterCheck: function(isChecked) {
if (isChecked) {
//query to db from php to update favourite number to 1
$.get('http://mysite.com/messages/favourite_checked'+'<?php foreach ($query as $row): ?><?php $row['id']; ?><?php endforeach; ?>');
}
// else (!isChecked)
// {
// //query to db from php to update favourite number to 0
// $.get('http://mysite.com/messages/favourite_unchecked');
// }
}
});
</script>
I think your basic problem is some confusion about when the PHP is running vs the javascript.
The PHP you put on the page is server side, it will load first, then the javascript will run client-side.
This part here:
$.get('http://mysite.com/messages/favourite_checked'+'<?php foreach ($query as $row): ?><?php $row['id']; ?><?php endforeach; ?>');
Seems like you are wanting this to be dynamic based on what you checked, but I don't see how that url is going to show specifically what you are looking for.
About the PHP:
I think you want to replace this:
<?php $row['id']; ?> // does nothing
with this:
<?php echo $row['id']; ?> // echo's the id
Although I´m not sure that that will work as the loop you have there will generate a strange url, just adding all id's...
About the javascript:
I´m not familiar with the simpleImageCheck() function you are calling, but does it have an onClick or onChange event handler? Otherwise I don´t see your code being run at all.
I'm returning all rows in a table with a while statement and PHP. the rows indicate a list of items. I'd like to include delete links next to each item so users can delete the entries. I'm trying to figure how to go about it in PHP. Can anyone help me write the script.. I'm using procedural.. not OOP.
I'm thinking the link takes users to a process page and back, but I'm not gonna be aware of the entries beforehand, it's all dynamic and the list is always changing.
thanks in advance
Best and save practice is using checkboxes. Google doesn't spider them, users can't put in malicious code easily and it doesn't refresh the page for every delete:
HTML sample:
while ($row = mysql_fetch_assoc($items))
{
echo '<input name="delete['.$row['id'].']" type="checkbox">';
}
PHP processing sample:
$delete = $_POST['delete'];
foreach($delete as $id = $value)
{
$id = mysql_real_escape_string($id);
mysql_query("DELETE FROM table_name WHERE id = $id");
}
Something like this should do the job nicely
Definitely take a look at Ignacio's comment. Since webspiders are able to follow links...naturally they will hit your delete link and destroy any data you have in there.
I'd recommend making it a tiny form with a submit button instead of a link.
Something along the lines of
echo "<form id='form_$id' method='post'>" ..
<input type='hidden' name='id' value='$id' /> ..
<input type='submit' name='submit_$id' value='delete' /> ..
</form>";
Wouldn't using Javascript to delete the record be a possible way to prevent web spiders from following the link?
For example, doing something like:
Delete
<script>
$('#delete_link').click(function() {
document.location.href = "delete.php?id=" + $(this).attr('rel');
});
</script>
This should be fine if web spiders do not follow Javascript links...