I have the following code:
while ($content = mysql_fetch_array($content2)){
echo $content[0];
session_start();
$_SESSION['content'] = $content[0];
?>
<br />
Edit post.
<br /> <br />
<?php
}
It fetches and displays all posts from a blog system database, and you can click on "Edit." below each post. What I want to do is pass the content of that post to my edit.php script.
The problem is, whichever "Edit" button I click on, this will always pass the content of my last post, not the content of the post above that "Edit" button.
Now, I can see why that might be: The whole loop will be executed before I click on any button, and the value stored in $_SESSION['content'] will always be the value from the loop's last iteration. Am I right?
Maybe I shouldn't be using SESSION. Is there a better approach? How can I pass the "right" value of $content[0] to my edit.php script?
The reason why the edit button is always getting the last post is because you are overriding the content variable in the session on each loop.
I am not sure what information you are getting from the database, but you should have a unique ID in the database for each post which you grab in the array as well. If this does not exists, I would strongly recommend making a change in your table as it will simplify your process.
while ($content = mysql_fetch_assoc($content2))
{
echo $content['postText'] . "<br />";
echo ' Edit post. <br /><br />';
}
You will then have to set up the edit page to grab the id $_GET['postId'] and grab the proper content from the database.
You code must be improved, your logic isn't good. First of all, you don't need to use a session var, one alternative to do this is passing the post ID using a GET argument, something like this:
while ( $content = mysql_fetch_array($content2) )
{
$post_content = $content[0];
$post_id = $content[1];
echo $post_content . '<br /> Edit post. <br /> <br />';
}
Then, in edit.php you will retrieve the $_GET['postId'] and load the post content to be updated.
This would be your best bet if you are ready to go for GET commands. See the code below :
$content = mysql_fetch_array($content2);
foreach($content as $key => $val) {
echo "<a href=edit.php?id=$val['id']>$val['name']</a>";
}
Just a quick fix.
Replace $val['id'] with the column name of uniqueID and $val['name'] with the column name of the post.
I am using Jquery UI Selectable. The user has the option to dynamically add new list items to the original setup.
I would like to include a 'clear' button that will give the user the ability to clear each individual item they created by clicking on an X input submit (img).
HTML (php)
if ($this->session->userdata('inactivefilter') == true) {
$inactivefilter = $this->session->userdata('inactivefilter');
$i=0;
foreach ($inactivefilter as $filter)
{
$filterdash = implode('-', explode(' ', $filter));
echo "<li class='ui-state-default' id='$filterdash'>$filter</li>";
echo "<div id=clear>
<form method='POST' action='".base_url()."main/clear_filter'>
<input type='image' name='filtervalue' value='$i' src='".base_url()."img/board/icons/clear.png'></input>
</form>
</div>";
$i++;
}
}
This is where the list is created. specifically the clear_filter action form.
Clear_filter currently 'attempts' to grab the value of '$i' but I don't know how to pass that correctly.
here is the controller:
public function clear_filter()
{
$i = $_POST['filtervalue'];
$this->thread_model->clear_filter($i);
}
I'll omit the clear_filter model due to its irrelevance to the problem.
Essentially, I just need $i to be picked up based on whatever value is clicked on in the dynamic form on the actual page.
Any help would be appreciated!
Well, it seems like I just had things a bit backwards.
The code was more or less correct.
For Codeigniter, you catch the passed input value=$i by using the name ="filtervalue"
Change the controller code to :
$i = $this->input->post('filtervalue');
and $i is set to whatever value was clicked on.
I have an onclick event called in a PHP foreach loop for several items whose author name I need to click. Only one name was getting generated, so I know that I must have a unique id for each HTML element. I already have a variable $objkey for a counter used in the loop so I appended it to the id.
<?php
//This is the item that appears in the loop.
//Currently, clicking on each one that is generated only generates the first author name
//The correct author as passed by PHP displays in the loop.
//$closest is the value of the author's name.
echo 'Click name to add <span><button id="closest' . $objkey . '" onClick="setAuthor()">' . $closest . '</button></span><br />';
?>
I have done a print_r('$objkey); and the appropriate value for the counter is getting passed along.
I want the value of this button element $closest to be passed to an input field. I have appended the variable to both the input's id and name elements (not sure if that helps) (UPDATE: There is an input field for each of the authors that needs to get the value):
<?php
echo '<input id="author_name' . $objkey . '" type="text" name="author_name' . $objkey . '" value="' . $author . '" />';
?>
Where I'm stuck is with my function:
<script type="text/javascript">function setAuthor() {
var author = document.getElementById("closest").innerHTML;
window.alert(author);
document.forms["myform"].elements["author_name"].value = author; }</script>
How do I create a variable in the function for the unique ids so that each looped item generates distinct names?
One way to do it is to pass this to the the setAuthor function:
<?php
//This is the item that appears in the loop.
//Currently, clicking on each one that is generated only generates the first author name
//The correct author as passed by PHP displays in the loop.
//$closest is the value of the author's name.
echo "Click name to add <button id='closest_{$objkey}' onClick='setAuthor(this)'>{$closest}</button><br/>";
?>
With this approach, you can access the element within setAuthor:
<script type="text/javascript">
function setAuthor(el) {
var author = el.innerHTML,
id = el.id.replace(/^closest_/, '');
if (console) {
console.log(author);
}
document.forms["myform"].elements["author_name_" + id].value = author;
}
</script>
However, you shouldn't set onclick inline and for each element. You should use an event registration function.
Hello i want any checkbox i am gonna check, to stay checked after pagination.
here is the code:
foreach($test as $string){
$queryForArray = "SELECT p_fname,p_id FROM personnel WHERE p_id = " .$string["p_id"]. " ;" ;
$resultForArray = mysql_query($queryForArray, $con);
$rowfForArray = mysql_fetch_array($resultForArray);
?>
<td id="<?php echo $rowfForArray["p_id"]?>" onclick="setStyles(this.id)" ><?php echo $rowfForArray["p_fname"]?></td>
<td><input id="<?php echo $rowfForArray["p_id"]?>" class="remember_cb" type="checkbox" name="how_hear[]" value="<?php echo $rowfForArray["p_fname"]?>"
<?php foreach($_POST['how_hear'] as $_SESSION){echo (( $rowfForArray["p_fname"] == $_SESSION) ? ('checked="checked"') : ('')); } ?>/></td>
</tr>
<tr>
I am geting the data from a search result i have in the same page , and then i have each result with a checkbox , so that i can check the "persons" i need for $_Session use.
The only think i want is the checkbox's to stay checked after pagination and before i submit the form!(if needed i can post the pagination code, but he is 100% correct)
In the checkbox tag use the ternary operation, without that foreach inside him:
<input [...] value="<?php echo $rowfForArray["p_fname"]?>" <?php $rowfForArray["valueToCompareIfTrue"] ? "checked='checked'" : ''; ?> />
because the input already is inside of 'for' loop, then each time of the loop will create a new checkbox wich will verify if need to being check or not.
I hope I have helped you.
A few ways to tackle this:
(Straight up PHP): Each page needs to be a seperate form then, and your "next" button/link needs to submit the form everytime they click next. The submit data should then get pushed to your $_SESSION var. The data can then be extracted and used to repopulate the form if they navigate backwards as well. Just takes some clever usage of setting the URL with the proper $_GET variables for the form.
(HTML5): This will rely more on JavaScript, but basically you get rid of pagination and then just break the entire data set into div chunks which you can hide/reveal with JavaScript+CSS or use a library like JQuery.
(AJAX): Add event listeners to the checkboxes so that when a button is checked an asynchronous call is made back to a PHP script and the $_SESSION variable is updated accordingly. Again, this one depends on how comfortable you are with JavaScript.
Just keep in mind that PHP = ServerSide & JavaScript = ClientSide. While you can hack some PHP together to handle "clientside" stuff, its usually ugly and convoluted...
I did it without touching the database...
The checkbox fields are a php collection "cbgroup[]".
I then made a hidden text box with all the values which equal the primary keys of the selectable items mirroring the checkboxes. This way, I can iterate through the fake checkboxes on the current page and uncheck the checkboxes by ID that exist on the current page only. If the user does a search of items and the table changes, the selectable items remain! (until they destroy the session)
I POST the pagination instead of GET.
After the user selects their items, the page is POSTED and I read in the hidden text field for all the checkbox IDs that exist on that current page. Because PhP only tells you which ones are checked from the actual checkboxes, I clear only the ones from the session array that exist on the POSTED page from this text box value. So, if the user selected items ID 2, 4, 5 previously, but the current page has IDs 7,19, and 22, only 7, 19, and 22 are cleared from the SESSION array.
I then repopulate the array with any previously checked items 7, 19, or 22 (if checked) and append it to the SESSION array along with 2, 4, and 5 (if checked)
After they page through all the items and made their final selection, I then post their final selections to the database. This way, they can venture off to other pages, perhaps even adding an item to the dB, return to the item selection page and all their selections are still intact! Without writing to the database in some temp table every page iteration!
First, go through all the checkboxes and clear the array of these values
This will only clear the checkboxes from the current page, not any previously checked items from any other page.
if (array_key_exists('currentids', $_POST)) {
$currentids = $_POST['currentids'];
if (isset($_SESSION['materials']) ) {
if ($_SESSION['materials'] != "") {
$text = $_SESSION['materials'];
$delimiter=',';
$itemList = explode($delimiter, $text);
$removeItems = explode($delimiter, $currentids);
foreach ($removeItems as $key => $del_val) {
//echo "<br>del_val: ".$del_val." - key: ".$key."<br>";
// Rip through all possibilities of Item IDs from the current page
if(($key = array_search($del_val, $itemList)) !== false) {
unset($itemList[$key]);
//echo "<br>removed ".$del_val;
}
// If you know you only have one line to remove, you can decomment the next line, to stop looping
//break;
}
// Leaves the previous paged screen's selections intact
$newSessionItems = implode(",", $itemList);
$_SESSION['materials'] = $newSessionItems;
}
}
}
Now that we have the previous screens' checked values and have cleared the current checkboxes from the SESSION array, let's now write in what the user selected, because they could have UNselected something, or all.
Check which checkboxes were checked
if (array_key_exists('cbgroup', $_POST)) {
if(sizeof($_POST['cbgroup'])) {
$materials = $_POST['cbgroup'];
$N = count($materials);
for($i=0; $i < $N; $i++)
{
$sessionval = ",".$materials[$i];
$_SESSION['materials'] = $_SESSION['materials'].$sessionval;
}
} //end size of
} // key exists
Now we have all the items that could possibly be checked, but there may be duplicates because the user may have paged back and forth
This reads the entire collection of IDs and removes duplicates, if there are any.
if (isset($_SESSION['materials']) ) {
if ($_SESSION['materials'] != "") {
$text = $_SESSION['materials'];
$delimiter=',';
$itemList = explode($delimiter, $text);
$filtered = array();
foreach ($itemList as $key => $value){
if(in_array($value, $filtered)){
continue;
}
array_push($filtered, $value);
}
$uniqueitemschecked = count($filtered);
$_SESSION['materials'] = null;
for($i=0; $i < $uniqueitemschecked; $i++) {
$_SESSION['materials'] = $_SESSION['materials'].",".$filtered[$i];
}
}
}
$_SESSION['materials'] is a collection of all the checkboxes that the user selected (on every paged screen) and contains the primary_key values from the database table. Now all you need to do is rip through the SESSION collection and read\write to the materials table (or whatever) and select/update by primary_key
Typical form...
<form name="materials_form" method="post" action="thispage.php">
Need this somewhere: tracks the current page, and so when you post, it goes to the right page back or forth
<input id="_page" name="page" value="<?php echo $page ?> ">
if ($page < $counter - 1)
$pagination.= " next »";
else
$pagination.= "<span class=\"disabled\"> next »</span>";
$pagination.= "</div>\n";
Read from your database and populate your table
When you build the form, use something like this to apply the "checked" value of it equals one in the SESSION array
echo "<input type='checkbox' name='cbgroup[]' value='$row[0]'";
if (isset($filtered)) {
$uniqueitemschecked = count($filtered);
for($i=0; $i < $uniqueitemschecked; $i++) {
if ($row[0] == $filtered[$i]) {
echo " checked ";
}
}
}
While you're building the HTML table in the WHILE loop... use this. It will append all the select IDs to a comma separated text value after the loop
...
$allcheckboxids = "";
while ($row = $result->fetch_row()) {
$allcheckboxids = $allcheckboxids.$row[0].",";
...
}
After the loop, write out the hidden text field
echo "<input type='hidden' name='currentids' value='$allcheckboxids'>";
This post relates to WordPress and CIMY User Extra Fields. I do not think you need a knowledge of the latter to help with this problem, as it seems to be a WordPress issue more than anything.
CIMY User Extra Fields is a plugin that allows registered users to have much more information in their profiles. You can add as many fields as you want. You then have to edit "author.php" to pull in the new information.
I am currently using the following code to pull in the new user profile fields:
<?php if (have_posts()) { $flag = true; while (have_posts()) { the_post();
if ($flag) { $value = get_cimyFieldValue(get_the_author_ID(), 'dj-name');
if ($value != NULL) echo "<p><strong>Staff Bio: </strong>" . cimy_uef_sanitize_content($value);
echo "</p>";
$flag = false; }}}?>
The issue is this. Some of my users have 0 posts and this code will only pull the extra field content for the user if that have 1 post or more. This is due to the "if (have_posts())" function I suspect. Is there someway to modify the code to display the information even if the user has 0 posts?
Thanks
Zach
If it's not a need that a user must have a post to have CIMY values stored (which I assume), you just don't need to check for post-count > 0. You probably have copied that chunk of code over from a post template.
The following example just takes the value, and if it is set, will do the output via echo:
<?php
$authorID = get_the_author_meta('ID');
$value = get_cimyFieldValue($authorID, 'dj-name');
if (!empty($value))
echo '<p><strong>Staff Bio: </strong>'
, cimy_uef_sanitize_content($value)
, '</p>'
;
?>