Jump to content

Recommended Posts

I guess updating the fields could be done using:

 

UPDATE table_name

SET column1=value, column2=value2,...

WHERE some_column=some_value

 

but not sure how to implement that. Create an Update button next to the submit button and a new code block for it on insert.php?

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-739005
Share on other sites

  • Replies 53
  • Created
  • Last Reply

Top Posters In This Topic

I added the code block for updating the row:

 

<?php
// DB Connection
$connection = mysql_connect("localhost","root","mypass");
if (!$connection) {
	die("Database connection failed: " . mysql_error());
}
// Select DB
mysql_select_db("hightrek", $connection);

    // sanitize the data to protect against injection attacks
    $eventName = mysql_real_escape_string($_POST['event_name']);
    $eventLocation = mysql_real_escape_string($_POST['event_location']);

    // we take what was entered in the date field, and run it through strtotime() (string to time) which gives a unix timestamp
    // then we run it through the date function and put it in the format we need for mysql.
    $eventDate = date('Y-m-d H:i:s', strtotime($_POST['event_date']) ); // FORMAT: 05/30/09 1:35 am

// CODE BLOCK
   if(isset($_POST['create_event'])) {
	  // Insert Values in a Row
      $insert_sql = "INSERT INTO events (eventName, eventLocation, eventDate) VALUES ('$eventName', '$eventLocation', '$eventDate')";
      $result = mysql_query($insert_sql, $connection) or die("Row insert failed: " . mysql_error())
	  // If (or not) successful...
      if(mysql_affected_rows() > 0)
      {        
         echo "1 record added";
      }
   } else {
     // the form has not been submitted yet.. no need to do anything here
   }

	/* 
	* UPDATING A ROW */
   if(isset($_POST['update_event'])) {

	$update_sql = mysql_query("UPDATE events SET 
			eventName = '$eventName' , 
			eventLocation = '$eventLocation', 
			eventDate = '$eventDate' 
			where eventId = '$eventId' ");
	$result = mysql_query($update_sql, $connection) or die("Row update failed: " . mysql_error());
	} else {
		echo "Update Failed!";
	}
?>

<a href="viewEvents.php">Return to previous page</a>

<?php
// Close Connection
mysql_close($connection);
?>

 

...and it doesn't work, ofcourse. :-) Can you please check?

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-739013
Share on other sites

Alright... your making progress. Now for the tricky part. You want to create a page to edit/delete items (edit.php? maybe). The original form to add, will be used to modify the items, so create a page that has the events listed with a couple of icons for edit / delete.

 

I typically do something like this...

<a href="add_event.php?action=edit&eventId=<?php echo $row['eventId']; ?>" ><img src="/images/edit.gif" ></a>  <a href="<?php echo $_SERVER['PHP_SELF']; ?>?action=delete&eventId=<?php echo $row['eventId']; ?>" ><img src="/images/delete.gif" ></a>

 

The delete function is pretty easy. At the top of the "edit" page. You would do something like this...

 

<?php

if(isset($_GET['action']) && isset($_GET['eventId']) && $_GET['action'] == 'delete')
{
  // initiate connection to DB
  $eventID = mysql_real_escape_string($_GET['eventId']); // sanitize the data
  $deleteQuery = "DELETE FROM events WHERE eventId = '$eventID'";
  $result = mysql_query($deleteQuery);
  if(mysql_affected_rows() > 0){echo 'Deleted Row";}
}
?>

 

The edit part is actually 2 pieces.... the first is responding to ?action=edit&eventId=XX. You want to run a query to retrieve the data for that particular ID, then you want to set that as the value="" value for the fields in the form you used to add the items.

 

Where your submit button is, add an if/else statement ....

<?php

if(isset($_GET['action']) && $_GET['action'] == 'edit')
{
   // display a submit button called UPDATE
}
else
{
// display a submit button called ADD... the one that is there now
}
?>

 

This allows you to take one form and use it for 2 different purposes. You take action depending on which submit button is given. When you detect the edit action, create a hidden field called eventID and give it the value of the event that is being edited so you can use it in your query to run the update statement.

 

So duplicate the code you use to actually add the event, and modify it to be something like this....

 

$updateQuery = "UPDATE events SET eventName='$eventName', eventLocation="$eventLocation', eventDate="$eventDate' WHERE eventId='$eventId'"

 

That is the basics of what you are wanting to accomplish.... so see what you can do with that and post back if you have questions.

 

 

In your previous post, it looks like your vars are not being populated properly. Follow the steps I have outlined above and see what you get, as my instructions should fix the issue your having.

 

Hope it helps,

 

Nate

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-739126
Share on other sites

So I replaced my static html button with this code block in viewEvents.php:

 

<?php
if(isset($_GET['action']) && $_GET['action'] == 'edit') {
echo "<input type=\"submit\" name=\"update_event\" value=\"Update Event\" />";
} else {
echo "<input type=\"submit\" name=\"create_event\" value=\"Create Event\" />";
}
?>

 

.but I don't understand where to place those edit/delete links. Should it be within the while loop so they're displayed on each row?

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-739505
Share on other sites

First off, I will give you a little tip. When dealing with the quotes you use in PHP, most everything can be done with ' ' (apostrophes). especially HTML. The way I usually do things is like this...

 

<?php
if(isset($_GET['action']) && $_GET['action'] == 'edit') {
   echo '<input type="submit" name="update_event" value="Update Event" />';
} else {
   echo '<input type="submit" name="create_event" value="Create Event" />';
}
?>

 

This avoids having to escape a crap load of stuff with a \.  When you need to use variables in HTML code, concatenate it with a . e.g.

 

<?php
echo '<div id="footer" class="someClass">'. $variableToEcho .'</div>';
?>

 

Notice, I start the string with a ', then I use a ' to end the literal string, and then a . (period) to tell PHP to "continue parsing this as 1 string, add the variable, and then another period to "connect" (concatenate) the pieces, and another ' to denote a literal string with 1 final ' to end the string.".

 

This also makes variables stick out better when using a code coloring editor.

 

So now to your question of where to put the other code.

 

In most cases, there are 2 pages that do *almost* the same thing. A public display of the events / other data, and then an admin area to manipulate them and edit them that is usually password protected. For our purpose here, just create a new page and create a new "display" code block. In that display codeblock, add the link image code so that each row has an edit / delete option next to it ( so in the while loop bit)..

 

<a href="add_event.php?action=edit&eventId=<?php echo $row['eventId']; ?>" ><img src="/images/edit.gif" ></a>  <a href="<?php echo $_SERVER['PHP_SELF']; ?>?action=delete&eventId=<?php echo $row['eventId']; ?>" ><img src="/images/delete.gif" ></a>

 

This then gives you a method to click an icon next to a row and modify or delete that. The delete code can be located in the top of this same page, as all your doing is detecting the action and id passed in the URL , and then running a query to perform the delete action, hence the PHP_SELF bit of the href="....".

 

The edit icon should link to the add event page so you can use the same form. Or you can create a new form if you would like. Depending on how this is going to be used, you might create a public display page and then a page that has the add form up top and the "edit / delete rows" at the bottom. If that is the case then the href="..." bit of the edit can be changed to the $_SERVER['PHP_SELF'] as well, or to the name of the page directly.

 

Give that a go and lemme know if / when you need help with the next steps.

 

Nate

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-739563
Share on other sites

I personally overuse double quotes

 

its so simple.. but a very bad practice.. and SO SLOW

 

double quotes are evaluating quotes, single quotes are literal quotes

 

"hello"

 

is a literal string, but PHP does not know that and will continue through the string looking for special characters and variables.. which requires a LOOP to loop through letters, and alot of processing (much like regex would) |...+... |....+.. |.....+. |......+ NO MATCH and starts at square one..

 

sometimes eval quotes are good to use.. but for the most part your script will run quicker (in longer scripts) with single quotes..

 

just my 2 cents

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-739589
Share on other sites

I never thought about it that way russell, I just got in the habit of using single quotes around everything except sql statements. With sql statements I surround it with " ". e.g.

 

$sql = "SELECT * FROM tableName WHERE this='$that' && that='$this'";

 

I found it quicker to code once I got into that habit, because I don't have to escape stuff. Especially  when dealing with HTML code. My fingers fly faster when dealing with '. .' rather than hitting the \ everytime I go to use a "

 

It seems to make for cleaner code also not having to look through all those \" \" quotes.

 

I guess it it a good thing I got into that habit. I just never really thought about the performance aspect of it.

 

Nate

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-739608
Share on other sites

Thanks for the great tip.

 

But, ahem, I still can't get myself past the syntax errors, please check:

 

	while ($row = mysql_fetch_array($result)) {
	echo "<tr><td>"
		.$row["eventId"]."</td><td>"
		.$row["eventName"]."</td><td>"
		.$row["eventLocation"]."</td><td>"
		.$row["eventDate"]."</td></td>"
		."<td>"
		.'<a href="edit_event.php?action=edit&eventId='.echo $row['eventId'];.'">Edit Event</a>'
		.'<a href="'.$_SERVER['PHP_SELF'];.'?action=delete&eventId='.echo $row['eventId'];.'">Delete Event</a>'
		."</td></tr>"
		;
}	

 

error is:

 

 

Parse error: syntax error, unexpected T_ECHO in /Volumes/disk2/Work/www/php/viewEvents.php on line 49

 

Thanks!

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-739634
Share on other sites

		echo "<tr><td>"
		.$row["eventId"]."</td><td>"
		.$row["eventName"]."</td><td>"
		.$row["eventLocation"]."</td><td>"
		.$row["eventDate"]."</td></td>"
		."<td>"

 

I know this method works with javascript.. but I am not quite sure if it works with php >.>

 

 

you could do something like

 

$a = sprintf('<tr><td>%1$s</td><td>%2$s</td><td>%3$s</td><td>%4$s</td><td><a href="edit_event.php?action=edit&eventId=%1$s'>Edit Event</a><a href="%5$s?action=delete&eventId=%1$s">Delete Event</a></td></tr>',
$row['eventId'],
$row['eventName'],
$row['eventLocation'],
$row['eventDate'],
$_SERVER['PHP_SELF']
);
echo $a;

 

OR!!

 

$arr = array('Id','Name','Location','Date');
echo "<tr>";
foreach ($arr as $value) {
	echo "<td>{$row['event'.$value]}</td>";
}
$id = $row['eventId'];
echo "<td><a href='edit_event.php?action=edit^eventId={$id}'>Edit Event</a>";
echo "<a href='{$_SERVER['PHP_SELF']}?action=delete&eventId={$id}'>Delete Event</a></td>";
echo "</tr>";

 

oh and your errors.. are probably do to you trying to attach an echo to a string..

 

actually that IS your error..

 

href="edit_event.php?action=edit&eventId='.echo $row['eventId'];.'">Edit Event</a>'

.'<a href="'.$_SERVER['PHP_SELF'];.'?action=delete&eventId='.echo $row['eventId'];.'">Delete

 

^^ errorous code

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-739653
Share on other sites

Yes, that method does work... I use it frequently.

 

This *should* work for ya. I don't think I have any syntax errors. I am not sure if it matters whether the concatenation period is at the beginning of the next line or at the end of the prev line.... This is just the way I code these types of blocks.  Personal preference I guess.

 

while ($row = mysql_fetch_array($result)) {
      echo '<tr><td>'.
         $row["eventId"].'</td><td>'. // this line could be deleted... you don't really need to display the event id.. 
         $row["eventName"].'</td><td>'.
         $row["eventLocation"].'</td><td>'.
         $row["eventDate"].'</td></td>'.
         '<td>'.
         '<a href="edit_event.php?action=edit&eventId='.$row['eventId'].'">Edit Event</a>'.
         '<a href="'.$_SERVER['PHP_SELF'];.'?action=delete&eventId='. $row['eventId'].'">Delete Event</a>'.
         '</td></tr>';
   }  

 

Nate

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-739758
Share on other sites

EDIT: Sorry, delete worked. I'd forgotten to place the following code in viewEvents.php

 

if(isset($_GET['action']) && isset($_GET['eventId']) && $_GET['action'] == 'delete') {
  // initiate connection to DB
  $eventID = mysql_real_escape_string($_GET['eventId']); // sanitize the data
  $deleteQuery = "DELETE FROM events WHERE eventId = '$eventID'";
  $result = mysql_query($deleteQuery);
  if (mysql_affected_rows() > 0){
echo "Deleted Row";
  }
}
?>

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-739782
Share on other sites

edit.php now contains this codeblock:

 

if(isset($_GET['action']) && isset($_GET['eventId']) && $_GET['action'] == 'edit') {
$update_sql = mysql_query("UPDATE events SET 
eventName = '$eventName' , 
eventLocation = '$eventLocation', 
eventDate = '$eventDate' 
where eventId = '$eventId' ");
$result = mysql_query($update_sql, $connection) or die("Row update failed: " . mysql_error());
} else {
echo "Update Failed!";
}

 

and php displays this error:

 

Notice: Undefined variable: eventName in /Volumes/disk2/Work/www/php/edit.php on line 10

Notice: Undefined variable: eventLocation in /Volumes/disk2/Work/www/php/edit.php on line 11

Notice: Undefined variable: eventDate in /Volumes/disk2/Work/www/php/edit.php on line 12

Notice: Undefined variable: eventId in /Volumes/disk2/Work/www/php/edit.php on line 12
Row update failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1

 

Should i have the same form on edit.php?

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-739791
Share on other sites

To get rid of the NOTICE: errors.... at the top of any pages giving this error, add this line....

 

ini_set('error_reporting', E_ALL ^ E_NOTICE);

 


if(isset($_GET['action']) && isset($_GET['eventId']) && $_GET['action'] == 'edit') {
$sql = "UPDATE events SET
   eventName = '$eventName' ,
   eventLocation = '$eventLocation',
   eventDate = '$eventDate'
   where eventId = '$eventId' "
$update_sql = mysql_query($sql) or die("Row update failed: " . mysql_error());

} else {
echo "Update Failed!";
}

 

Try that... You had 2 mysql_query statements..

 

the first was

$update_sql = mysql_query("UPDATE events .....

Then you had

$result = mysql_query($update_sql, $connect.... // you were passing the resource id from the first one into this one.

 

Try what I gave and see if that helps ya.

 

Nate

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-739794
Share on other sites

For displaying ID (serial #), I'm using this:

 

	$x = 1;
while ($row = mysql_fetch_array($result)) {
      echo '<tr><td>'.
         $x++ .'</td><td>'.
         $row["eventName"].'</td><td>'.
         $row["eventLocation"].'</td><td>'.
         $row["eventDate"].'</td></td>'.
         '<td>'.
         '<a href="edit.php?action=edit&eventId='.$row['eventId'].'">Edit</a> / '.
         '<a href="'.$_SERVER['PHP_SELF'].'?action=delete&eventId='. $row['eventId'].'">Delete</a>'.
         '</td></tr>';
   }

 

is there an elegant solution?

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-739795
Share on other sites

Great, the other error is gone, but I think what the "undefined variable" says is that php has no new data to update the table because I reach this page (edit.php) by simply clicking on "edit" link on viewevents.

 

To enter new data, do I need a new form on edit.php?

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-739799
Share on other sites

The Notice: undefined variable message will come up because the var has not been initialized.

 

I have had it throw those errors on the line I set the var. Probably not the best thing to do, but I just use the ini_set line to ignore them.

 

In this particular setup, I personally would do it like this....

 

display.php - public display of the events... no form, only the events displayed

edit.php - form at the top of the page to add new events & edit events when the edit link is selected, and a listing of the events at the bottom of the page with the edit / delete buttons.

 

 

Gotta run my son to the Dr., post back with any questions and I will take a look when I get back if someone else don't answer them for ya.

 

Nate

 

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-739817
Share on other sites

A separate display page is probably not required if we're displaying it on edit (currently viewEvents.php) page because the list is not for public.

 

So only two things remain now:

 

1. Ability to edit records.

2. User Authentication. (I think I can try it myself, seems easy.)

 

and these are what the pages look like:

 

viewEvents.php

 

<?php include("hightrek_mysql.php") ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>View Events</title>
</head>
<script type="text/javascript">
function confirmDelete() {
if(confirm("Are you sure you want to delete this event?")) {
	return true;
} else {
	return false;
}
}
</script>
<body>
<form action="insert.php" method="POST">
<fieldset>
<legend>Create a Row</legend>
	<label>Event Name:</label> <input type="text" name="event_name" /> <br />
	<label>Event Location:</label> <input type="text" name="event_location" /> <br />
	<label>Event Date:</label> <input type="text" name="event_date" /> <br />
	<?php
	if(isset($_GET['action']) && $_GET['action'] == 'edit') {
	   echo '<input type="submit" name="update_event" value="Update Event" />';
	} else {
	   echo '<input type="submit" name="create_event" value="Create Event" />';
	}
	?>
</fieldset>
</form><br />
<?php
// DELETING A RECORD
if(isset($_GET['action']) && isset($_GET['eventId']) && $_GET['action'] == 'delete') {
  // initiate connection to DB
  $eventID = mysql_real_escape_string($_GET['eventId']); // sanitize the data
  $deleteQuery = "DELETE FROM events WHERE eventId = '$eventID'";
  $result = mysql_query($deleteQuery);
  if (mysql_affected_rows() > 0){
	echo "Row Deleted.";
  }
}
// CREATING A RECORD
if(isset($_POST['create_event'])) {
   $insert_sql = "INSERT INTO events (eventName, eventLocation, eventDate) VALUES ('$eventName', '$eventLocation', '$eventDate')";
   $result = mysql_query($insert_sql, $connection) or die("Row insert failed: " . mysql_error());
   if(mysql_affected_rows() > 0) {        
      echo "1 record added";
   }
}
?>
<table cellspacing="5" cellpadding="5" border="1">	
<?php
$result = mysql_query("SELECT * FROM events", $connection);
if (!$result) {
	die("Database query failed: " . mysql_error());
}

$x = 1;
while ($row = mysql_fetch_array($result)) {
      echo '<tr><td>'.
         $x++ .'</td><td>'.
         $row["eventName"].'</td><td>'.
         $row["eventLocation"].'</td><td>'.
         $row["eventDate"].'</td></td>'.
         '<td>'.
         '<a href="edit.php?action=edit&eventId='.$row['eventId'].'">Edit</a> / '.
         '<a href="'.$_SERVER['PHP_SELF'].'?action=delete&eventId='. $row['eventId'].
		 '"onclick="return confirmDelete()">Delete</a>'.
         '</td></tr>';
   }
?>
</table>
</body>
</html>
<?php
// Close Connection
mysql_close($connection);
?>

 

and insert.php

 

<?php include("hightrek_mysql.php")

mysql_select_db("hightrek", $connection);

    $eventName = mysql_real_escape_string($_POST['event_name']);
    $eventLocation = mysql_real_escape_string($_POST['event_location']);

    $eventDate = date('Y-m-d H:i:s', strtotime($_POST['event_date']) ); // FORMAT: 05/30/09 1:35 am

   if(isset($_POST['create_event'])) {
	  // Insert Values in a Row
      $insert_sql = "INSERT INTO events (eventName, eventLocation, eventDate) VALUES ('$eventName', '$eventLocation', '$eventDate')";
      $result = mysql_query($insert_sql, $connection) or die("Row insert failed: " . mysql_error());
	  // If (or not) successful...
      if(mysql_affected_rows() > 0) {        
         echo "1 record added";
      }
   }
?>

<a href="viewEvents.php">Return to previous page</a>

<?php
// Close Connection
mysql_close($connection);
?>

 

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-739913
Share on other sites

For the editing of records part there is 2 parts. The first is to determine the edit function needs to be started, and then run a query to get the data for the fields.

 

<?php

if(isset($_GET['action']) && $_GET['action'] && isset($_GET['id']))
{
   $id = $_GET['id'];
   $query = "SELECT * FROM events WHERE eventId = '$id'";
   $result = mysql_query($query);
   while($row = mysql_fetch_array($result))
   {
      $edit['event_name'] = $row['eventName'];
      $edit['event_location'] = $row['eventLocation'];
      $edit['event_date'] =  $row['eventDate'];     
   }
}
?>

 

Once you have run this query, you have the data to fill in the value attributes of the text fields. But just so your not plugging in the $edit array items above, and possibly getting errors because they are not set, I will show you how I do this type of thing.

 

<?php
function getEdit($fieldName){
  global $edit; // set this to global so $edit is available inside this function.
  if(isset($edit[$fieldName]))
  {
     echo 'value="'.$edit[$fieldName].'"';
  }
}
?>

This function takes 1 parameter, the name of the field. It looks to see if the $edit array is set with the fieldname as a key. This is how the edit vars are set above. This is a user created function. Since we are going to be repeating the same checks 3 times, it is easier to put the code in a re-usable function to keep the code cleaner.

 

To use it add it to the fields.

 

 <input type="text" name="event_name"  <?php getEdit('event_name'); ?> />

 

You will then want to add a line in the form to add a hidden field if the $_GET['id'] var is set so that the form contains the ID. Once the form is submitted, you lose the ID var in the URL.

 

<?php 
if(isset($_GET['id'])){
   echo '<input type="hidden" name="eventId" value="'.$_GET['id'].'" />';
}
?>

 

So then once it is all put together, when you hit the edit link, the vars appear in the URL, and the update button shows up, your query runs and sets the $edit vars, the function runs and fills in the value attributes, and then you can make changes to the field values and hit the update button.

 

Then you use the same type of code you have for the add function, but change the if statement to be the name of the update button, and instead of an add statement, you run the update statement using $_POST['eventId'] in the WHERE clause.

 

Hope that makes sense, and gives you an idea of what to do next. Post back if you have questions.

 

Nate

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-739972
Share on other sites

I personally overuse double quotes

 

its so simple.. but a very bad practice.. and SO SLOW

 

double quotes are evaluating quotes, single quotes are literal quotes

 

"hello"

 

is a literal string, but PHP does not know that and will continue through the string looking for special characters and variables.. which requires a LOOP to loop through letters, and alot of processing (much like regex would) |...+... |....+.. |.....+. |......+ NO MATCH and starts at square one..

 

sometimes eval quotes are good to use.. but for the most part your script will run quicker (in longer scripts) with single quotes..

 

just my 2 cents

 

 

Single quotes are faster, but usually not enough to warrant calling double quotes SO SLOW.

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-739985
Share on other sites

This the viewEvents.php now:

 

<?php include("hightrek_mysql.php") ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>View Events</title>
</head>
<script type="text/javascript">
function confirmDelete() {
if(confirm("Are you sure you want to delete this event?")) { return true; } 
else { return false; }
}
</script>
<body>
<form action="insert.php" method="POST">
<fieldset>
<legend>Create a Row</legend>
	<label>Event Name:</label> <input type="text" name="event_name" <?php getEdit('event_name'); ?> /> <br />
	<label>Event Location:</label> <input type="text" name="event_location" <?php getEdit('event_location'); ?> /> <br />
	<label>Event Date:</label> <input type="text" name="event_date" <?php getEdit('event_date'); ?> /> <br />
	<?php
	if(isset($_GET['action']) && $_GET['action'] == 'edit') {
	   echo '<input type="submit" name="update_event" value="Update Event" />';
	} else {
	   echo '<input type="submit" name="create_event" value="Create Event" />';
	}
	if(isset($_GET['id'])){
	   echo '<input type="hidden" name="eventId" value="'.$_GET['id'].'" />';
	}		
	?>
</fieldset>
</form><br />
<?php
// DELETING A RECORD
if(isset($_GET['action']) && isset($_GET['eventId']) && $_GET['action'] == 'delete') {
  // initiate connection to DB
  $eventID = mysql_real_escape_string($_GET['eventId']); // sanitize the data
  $deleteQuery = "DELETE FROM events WHERE eventId = '$eventID'";
  $result = mysql_query($deleteQuery);
  if (mysql_affected_rows() > 0){
	echo "Row Deleted.";
  }
}
// CREATING A RECORD
if(isset($_POST['create_event'])) {
   $insert_sql = "INSERT INTO events (eventName, eventLocation, eventDate) VALUES ('$eventName', '$eventLocation', '$eventDate')";
   $result = mysql_query($insert_sql, $connection) or die("Row insert failed: " . mysql_error());
   if(mysql_affected_rows() > 0) {        
      echo "1 record added";
   }
}
// EDITING A RECORD
if(isset($_GET['action']) && $_GET['action'] && isset($_GET['id'])) {
   $id = $_GET['id'];
   $query = "SELECT * FROM events WHERE eventId = '$id'";
   $result = mysql_query($query);
   while($row = mysql_fetch_array($result)) {
      $edit['event_name'] = $row['eventName'];
      $edit['event_location'] = $row['eventLocation'];
      $edit['event_date'] =  $row['eventDate'];     
   }
}
// Function for filling the attributes...
function getEdit($fieldName){
  global $edit; // set this to global so $edit is available inside this function.
  if(isset($edit[$fieldName]))
  {
     echo 'value="'.$edit[$fieldName].'"';
  }
}
?>
<table cellspacing="5" cellpadding="5" border="1">	
<?php
$result = mysql_query("SELECT * FROM events", $connection);
if (!$result) {
	die("Database query failed: " . mysql_error());
}

$x = 1;
while ($row = mysql_fetch_array($result)) {
      echo '<tr><td>'.
         $x++ .'</td><td>'.
         $row["eventName"].'</td><td>'.
         $row["eventLocation"].'</td><td>'.
         $row["eventDate"].'</td></td>'.
         '<td>'.
         '<a href="edit.php?action=edit&eventId='.$row['eventId'].'">Edit</a> / '.
         '<a href="'.$_SERVER['PHP_SELF'].'?action=delete&eventId='. $row['eventId'].
		 '"onclick="return confirmDelete()">Delete</a>'.
         '</td></tr>';
   }
?>
</table>
</body>
</html>
<?php
// Close Connection
mysql_close($connection);
?>

 

but the vars don't appear in the url (eg. http://localhost/php/edit.php?action=edit&eventId=30) and the "undefined variable" errors still show up.

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-740215
Share on other sites

I had a few things goofed up. Try this and lemme know what you get. I re-structured a little. Most of the edit/delete/add code can go at the top. The function was not declared before you were trying to use it, so it has to go before the form. I am surprised that you did not get a big ol fatal error on that one .

 

I changed the location of the edit var. There is no need to go to a seperate page as this page has the form you need and it has all the modification functions. This one page can do it all.

 

<?php
ini_set('error_reporting',E_ALL ^ E_NOTICE);
include("hightrek_mysql.php");

   // DELETING A RECORD
   if(isset($_GET['action']) && isset($_GET['eventId']) && $_GET['action'] == 'delete') {
     // initiate connection to DB
     $eventID = mysql_real_escape_string($_GET['eventId']); // sanitize the data
     $deleteQuery = "DELETE FROM events WHERE eventId = '$eventID'";
     $result = mysql_query($deleteQuery);
     if (mysql_affected_rows() > 0){
      echo "Row Deleted.";
     }
   }
   // CREATING A RECORD
   if(isset($_POST['create_event'])) {
      $insert_sql = "INSERT INTO events (eventName, eventLocation, eventDate) VALUES ('$eventName', '$eventLocation', '$eventDate')";
      $result = mysql_query($insert_sql, $connection) or die("Row insert failed: " . mysql_error());
      if(mysql_affected_rows() > 0) {        
         echo "1 record added";
      }
   }
   // EDITING A RECORD
   if(isset($_GET['action']) && $_GET['action'] = 'edit' && isset($_GET['eventId'])) {
      $id = $_GET['eventId'];
      $query = "SELECT * FROM events WHERE eventId = '$id'";
      $result = mysql_query($query);
      while($row = mysql_fetch_array($result)) {
         $edit['event_name'] = $row['eventName'];
         $edit['event_location'] = $row['eventLocation'];
         $edit['event_date'] =  $row['eventDate'];     
		print_r($edit);
      }
   }
   // Function for filling the attributes...
   function getEdit($fieldName){
     global $edit; // set this to global so $edit is available inside this function.
     if(isset($edit[$fieldName]))
     {
        echo 'value="'.$edit[$fieldName].'"';
     }
   }
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>View Events</title>
</head>
<script type="text/javascript">
function confirmDelete() {
   if(confirm("Are you sure you want to delete this event?")) { return true; }
   else { return false; }
}
</script>
<body>
<form action="insert.php" method="POST">
   <fieldset>
   <legend>Create a Row</legend>
      <label>Event Name:</label> <input type="text" name="event_name" <?php getEdit('event_name'); ?> /> <br />
      <label>Event Location:</label> <input type="text" name="event_location" <?php getEdit('event_location'); ?> /> <br />
      <label>Event Date:</label> <input type="text" name="event_date" <?php getEdit('event_date'); ?> /> <br />
      <?php
      if(isset($_GET['action']) && $_GET['action'] == 'edit') {
         echo '<input type="submit" name="update_event" value="Update Event" />';
      } else {
         echo '<input type="submit" name="create_event" value="Create Event" />';
      }
      if(isset($_GET['id'])){
         echo '<input type="hidden" name="eventId" value="'.$_GET['id'].'" />';
      }      
      ?>
   </fieldset>
</form><br />
<table cellspacing="5" cellpadding="5" border="1">   
<?php
   $result = mysql_query("SELECT * FROM events");
   if (!$result) {
      die("Database query failed: " . mysql_error());
   }
   
   $x = 1;
   while ($row = mysql_fetch_array($result)) {
         echo '<tr><td>'.
            $x++ .'</td><td>'.
            $row["eventName"].'</td><td>'.
            $row["eventLocation"].'</td><td>'.
            $row["eventDate"].'</td></td>'.
            '<td>'.
            '<a href="'.$_SERVER['PHP_SELF'].'?action=edit&eventId='.$row['eventId'].'">Edit</a> / '.
            '<a href="'.$_SERVER['PHP_SELF'].'?action=delete&eventId='. $row['eventId'].
          '"onclick="return confirmDelete()">Delete</a>'.
            '</td></tr>';
      }
?>
</table>
</body>
</html>
<?php
  // Close Connection
   mysql_close($connection);
?>

 

Nate

 

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-740236
Share on other sites

Great, Now I see how its done.

 

On clicking edit, input fields are populated with the data of that row and the button changes to "Update Event". However, on clicking that button, it takes me to insert.php which shows this error:

 

 

Parse error: syntax error, unexpected T_VARIABLE in /Volumes/disk2/Work/www/php/insert.php on line 5

 

insert.php contains:

 

<?php include("hightrek_mysql.php")

// mysql_select_db("hightrek", $connection);

    $eventName = mysql_real_escape_string($_POST['event_name']);
    $eventLocation = mysql_real_escape_string($_POST['event_location']);

    $eventDate = date('Y-m-d H:i:s', strtotime($_POST['event_date']) ); // FORMAT: 05/30/09 1:35 am

   if(isset($_POST['create_event'])) {
	  // Insert Values in a Row
      $insert_sql = "INSERT INTO events (eventName, eventLocation, eventDate) VALUES ('$eventName', '$eventLocation', '$eventDate')";
      $result = mysql_query($insert_sql, $connection) or die("Row insert failed: " . mysql_error());
	  // If (or not) successful...
      if(mysql_affected_rows() > 0) {        
         echo "1 record added";
      }
   }
?>

<a href="viewEvents.php">Return to previous page</a>

<?php
// Close Connection
mysql_close($connection);
?>

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-740257
Share on other sites

I am not going to answer it for you I am going to challenge you to find it yourself :).. But here is a hint.

 

Most unexpected T_VARIABLE in.... errors are a result of lines above it. If it is not expecting a variable on the line mentioned, it means that the lines above it were not terminated correctly. Can you see what I forgot?? (look at line 1).

 

Nate

Link to comment
https://forums.phpfreaks.com/topic/141034-event-display/page/2/#findComment-740259
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.