Jump to content

Values from table and updating a row


B_CooperA

Recommended Posts

I've created a update form in my website where users can update their statuses every time they press the "Update" - button, which will open up the form (this has been made with jQuery). The codes are following:

 

Button(s) to open up the edit event form:

if($_SESSION['user_id'] == $_GET['id']) {
	echo "
	<form action='".$_SERVER['PHP_SELF']."' method='post'>
	<input type='hidden' name='event_id' value='".$row['event_id']."' />
	<ul class='profile-user-buttons'>

        // Edit button
	<li><button name='edit_event' class='edit-event medium-button-grey'>
        Muokkaa tapahtuma</button>
        </li>
        
        // Delete button
        <li><button type='submit' name='remove_event' class='remove-event medium-button-            grey'>Poista tapahtuma</button>
        </li>";
        
        // Count attendents
	if($this->countTotalattendents($row['event_id']) >= 1) {
	
        echo "
        // Remind attendents
        <li><button type='submit' name='remind_user' 
        class='remind-user medium-button-remind'>Muistuta</button>
        </li>";
	}
		echo	"</ul>
		</form>";
	}

Here's a edit function from my class file:

public function editEvent() {

	$event_name 		= htmlspecialchars($_POST['event_name']);
	$event_address 		= htmlspecialchars($_POST['event_address']);
	$event_date 		= htmlspecialchars($_POST['event_date']);
	$event_time_hour 	= htmlspecialchars($_POST['event_time_hour']);
	$event_time_minute 	= htmlspecialchars($_POST['event_time_minute']);
	$event_description 	= htmlspecialchars($_POST['event_description']);


	if (empty($event_name) && empty($event_date) && empty($event_address)
	&& empty($event_time_hour) && empty($event_time_minute)) {

		return false;
	}

	$updates = array();

	if (!empty($event_name))

  		$updates[] = 'event_name="'.$event_name.'"';

	if (!empty($event_time_minute) || $event_time_hour)

		$event_time = $event_time_hour.":".$event_time_minute;
 		$updates[] = 'event_time="'.$event_time.'"';

 	if(!empty($event_date)) 

 		$updates[] = 'event_date="'.$event_date.'"';

 	if(!empty($event_address))

 		$updates[] = 'event_address="'.$event_address.'"';

 	if(!empty($event_description))

 		$updates[] = 'event_description="'.$event_description.'"';

	$updates = implode(', ', $updates);

        // Setting up the MySQL query
	$query = "UPDATE events SET $updates WHERE event_id = :event_id";
	$stmt = $this->connect->prepare($query);
	$stmt->execute(array(
		':event_id' => $event_id
		));

	if($query) {

		header("location: profile.php?id=".$_GET['id']."");
		exit();

	} else {

		echo "ei toimi";
	}
}

And here's my form which is in different file than these two blocks of code:

<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" class="event_edit_form">
	<ul>
	<div class="event_header">Tapahtuman muokkaus »</div>

	<li>
        <label for="event_name">Tapahtuma:</label> 
	<input type="text" name="event_name" class="full" 
        placeholder="Tapahtuman nimi" />
        </li>

        <li>
        <label for="event_address">Osoite:</label> 
	<input type="text" name="event_address" class="full" 
        placeholder="Esimerkkiosoite 5"/>
        </li>
	
        <li>
        <label for="event_date">Päivämäärä ja aika:</label>
	<input type="text" name="event_date" class="datepicker smaller" 
        placeholder="<?php echo date("d.m.Y"); ?>" />
	
        <input type="text" name="event_time_hour" class="small" placeholder="12" />
	<input type="text" name="event_time_minute" class="small" placeholder="00" />
        </li>
	
        <li>
        <label for="event_description">Kuvaus tapahtumasta:</label>
	<textarea name="event_description" placeholder="Kuvaile tapahtumaa lyhyesti">
        </textarea>
        </li>

	<li><input type="submit" id="publish" name="update_event" 
        class="medium-button-blacker" value="Päivitä tapahtuma" />
        </li>

	</ul>
</form>

And I'm calling the event method within the same file as the form like this:

<?php

      if(isset($_POST['update_event'])) {

	if($event->editEvent()) {

	} else {

		$event->displayErrors();
	}
} 

?>

The major problem is that it doesn't update those events and I think I know the reason. It can't get the right value of event_id inside the execute array. I've tested the query with some static event_id numbers and it will work. I've tried

almost anything in it.. $_GET['event_id'], $_POST['event_id'], $event_id, $row['event_id'].. None of the will work.

 

Second issue is that every time I want to edit a certain event, I would want it to fill those form fields automatically with the values retrieved from the database acting as placeholders. So user can see what was the earlier value of that field.

 

Thanks in advance!

Edited by B_CooperA
Link to comment
Share on other sites

In the first form you're passing the event_id as a hidden form field. However in the second form the event_id is not present. In both cases you need to be defining the event_id in the form, then in the code that processes the submitted form your'd use $_POST['event_id'] to get the events id

 

To set the form fields with predefined data you need echo the fields value within the value attribute. Example

<input type="text" name="event_name" class="full" value="<?php echo $row['event_name']; ?>" placeholder="Tapahtuman nimi" />
Edited by Ch0cu3r
Link to comment
Share on other sites

 

In the first form you're passing the event_id as a hidden form field. However in the second form the event_id is not present. In both cases you need to be defining the event_id in the form, then in the code that processes the submitted form your'd use $_POST['event_id'] to get the events id

 

To set the form fields with predefined data you need echo the fields value within the value attribute. Example

<input type="text" name="event_name" class="full" value="<?php echo $row['event_name']; ?>" placeholder="Tapahtuman nimi" />

 

But how can I get the event_id and basically any other value from the database to form since the other form is in different file? I certainly can't use a $row['event_id'] because It will give me an undefined variable: row error?

Edited by B_CooperA
Link to comment
Share on other sites

Here's the function for listing all the events:

public function showAllEvents() {

$query = "SELECT * FROM events LEFT JOIN users ON users.user_id = events.creatoruserid
WHERE NOW() <= events.event_date
ORDER BY events.event_creation_date DESC"; 

      $stmt = $this->connect->prepare($query);
      $stmt->execute();
      $rows = $stmt->rowCount();

      if($rows >= 1) {

        $i = 1;
        while($i <= $rows) {

        $row = $stmt->fetch(PDO::FETCH_ASSOC);


            
	// Echo the user-event div part
	echo "<div class='black-show-name'>
	<a href='profile.php?id=".$row['user_id']."'>".$row['name']."</a>
	<div class='tri_angle'></div></div>
	<div class='user-event-header' >
	<input type='hidden' value='".$row['event_id']."' />

	<a href='profile.php?id=".$row['user_id']."'>
        <img src='images/thumbnails/".$row['profilepic']."' class='profilesmall'/></a>
	
        <h2><ul class='event-heading'>
	<li class='event_city' title='Paikkakunta'>".ucfirst($row['event_city']).'</li>

	<li class="event_name" title="Tapahtuma">' .ucfirst($row['event_name']). '</li>

	<li class="event-date" title="Päivämäärä">'. 
	date("d.m.Y G:i", strtotime($row[ 'event_date'])). ' <small>('.$days .')</small>        </li>

	<li class="event-created" title="Alkuun">
        Osallistujia: '. $this->countTotalattendents($row['event_id']). " 
	</li>

	<li class='event-attend' title='Näytä lisää'>";
	if($this->isAttending($row['event_id']) >= 1) {
	echo "<form action='".$_SERVER['PHP_SELF']."' method='post'>
	<input type='hidden' name='event_id' value='".$row['event_id']."'/>

        // Cancel the attending
	<input type='submit' name='remove_attend' value='-' title='Peru osallistuminen' 
        class='medium-button-remind' />
	</form>";

	} else {

	echo "<form action='".$_SERVER['PHP_SELF']."' method='post'>
	<input type='hidden' name='event_id' value='".$row['event_id']."'/>

        // Attend into event
	<input type='submit' name='attend_event' value='+' title='Osallistu tapahtumaan'        
        class='medium-button-attend' />
      	</form>";
  }		
  	echo "</li>
	</ul></h2>
	</div>

	<div class='event'>
	<p>Tapahtuman päivämäärä -ja kellonaika: " 
	.date('d.m.Y', strtotime($row['event_date']))." " 
	.$row['event_time']. "
      
	<p>Tapahtuman osoite - ja kaupunki: " 
	.ucfirst($row['event_address']). ", "
	.ucfirst($row['event_city'])."</p>
      
	<p>Tapahtuman kuvaus: " .ucfirst($row['event_description']). "</p>

 
	<div class='right_area'>";

        // Display attendents Names
	$this->getAttendentsNames($row['event_id']);

	echo "</div>";

	if($_SESSION['user_id'] == $row['creatoruserid']) {
        echo "
	<form action='".$_SERVER['PHP_SELF']."' method='post'>
	<input type='hidden' name='event_id' value='".$row['event_id']."' />
	<ul class='profile-user-buttons'>

	<li>
       <button name='edit_event' class='edit-event medium-button-grey'>Muokkaa tapahtuma       </button>
       </li>
	
       <li><button type='submit' name='remove_event' 
       class='remove-event medium-button-grey'>Poista tapahtuma</button>
       </li>";
	
       // If there are attendents, add the remind - button

       if($this->countTotalattendents($row['event_id']) >= 1) {

       echo "<li><button type='submit' name='remind_user' 
       class='remind-user medium-button-remind'>Muistuta</button></li>";
      
       }
	echo "</ul></form>";
	
     }

	echo "</div>";

	$i++;
}

	// If there are no events, display this

    } else {

	echo "<p>Ei näytettäviä tapahtumia</p>";

}

}
Link to comment
Share on other sites

Here

if($_SESSION['user_id'] == $row['creatoruserid']) {
        echo "
	<form action='".$_SERVER['PHP_SELF']."' method='post'>
	<input type='hidden' name='event_id' value='".$row['event_id']."' />
	<ul class='profile-user-buttons'>

	<li>
       <button name='edit_event' class='edit-event medium-button-grey'>Muokkaa tapahtuma       </button>
       </li>
	
       <li><button type='submit' name='remove_event' 
       class='remove-event medium-button-grey'>Poista tapahtuma</button>
       </li>";

You have an edit event button  (7th line). So you're passing the event_id to your edit event script via $_POST. When the user clicks the edit_event button you'd use $_POST['event_id'] to get the event out of the database, then in the form you provide for editing the event you need add the event_id as a hidden form field. 

<input type='hidden' name='event_id' value='".$_POST['event_id']."'/>

The code that then updates the event when the update_event button is pressed you'd use $_POST['event_id'] in your query to target the event that is being updated.

Edited by Ch0cu3r
Link to comment
Share on other sites

Tried what you wrote above, but still get the undefined index error:

<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" class="event_edit_form">
	<ul>
	<div class="event_header">Tapahtuman muokkaus »</div>
		
	<li><label for="event_name">Tapahtuma:</label> 
	<input type="text" name="event_name" class="full" 
        placeholder="Tapahtuman nimi" /></li>
		
	<li><label for="event_name">Osoite:</label> 
	<input type="text" name="event_address" class="full" 
        placeholder="Esimerkkiosoite 5"/></li>
		
	<li><label for="event_date">Päivämäärä ja aika:</label>
	<input type="text" name="event_date" class="datepicker smaller" 
        placeholder="<?php echo date("d.m.Y"); ?>" />

	<input type="text" name="event_time_hour" class="small" placeholder="12" />
	<input type="text" name="event_time_minute" class="small" placeholder="00" />
        </li>

	<li><label for="event_description">Kuvaus tapahtumasta:</label>
	<textarea name="event_description" placeholder="Kuvaile tapahtumaa lyhyesti">
        </textarea></li>

	<?php
	echo "<input type='hidden' name='event_id' value='".$_POST['event_id']."'/>";
	?>

	<li><input type="submit" id="publish" name="update_event" 
        class="medium-button-blacker" value="Päivitä tapahtuma" />
        </li>

	</ul>
	</form>
Link to comment
Share on other sites

Okay I think what is wrong with this, it has something to do with my javascript. So the update_event_form is there just statically placed in the page, so even if the edit_event - button is not pressed, the form can still be viewed in the source code. So one more time guys: :D

 

1# The form which opens the edit-event form if the edit_event - button is pressed:

if($_SESSION['user_id'] == $row['creatoruserid']) {
	echo "
	<form action='".$_SERVER['PHP_SELF']."' method='post'>
	<input type='hidden' name='event_id' value='".$row['event_id']."' />

	<ul class='profile-user-buttons'>
	<li><button name='edit_event' class='edit-event medium-button-grey'>
        Muokkaa tapahtuma</button>
        </li>
        
        </ul>
        </form>";
}

2# the edit_event form (statically placed in my other php file):

<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post" class="event_edit_form">

	<ul>
	<div class="event_header">Tapahtuman muokkaus »</div>
		
	<li><label for="event_name">Tapahtuma:</label> 
	<input type="text" name="event_name" class="full" 
        placeholder="Tapahtuman nimi" />
        </li>
		
	<li><label for="event_name">Osoite:</label> 
	<input type="text" name="event_address" class="full" 
        placeholder="Esimerkkiosoite 5"/>
        </li>
		
	<li><label for="event_date">Päivämäärä ja aika:</label>
	<input type="text" name="event_date" class="datepicker smaller" 
        placeholder="<?php echo date("d.m.Y"); ?>" />
		
        <input type="text" name="event_time_hour" class="small" placeholder="12" />
	<input type="text" name="event_time_minute" class="small" placeholder="00" />
        </li>

	<li><label for="event_description">Kuvaus tapahtumasta:</label>
	<textarea name="event_description" placeholder="Kuvaile tapahtumaa lyhyesti">
        </textarea></li>

	<input type="hidden" name="event_id" value="<?php echo $_POST['event_id']; ?>"/>

	<li><input type="submit" id="publish" name="update_event" 
	class="medium-button-blacker" value="Päivitä tapahtuma" /></li>
		
	</ul>
	</form>

3# Javascript to open up that form in modal:

$(document).ready(function() {

$(".edit-event").click(function(e) {

	e.preventDefault();

	$("form.event_edit_form").easyModal({

		autoOpen: true,
		overlayOpacity: 0.2,
		overlayColor: "#666360",
		overlayClose: true,
		closeOnEscape: true

	});

});

});

4# And finally the if statement to execute the editEvent method if user has pressed the update_event button:

<?php 

if(isset($_POST['update_event'])) {

	if($event->editEvent()) {

} else {

	$event->displayErrors();
}

} 
?>
Link to comment
Share on other sites

Oh I see now. For the modal to work you need the form to be submitted by ajax and then output the form in the modal. Currently your page is just static, no data is being sent/received from your script to be able to edit the event. All you are doing is displaying the modal when the edit-event button is pressed.

Edited by Ch0cu3r
Link to comment
Share on other sites

Yea, using JQuery's $.ajax() method will be fine. What you want to do first is wrap your existing edit form into a container div, eg

<div id="edit-form-container">
    <form action="<?php $_SERVER['PHP_SELF']; ?>" method="post" class="event_edit_form">
        ... rest of form...
    </form>
</div>

When the edit-event button is pressed you want to submit then parent form (the one that belongs to the button) using JQuery $.ajax method, so your script receives the event_id.

 

Now the important part is how your existing script handles this ajax request. You  only want your php script to return the html form code for editing the event, you don't want the whole webpage back. When you get the response from the ajax request you will then add the returned form into the edit-form-container div container, using something like $('#edit-form-container).html(ajaxRresponseTextVariable). Then your existing modal code for displaying the form should work.

 

You still want to maintain backwards compatibility if someone disables javascript. So you will want to make sure your script works without javascript too.

Edited by Ch0cu3r
Link to comment
Share on other sites

 

 

If i'm using classes, how the ajax request should know what method to look for

That is down to you.

 

In PHP you can detect an ajax request by checking the HTTP_X_REQUESTED_WITH $_SERVER variable. Example code to handle the request

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    // ajax request detected

    // check that the event_id has been posted
    if(isset($_POST['event_id']))
    {
         // get the event from database
         $row = $event_class_object->method_that_gets_the_event_from_db($_POST['event_id']);

         // return the html form for editing the event
         echo '
    <form action="'.$_SERVER['PHP_SELF'].'" method="post" class="event_edit_form">
        <input type="hidden" name="event_id" value="' .$row['event_id']. '" />
        ... rest of form...
    </form>';
    }
    exit(); // stop the script if needed.
}
Link to comment
Share on other sites

I actually meant the jQuery's ajax part.. You said few comments back that I should submit the parent form when I've pressed that edit-event button, so in jQuery like this:

$(document).ready(function() {

$(".edit-event").on("click", function() {
$(".parent_form_name").submit();
});

});

Where should I put this part of code?:

$.ajax({
url: 'http://example.com', <- What to put in here? Path to my Events.class.php - file?
type: 'POST',
data: $('.edit_event_form').serialize(),
cache: false,
}).done(function (response) {
/* It worked */
}).fail(function () {
/* It didnt worked */
});
Link to comment
Share on other sites

The javasript code be like this (I have not tested this code)

$(document).ready(function() {

	$("form .edit-event").click(function(e) {

		e.preventDefault();
	    var eventForm = $(this).form; // get the parent form

		$.ajax({
			url: 'http://example.com/file_that_processes_form.php', // or $_SERVER['PHP_SELF']
			type: 'POST',
			data: $(eventForm).serialize(),
			cache: false,
			}).done(function (response) {
				formHTML = response;                      // get the response
			}).fail(function () {
				formHTML = 'Oops something went wrong';   // display an error message in modal
			})
		});

		$('#edit-form-container').html(formHTML);                 // add response to the #edit-form-container container

		$("form.event_edit_form").easyModal({
			autoOpen: true,
			overlayOpacity: 0.2,
			overlayColor: "#666360",
			overlayClose: true,
			closeOnEscape: true
		});
	});
});

The url: segment needs to be whatever $_SERVER['PHP_SELF'] is.

Edited by Ch0cu3r
Link to comment
Share on other sites

Been testing the javascript

 

Change

var eventForm = $(this).form

to

var eventForm = $(this).closest( "form" )

Change

cache: false,
}).done(function (response) {
	formHTML = response;                      // get the response
}).fail(function () {
	formHTML = 'Oops something went wrong';   // display an error message in modal
})

to

cache: false,
context: $('#edit-form-container')
}).done(function (response) {
	$(this).html(response);                      // get the response
}).fail(function () {
	$(this).html('Oops something went wrong');   // display an error message in modal
})
Link to comment
Share on other sites

Now I'm getting a 404 network error on that url: $_SERVER['PHP_SELF'] line, so far it does look like this:

Tried with and without those PHP tags and echo


   $("form .edit-event").click(function(e) {

        e.preventDefault();
        var eventForm = $(this).closest("form"); // get the parent form

        $.ajax({
            url: "<?php echo $_SERVER['PHP_SELF']; ?>", // or $_SERVER['PHP_SELF']
            type: 'POST',
            data: $(eventForm).serialize(),
            cache: false,
            context: $('#edit-form-container')
            }).done(function (response) {
                $(this).html(response);                      // get the response
            }).fail(function () {
                $(this).html('Oops something went wrong');   // display an error message in modal
            })
        });

        $('#edit-form-container').html(formHTML);                 // add response to the #edit-form-container container

        $("form.event_edit_form").easyModal({
            autoOpen: true,
            overlayOpacity: 0.2,
            overlayColor: "#666360",
            overlayClose: true,
            closeOnEscape: true
        });

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.