Jump to content

Trying to update info on db via form...issues with script


lilbadger25

Recommended Posts

I realize my code is one big mess. I have been trying different things and probably have remnants of other ideas in here, but basically what I need it to do is to pull the title and info from the database, populate the image drop down from a folder on the server, and give the user the ability to edit the content or image.

 

It works in terms of populating the title and info. The drop down is loaded with the image names from the image folder on the server, but:

 

1. it doesnt show the image that is associated with the event, and i'd like it to.

 

2. it doesnt work. the text doesnt update, BUT it does make a new event that loads the image i've selected.

 

I have limited PHP knowledge (I'm sure that's apparent), but I am trying to learn.  I have been staring at this script for so long it's stopped making sense. I'd love to clean it up and, well, make it work. Can anyone lend a hand?

 

I was also told (maybe here) that mysql_result is not a very good (or fast) way to call results. If there is another way, I'd love to learn about it. As I mentioned in an earlier post, I am still learning and would love to learn better ways of doing things as I go.

 

<?php 	require_once('site.php'); 
mysql_select_db($database_site, $site);

$query = "SELECT * FROM events WHERE eventID = '$id'";
$result = mysql_query($query) or die ("Error in query: $query. " . mysql_error());
$i = 0
$id = mysql_result($result,$i,"eventID");
$eventTitle = mysql_result($result,$i,"eventTitle");
$eventInfo = mysql_result($result,$i,"eventInfo");
$eventImage = mysql_result($result,$i,"eventImage");

// form not yet submitted
// display initial form
if (!isset($_POST['action']))
{
?>
<table align="left" cellpadding="5" cellspacing="5">
<form action="<? echo $PHP_SELF; ?>" method="post">
          <input type="hidden" name="_submit_check" value="1"/>
          <input type="hidden" name="eventID"  value="<? echo $id; ?>" />
              <tr>
      <td valign="top" align="left"><b>Title</b></td>
      <td><input size="50" maxlength="250" type="text" name="eventTitle" value="<? echo $eventTitle; ?>" />
      </td>
    </tr>
    <tr>
      <td valign="top" align="left"><b>Info</b></td>
      <td><textarea name="eventInfo" cols="40" rows="10"><? echo $eventInfo; ?></textarea>
      </td>
    </tr>
    <tr>
      <td valign="top" align="left"><strong>Image</strong></td>
      <td><?
$directory = "images/";
$handler = opendir($directory);

print "<select name='imagename'>";
while ($file = readdir($handler)) {

// if $file isn't this directory or its parent,
// display in the select menu
if ($file != '.' && $file != '..') {
   print "<option value='$file'>$file</option>";
}
}
print "</select>";
closedir($handler); ?>
        <p align="center">
          <input type="submit" value="Submit" name="action" />
        </p></td>
    </tr>
  </form>
</table>
<?php
}
else
{

$imagename = $_POST['imagename'];
$query = "INSERT INTO events (eventTitle, eventInfo, eventImage) VALUES ('$eventTitle', '$eventInfo', '$imagename')";
$result = mysql_query($query) or die ("Error in query: $query. " . mysql_error());

// set up error list array
$errorList = array();
$count = 0;
// validate text input fields
if (!$eventTitle) { $errorList[] = "Invalid entry: Title"; $count++; }
if (!$eventInfo) { $errorList[] = "Invalid entry: Info"; $count++; }
// check for errors
// if none found...
if (sizeof($errorList) == 0)
{
// open database connection
	$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// print result
	echo "Update successful! <a href=intro.php>Go back to the Welcome page.</a>.";
// close database connection
	mysql_close($connection);
}
else
{
// errors found
// print as list
	echo "The following errors were encountered: <br>";
	echo "<ul>";
	for ($x=0; $x<sizeof($errorList); $x++)
	{
		echo "<li>$errorList[$x]";
	}
	echo "</ul>";
}
}
?>

Link to comment
Share on other sites

try this out

 

<?php
$directory = "images/";
$handler = opendir($directory);

print "<select name='imagename'>";
while ($file = readdir($handler)) {

// if $file isn't this directory or its parent,
// display in the select menu
if ($file != '.' && $file != '..') {
   if($file == $eventImage){
   print "<option value='$file' selected>$file</option>";
   $current_image = "<img src=\"$directory.$file\">";
   } else {
   print "<option value='$file'>$file</option>";
   $current_image = "No Image selected";
   }
}
}
print "</select>";
closedir($handler);
echo "$current_image"; 
?>

 

Ray

 

Ray

Link to comment
Share on other sites

Thanks Ray. It shows the image associated with the event, the first time I go to the edit page. There's a problem with going to another event, as it shows the image for the first event. I'm assuming this is what is happening. Is there a way to clear the $file variable each time the page is loaded?

 

When I hit submit, I get the following error:

Error in query: UPDATE events (eventTitle, eventInfo, eventImage) VALUES ('Event 166', 'Lorem ipsum...', 'cukes.jpg'). 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 '(eventTitle, eventInfo, eventImage) VALUES ('Event 166', 'Lorem

 

So, there's obviously a problem with my query:

	$query = "UPDATE events (eventTitle, eventInfo, eventImage) VALUES ('$eventTitle', '$eventInfo', '$file')";

 

everything is defined...what am I missing?

 

 

 

Link to comment
Share on other sites

added single quotes around events.

 

Error in query: UPDATE 'events' (eventTitle, eventInfo, eventImage) VALUES ('Event 166', 'Lorem ipsum ...', 'salad.jpg'). 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 ''events' (eventTitle, eventInfo, eventImage) VALUES ('Event 166

 

Why in the last line is it "events' (with both double and single quotes)?

 

It is also holding onto the salad.jpg variable which was the first selection, regardless of which image I chose to update to.

Link to comment
Share on other sites

UPDATE uses the set command

 

"UPDATE events SET eventTitle = '$eventTitle', eventInfo = '$eventInfo', eventImage = '$file' WHERE id = '$id'"

 

Make sure you have some sort of WHERE in your update otherwise it will update everything in the table.

 

Not sure why it shows the first. instead of using $file use $eventimage as the src for the image.

 

Ray

Link to comment
Share on other sites

You need backticks, not single quotes.  Also you are using a INSERT query with UPDATE, that wont work.

 

added single quotes around events.

 

Error in query: UPDATE 'events' (eventTitle, eventInfo, eventImage) VALUES ('Event 166', 'Lorem ipsum ...', 'salad.jpg'). 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 ''events' (eventTitle, eventInfo, eventImage) VALUES ('Event 166

 

Why in the last line is it "events' (with both double and single quotes)?

 

It is also holding onto the salad.jpg variable which was the first selection, regardless of which image I chose to update to.

Link to comment
Share on other sites

Revraz, what is the difference between single quotes and backticks? I know where they are and that they look different, I'm wondering how they are used in PHP.

 

Thanks to both of you guys for correcting my UPDATE query. I don't know how I didn't catch that.

 

What is happening now, is that no matter which event I choose to update (there are currently 5), the link shows the correct ID, but the fields on the edit page (which you guys have been helping me with) are populating with only the first row's data.

 

<?php 	
require_once('../Connections/site.php'); 
mysql_select_db($site, $site);
$query = "SELECT * FROM events";
$result = mysql_query($query);
$num = mysql_num_rows($result);
  //for($i = 0;$i < $num;$i++){
    $id = mysql_result($result,$i,"eventID");
    $eventTitle = mysql_result($result,$i,"eventTitle");
    $eventInfo = mysql_result($result,$i,"eventInfo");
    $eventImage = mysql_result($result,$i,"eventImage");

// form not yet submitted
// display initial form
if (!isset($_POST['action']))
{
?>
<table align="left" cellpadding="5" cellspacing="5">
  <form action="<? echo $PHP_SELF; ?>" method="post">
    <input type="hidden" name="eventID"  value="<? echo $id; ?>" />
    <tr>
      <td valign="top" align="left"><b>Title</b></td>
      <td><input size="50" maxlength="250" type="text" name="eventTitle" value="<? echo $eventTitle; ?>" />
      </td>
    </tr>
    <tr>
      <td valign="top" align="left"><b>Info</b></td>
      <td><textarea name="eventInfo" cols="40" rows="10"><? echo $eventInfo; ?></textarea>
      </td>
    </tr>
    <tr>
      <td valign="top" align="left"><strong>Image</strong></td>
      <td><?php
$directory = "images/";
$handler = opendir($directory);

print "<select name='eventImage'>";
while ($eventImage = readdir($handler)) {

// if $file isn't this directory or its parent,
// display in the select menu
if ($eventImage != '.' && $eventImage != '..') {
   if($eventImage == $eventImage){
   print "<option value='$eventImage' selected>$eventImage</option>";
   $current_image = "<img src=\"$directory.$eventImage\">";
   } else {
   print "<option value='$eventImage'>$eventImage</option>";
   $current_image = "No Image selected";
   }
}
} ?>
        </select>
        <p align="center">
          <input type="submit" value="Submit" name="action" />
        </p></td>
    </tr>
  </form>
</table>
<?php
}
else
{
$imagename = $_POST['imagename'];
$query = "UPDATE events SET eventTitle = '$eventTitle', eventInfo = '$eventInfo', eventImage = '$eventImage' WHERE id = '$id'";
$result = mysql_query($query) or die ("Error in query: $query. " . mysql_error());
// set up error list array
$errorList = array();
$count = 0;
// validate text input fields
if (!$eventTitle) { $errorList[] = "Invalid entry: Title"; $count++; }
if (!$eventInfo) { $errorList[] = "Invalid entry: Info"; $count++; }
// check for errors
// if none found...
if (sizeof($errorList) == 0)
{
// print result
	echo "Update successful! <a href=intro.php>Go back to the Welcome page.</a>.";
// close database connection
	mysql_close($connection);
}
else
{
// errors found
// print as list
	echo "The following errors were encountered: <br>";
	echo "<ul>";
	for ($x=0; $x<sizeof($errorList); $x++)
	{
		echo "<li>$errorList[$x]";
	}
	echo "</ul>";
}
}
?>

Link to comment
Share on other sites

Backticks are used for MySQL table and field names.  It's a mysql syntax character and not related to PHP.

 

Revraz, what is the difference between single quotes and backticks? I know where they are and that they look different, I'm wondering how they are used in PHP.

 

Link to comment
Share on other sites

The fields on the edit page will not populate as you have taken out the for loop, I think this is the one at the top, correct?

 

Personally I would write it like :

mysql_select_db($site, $site);
$qry = mysql_query("SELECT * FROM events") or trigger_error("SQL", E_USER_WARNING);
while($row == mysql_fetch_assoc($qry)) {
             $id = $row["eventID"];
             $eventTitle = $row["eventTitle"];
             $eventInfo = $row["eventInfo"];
             $eventImage = $row["eventImage"];
//Other code goes in here...
        }

 

Now do you mean to have as many forms as there are events, as that can get messy indeed and is not recommended way about it, or do you want to have a SELECT menu, where you can choose an event to be edited (best option)?

Link to comment
Share on other sites

Thanks Scotty...what happens is that there's a list of events on a "list events" page where the admin has a choice to either edit or delete the page. When the link is clicked, the $id is passed through the URL and the eventEdit.php page uses that $id to populate the fields to be edited.

 

Would the above snippet work in that case?

Link to comment
Share on other sites

All the above snippet does is get all the events, then for each event gets ur ids, and the other fields u want to pass.  You really just need one form.

 

What I would suggest is to use a radio button to select which event to edit.

 

Try this

<table align="left" cellpadding="5" cellspacing="5">
<form action="<? echo $PHP_SELF; ?>" method="post">
<?php

// form not yet submitted
// display initial form
if (!isset($_POST['action']))
{
require_once('../Connections/site.php'); 
mysql_select_db($site, $site);
$qry = mysql_query("SELECT * FROM events") or trigger_error("SQL", E_USER_WARNING);
while($row == mysql_fetch_assoc($qry)) {
	$id = $row["eventID"];
    $eventTitle = $row["eventTitle"];
    $eventInfo = $row["eventInfo"];
    $eventImage = $row["eventImage"];

?>

    <label for="eventID">Edit ?</label><input type="radio" name="eventID" id="eventID" value="<? echo $id; ?>" />
    <tr>
      <td valign="top" align="left"><b>Title</b></td>
      <td><input size="50" maxlength="250" type="text" name="eventTitle" value="<? echo $eventTitle; ?>" />
      </td>
    </tr>
    <tr>
      <td valign="top" align="left"><b>Info</b></td>
      <td><textarea name="eventInfo" cols="40" rows="10"><? echo $eventInfo; ?></textarea>
      </td>
    </tr>
    <tr>
      <td valign="top" align="left"><strong>Image</strong></td>
      <td><?php
$directory = "images/";
$handler = opendir($directory);

print "<select name='eventImage'>";
while ($eventImage = readdir($handler)) {

// if $file isn't this directory or its parent,
// display in the select menu
if ($eventImage != '.' && $eventImage != '..') {
   if($eventImage == $eventImage){
   print "<option value='$eventImage' selected>$eventImage</option>";
   $current_image = "<img src=\"$directory.$eventImage\">";
   } else {
   print "<option value='$eventImage'>$eventImage</option>";
   $current_image = "No Image selected";
   }
}
} ?>
        </select>
<?php } ?>
        <p align="center">
          <input type="submit" value="Submit" name="action" />
        </p></td>
    </tr>
  </form>
</table>
<?php
}
else
{
$imagename = $_POST['imagename'];
$query = "UPDATE events SET eventTitle = '$eventTitle', eventInfo = '$eventInfo', eventImage = '$eventImage' WHERE id = '$id'";
$result = mysql_query($query) or die ("Error in query: $query. " . mysql_error());
// set up error list array
$errorList = array();
$count = 0;
// validate text input fields
if (!$eventTitle) { $errorList[] = "Invalid entry: Title"; $count++; }
if (!$eventInfo) { $errorList[] = "Invalid entry: Info"; $count++; }
// check for errors
// if none found...
if (sizeof($errorList) == 0)
{
// print result
	echo "Update successful! <a href=intro.php>Go back to the Welcome page.</a>.";
// close database connection
	mysql_close($connection);
}
else
{
// errors found
// print as list
	echo "The following errors were encountered: <br>";
	echo "<ul>";
	for ($x=0; $x<sizeof($errorList); $x++)
	{
		echo "<li>$errorList[$x]";
	}
	echo "</ul>";
}
}
?>

 

Ive just copied and pasted about and added a few things in there so it may mess up your tables etc.

 

What I suggest is to go through some of the quick tutorials here -> www.w3schools.com just to get clearer understanding of how some of the html elements work and things like post.  Also the php manual tells you how the functions used work www.php.net.  Good Luck

Link to comment
Share on other sites

Thanks again, Scotty. I actually have gone through tutorials, have books, etc. I just find that there are not examples of what I'm doing and when I find seperate tutorials about what I'm trying to do, I just can't figure out how to put them together. The edit events page worked fine when I had just plain fields populated with the information on the database (based on id) but the issues started when I added the drop down menu with the photo options.

 

I can make the text information populate the boxes, and editable, and get it all to update.

 

I can get the drop down menu to populate with the imagenames from the server.

 

But I can't for the life of me, get them to work simultaneously.

 

Through adding and deleting bits of code, I've managed to delete parts that I shouldn't have and now it's just a mess.

 

Aside from the mess, I certianly wouldn't have gotten as much as I have done without the kind people on this board.

 

Part of my frustration issue is that I inherited this stuff with a new job and haven't had a chance to "catch up". It's been 5 years since I've written php and some of the elements that were promised are beyond my grasp. I'm trying...and I'm absolutely willing to read and learn and do tutorials...I just wish I had the TIME to actually do the tutorials that I need to do to get this project completed. I'm sort of learning these new elements as I go and I fear I'm not learning them as well as I'd like to - but deadlines are deadlines. I can't wait until this project is completed!

Link to comment
Share on other sites

The reason they won't work together is because you have two different variables with the same name.

 

Change

while ($eventImage = readdir($handler)) {
//to
while ($imageLocation = readdir($handler)) {

 

Then all subsequent $eventImage to $imageLocation after that.

 

What is happening now?

Link to comment
Share on other sites

Now, there's a Parse error: parse error, unexpected T_ELSE in /home/sites/site19/web/mucci/update/eventsEdit.php on line 82

 

I checked closed brackets and missing ;s but I couldn't see what what wrong.

 

<?php 	
require_once('../Connections/site.php'); 
$connection = mysql_connect($hostname_site, $username_site, $password_site) or die ("Unable to connect!");
mysql_select_db($database_site);
$qry = mysql_query("SELECT * FROM events") or trigger_error("SQL", E_USER_WARNING);
while($row == mysql_fetch_assoc($qry)) {
    $id = $row["eventID"];
    $eventTitle = $row["eventTitle"];
    $eventInfo = $row["eventInfo"];
    $eventImage = $row["eventImage"];
// form not yet submitted
// display initial form
if (!isset($_POST['action']))
{
?>
<table align="left" cellpadding="5" cellspacing="5">
  <form action="<? echo $PHP_SELF; ?>" method="post">
    <input type="hidden" name="eventID"  value="<? echo $id; ?>" />
    <tr>
      <td valign="top" align="left"><b>Title</b></td>
      <td><input size="50" maxlength="250" type="text" name="eventTitle" value="<? echo $eventTitle; ?>" />
      </td>
    </tr>
    <tr>
      <td valign="top" align="left"><b>Info</b></td>
      <td><textarea name="eventInfo" cols="40" rows="10"><? echo $eventInfo; ?></textarea>
      </td>
    </tr>
    <tr>
      <td valign="top" align="left"><strong>Image</strong></td>
      <td><?php
$directory = "images/";
$handler = opendir($directory);
print "<select name='eventImage'>";
while ($imageLocation = readdir($handler)) {

// if $file isn't this directory or its parent,
// display in the select menu
if ($imageLocation != '.' && $imageLocation != '..') {
   if($imageLocation == $imageLocation){
   print "<option value='$imageLocation' selected>$imageLocation</option>";
   $current_image = "<img src=\"$directory.$imageLocation\">";
   } else {
   print "<option value='$imageLocation'>$imageLocation</option>";
   $current_image = "No Image selected";
   } }
}
} ?>
        </select>
        <p align="center">
          <input type="submit" value="Submit" name="action" />
        </p></td>
    </tr>
  </form>
</table>
<?php
}
else
{
$imagename = $_POST['imagename'];
$query = "UPDATE events SET eventTitle = '$eventTitle', eventInfo = '$eventInfo', eventImage = '$imageLocation' WHERE id = '$id'";
$result = mysql_query($query) or die ("Error in query: $query. " . mysql_error());
// set up error list array
$errorList = array();
$count = 0;
// validate text input fields
if (!$eventTitle) { $errorList[] = "Invalid entry: Title"; $count++; }
if (!$eventInfo) { $errorList[] = "Invalid entry: Info"; $count++; }
// check for errors
// if none found...
if (sizeof($errorList) == 0)
{
// print result
	echo "Update successful! <a href=intro.php>Go back to the Welcome page.</a>.";
// close database connection
	mysql_close($connection);
}
else
{
// errors found
// print as list
	echo "The following errors were encountered: <br>";
	echo "<ul>";
	for ($x=0; $x<sizeof($errorList); $x++)
	{
		echo "<li>$errorList[$x]";
	}
	echo "</ul>";
}
}
?>
</body>

Link to comment
Share on other sites

Make sure all your ELSE's have a IF before it.

 

Now, there's a Parse error: parse error, unexpected T_ELSE in /home/sites/site19/web/mucci/update/eventsEdit.php on line 82

 

I checked closed brackets and missing ;s but I couldn't see what what wrong.

 

Link to comment
Share on other sites

I must be missing one (or you wouldn't have pointed me in that direction, I'm thinking)...I can't seem to find it.

 

There's:

if the submit button is pushed, update database else print error

if the image is in the directory, display the name else display "no image selected"

if error list is empty, print "update is successful" else print the errors

 

Am I missing one? The error points to an else, so it would make sense that it's a missing "if"...or maybe the else is in the wrong spot?

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.