Log in

View Full Version : working w/ code that searches mySQL db but want to update as well



?foru
02-14-2009, 04:23 AM
I am working with a mySQL database and there are 4 fields at the moment. The script works to search the database, and I adapted it to display the results in form fields so the values can be changed to update the records. My issue is where to incorporate the UPDATE statement in the following code.


<html>
<head>
<title>database search script</title>
</head>
<body>
<form name="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
<input type="text" name="q" />
<input type="submit" name="Submit" value="Search" />
</form>
<?php
//set your table name here
$table_name="your_data";

// Get the search variable from URL
$var = @$_GET['q'] ;
$trimmed = trim($var); //trim whitespace from the stored variable
// rows to return
$limit=10;
// check for an empty string and display a message.
if ($trimmed == "")
{
echo "<p>Please enter a search...</p>";
exit;
}

// check for a search parameter
if (!isset($var))
{
echo "<p>We dont seem to have a search parameter!</p>";
exit;
}
//connect to your database ** EDIT REQUIRED HERE **
mysql_connect("your_host", "your_username","your_password"); //(host, username, password)

//specify database ** EDIT REQUIRED HERE **
mysql_select_db("your_databasename") or die("Unable to select database"); //select which database we're using

// Build SQL Query
$query = "select * from $table_name where tn like \"%$trimmed%\"
order by tn"; // EDIT HERE and specify your table and field names for the SQL query

$query2 = "select * from $table_name where fqdn like \"%$trimmed%\"
order by fqdn"; // EDIT HERE and specify your table and field names for the SQL query

$numresults=mysql_query($query);
$numrows=mysql_num_rows($numresults);

$numresults2=mysql_query($query2);
$numrows=mysql_num_rows($numresults2);

// no results
if ($numrows == 0)
{
echo "Results<br>";
echo "<p>Your search for: &quot;" . $trimmed . "&quot; returned zero results</p>";
}

// next determine if s has been passed to script, if not use 0
if (empty($s)) {
$s=0;
}

// get results
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");

$query2 .= " limit $s,$limit";
$result2 = mysql_query($query2) or die("Couldn't execute query");

// display what the person searched for
echo "<p>You searched for: &quot;" . $var . "&quot;</p>";

// begin to show results set
echo "Results<br>";
$count = 1 + $s ;

// now you can display the results returned
while ($row= mysql_fetch_array($result) OR ($row= mysql_fetch_array($result2))) {
$tn = $row["tn"];
$acct_number = $row["acct_number"];
$port = $row["port"];
$fqdn = $row["fqdn"];

echo "<form><table cellspacing=\"0\" cellpadding=\"3\" rules=\"all\" bordercolor=\"Black\" border=\"1\" style=\"border-color:Black;border-width:1px;border-style:solid;font-family:Verdana;font-size:8pt;border-collapse:collapse;\">
<tr>
<td>TN</td>
<td>AccountNumber</td>
<td>Port</td>
<td>FQDN Domain</td>
</tr>
<tr>
<td><input name=\"tn\" type=\"text\" id=\"tn\" value=\"$tn\" size=\"15\"></td>
<td><input name=\"acct_number\" type=\"text\" id=\"acct_number\" value=\"$acct_number\" size=\"17\"></td>
<td><input name=\"port\" type=\"text\" id=\"port\" value=\"$port\" size=\"2\"></td>
<td><input name=\"fqdn\" type=\"text\" id=\"fqdn\" value=\"$fqdn\" size=\"30\"></td>
</tr><input type=\"submit\" name=\"Update\" value=\"Update Database\" />
</table></form>" ;

$count++ ;
}

$currPage = (($s/$limit) + 1);

//break before paging
echo "<br />";

// next we need to do the links to other results
if ($s>=1) { // bypass PREV link if s is 0
$prevs=($s-$limit);
print "&nbsp;<a href=\"$PHP_SELF?s=$prevs&q=$var\">&lt;&lt;
Prev 10</a>&nbsp&nbsp;";
}

// calculate number of pages needing links
$pages=intval($numrows/$limit);

// $pages now contains int of pages needed unless there is a remainder from division

if ($numrows%$limit) {
// has remainder so add one page
$pages++;
}

// check to see if last page
if (!((($s+$limit)/$limit)==$pages) && $pages!=1) {

// not last page so give NEXT link
$news=$s+$limit;

echo "&nbsp;<a href=\"$PHP_SELF?s=$news&q=$var\">Next 10 &gt;&gt;</a>";
}

$a = $s + ($limit) ;
if ($a > $numrows) { $a = $numrows ; }
$b = $s + 1 ;
echo "<p>Showing results $b to $a of $numrows</p>";
?>
</body>
</html>

I've worked with UPDATE on something else but it was where ALL the records were pulled with a "while" loop then you had to choose which one to update from a long list.

I'll need to see if "submit" was hit to be able to run the update

$sql="UPDATE $tbl_name SET tn='$tn', acct_number='$acct_number', port='$port', fqdn='$fqdn'";
Thank you for any help!

fobos
02-15-2009, 02:16 AM
?foru,
just to verify, you want to have an update next to the displayed results?

ex. Results..

Results "update"
Results "update"
Results "update"
Results "update"

then when you click on "update" it takes you to a form where you can change the values of that result, then submit the form to update the values?

please let me know if this is correct

?foru
02-15-2009, 08:08 PM
Thank you for your reply fobos. Yes, that's correct.

On another project I used the following
I think the end bracket right above if ($_POST["$submit"]) closed the while loop since all the results were displayed for that scenario.

<a href=\"$PHP_SELF?cmd=edit&tn=$tn\">Update</a>

cmd=edit was passed to the URL and it jumped to the "form" portion of my code which was...


<? //edit individual items//////////////////////////////////////////
if($_GET["cmd"]=="edit" || $_POST["cmd"]=="edit")
{
if (!isset($_POST["submit"]))
{
$tn = $_GET["tn"];
$sql = "SELECT * FROM $tbl_name WHERE tn=$tn";
$result = mysql_query($sql);
$myrow = mysql_fetch_array($result);
?>
<br />
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type=hidden name="id" value="<?php echo $myrow["id"] ?>">

Name:<br><INPUT TYPE="TEXT" NAME="name" VALUE="<?php echo $myrow["tn"] ?>" SIZE=30><br><br>
Email:<br><INPUT TYPE="TEXT" NAME="email" VALUE="<? echo $myrow["acct_number"] ?>"SIZE=30><br><br>
Testimonial:<br><TEXTAREA NAME="testimonial" ROWS=10 COLS=45><? echo $myrow["port"] ?></TEXTAREA><br><br>
Status:<br><INPUT TYPE="TEXT" NAME="status" VALUE="<?php echo $myrow["fqdn"] ?>" SIZE=4> <a href="index.php?cmd=delete&id=<?php echo $myrow["id"] ?>" onClick="javascript:return confirm('Are you sure you want to delete this item ? It cannot be undone')">delete this item from the database</a><br>Set the status to 2 if you want a testimonial to show.<br>Set the status to 1 if you do not want it to show.<br>

<input type="hidden" name="cmd" value="edit">

<input type="submit" name="submit" value="submit">

</form>

<? } ?>
<?
if ($_POST["$submit"])
{
$tn = $_POST["tn"];
$acct_number = $_POST["acct_number"];
$port = $_POST["port"];
$fqdn = $_POST["fqdn"];

$sql = "UPDATE $tbl_name SET tn='$tn',acct_number='$acct_number',port='$port',fqdn='$fqdn'";
//replace news with your table name above
$result = mysql_query($sql);
echo "<BR><BR><table><tr><td class='confirm'>Thank you! Information updated.</td></tr></table>";
echo "<BR><BR>";
echo "<a href='test_search.php'>Update another record</a>";
}
}

?>

In the other project it was all contained within the same page so the user wasn't forced to jump around which was nice. I have tried many things but when I go to edit it takes me right back to the empty search form.

Thank you for any help, and if we can get a working solution I'm sure others would find this to be useful for something they're working on.

fobos
02-15-2009, 11:02 PM
well lucky for you i use what you are looking for, except when they click on "update" i go to another page, but i will give you what i have.
this is all on one page, displayed in order. Please let me know if this doesnt work.

Information that is displayed in table with Update and delete.


<?php
mysql_connect("host","user","pass");
mysql_select_db("db");
$color1 = ""; // color of row 1
$color2 = "#FFFFFF";// color of row 2
$row_count = 0;
$result = mysql_query("SELECT * FROM tblname ORDER BY whatever");
while($row = mysql_fetch_array($result)) {
$row_color = ($row_count % 2) ? $color1 : $color2; //alternate row color
$row_count++;
$id = $row['id']; // gets the id for the row that you want to edit when you click "update"
echo"
<table cellSpacing='0' cellPadding='0' width='100%' border='0'>
<tbody>
<tr bgcolor='$row_color'>
<td>Name:</td>
<td>Email:</td>
<td>Testimonial:</td>
<td>Status:</td>
<td><a href=\"page.php?id=$id\">Update</a></td>
<td><a onClick=\"return confirm("Are You Sure?")\" href=\"page.php?action=del&id=$id\">Delete</a></td>
</tr>
</tbody>
</table>";// closing of echo
}
if($_REQUEST['action']=="del") {
mysql_query("DELETE FROM $table WHERE id={$_REQUEST['id']};");
}
?>


The update form


<?php
$con = mysql_connect("host","user","pass");
if(!$con) {
die('Could not connect: ' . myslq_error());
}
mysql_select_db("db", $con);
$sql = "SELECT * FROM table WHERE id=$_GET[id]"; // gets in id and table name from Update click
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
?>
<form action="page.php" method="post">
<table cellSpacing="0" cellPadding="3" width="100%" border="0">
<tbody>
<tr>
<td>ID:</td>
<td><input size="65" type="text" name="id" value"<?php echo $row['id'] ?>"></td>
</tr>
<tr>
<td>Name:</td>
<td><input size="65" type="text" name="tn" value"<?php echo $row['tn'] ?>"></td>
</tr>
<tr>
<td>Email:</td>
<td><input size="65" type="text" name="acct_number" value"<?php echo $row['acct_number'] ?>"></td>
</tr><tr>
<td>Testimonial:</td>
<td><input size="65" type="text" name="port" value"<?php echo $row['port'] ?>"></td>
</tr><tr>
<td>Status:</td>
<td><input size="65" type="text" name="fqdn" value"<?php echo $row['fqdn'] ?>"></td>
</tr>
<tr>
<td>Submit</td>
<td><input type="submit" name="submit" value="Submit"></td>
</tr>
</tbody>
</table>


The submit section


<?php
if(isset($_POST['submit'])) {
$con = mysql_connect("host","user","pass");
if(!$con) {
die('Could not connect: ' . myslq_error());
}
mysql_select_db("db", $con);
mysql_query("UPDATE table SET tn = '$_POST[tn]', acct_number = '$_POST[acct_number]', port = '$_POST[port]', fqdn= '$_POST[fqdn]' WHERE id = '$_POST[id]'");
mysql_close($con);
}
?>

?foru
02-19-2009, 02:21 AM
Sorry for the delayed reply. I haven't had as much time to work with this as I would like to.

On the page that will send the info to update.php I used update.php?id=".$row["id"]." because this was already echo'ed in PHP and that works fine to give me update.php?id=5 in the browser for the update.php page. The issue is getting the values into the fields to update the database.

For update.php I also tried to just echo the variables like...<? echo "$tn"; ?> after I turned them into a variable like...$tn=$row["tn"]; and that didn't work either.

update.php connects to the database and gets the id passed through the URL but doesn't grab the info from that row. I've tried everything I can think of but can't seem to get it to work.

?foru
02-19-2009, 03:36 AM
When I've done updates to databases in the past there hasn't been many records at all so it displays all rows approx 10 or less. With this there will be too many records so I only need the data from that specific id row.

I found the following and tried that also and it didn't work...


while(list($id,$tn,$acct_number,$port,$fqdn)= mysql_fetch_row($result))
{
echo "ID :$id <br>" .
.....
.......
}

Please let me know if anyone has any ideas. Thank you.

fobos
02-21-2009, 09:21 PM
?foru,
Just want to make sure. This code works for me, i tested it before i gave it to you.
Make sure that you put all this code onto one page, and yes this will update the row that was selected only.

?foru
02-24-2009, 06:56 PM
Yeah, I put the 3 sections on top of each other in order in the same page, but it isn't working for some reason. I did have to escape the quotes in line 21 though (\"Are You Sure?\") since it gave a parsing error.

When I pass the id in the URL to page.php I only get the middle section of code which is the form and its blank.

?foru
02-25-2009, 03:55 AM
I did spot an extra space in the part of the connection code which I caught after I added
or die (mysql_error ()); after the mysql_connect statement. For some reason when I clicked on "Update" it didn't fill out the form. Fobos I appreciate you posting the code you did, maybe different php version or something odd.

I was able to get this to work though, but I noticed for some reason the fqdn field isn't updating. The fqdn field is set as text in mySQL and will contain letters numbers and periods. I noticed that when a record is updated regardless of if the fqdn is changed or not that info is being deleted.

fqdn is the fully qualified domain name and would look something like this...
00131148DCBA.area.domain.com

from form

<input type="text" name=="fqdn" value="<?php echo $myrow["fqdn"] ?>" size=35>

Update statement


$tn = $_POST["tn"];
$acct_number = $_POST["acct_number"];
$port = $_POST["port"];
$fqdn = $_POST["fqdn"];

$sql = "UPDATE toast_data SET tn='$tn', acct_number='$acct_number', port='$port', fqdn='$fqdn' WHERE id=$id";

Does anyone have any suggestions or ideas on why a text field would be deleted when the information around it is updating correctly? I really appreciate it.

JasonDFR
02-25-2009, 07:21 AM
<input type="text" name=="fqdn" value="<?php echo $myrow["fqdn"] ?>" size=35>

You have two == after name.

So by the time $fqdn got into your query, it was equal to nothing. The UPDATE query didn't delete anything, it just changed the value to what the query was telling it to.

Have you tried echoing $_POST['fqdn'] in the form processing part of the script? Always try echoing the information being posted. This is a great debugging technique.

Also, validate your (X)HTML. http://validator.w3.org/ It will catch errors like the one you have.

Also, use php to validate the information from your form before processing it.


if ( empty($_POST['fqdn']) )
echo 'fqdn is required';

?foru
02-25-2009, 06:57 PM
Thank you for taking a look JasonDFR. I clearly missed the == after name. I changed that and it works now. Your explanation makes sense so thank you for that as well and for the additional tips because I wasn't echoing $_POST (definitely worth keeping in mind).

I normally always have
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org..."><html xmlns="http://www.w3.org/1999/xhtml"> in my page although I didn't have it along with proper /> tags in this one. I will be taking the php code out and placing it into a page already setup with a stylesheet...etc.

Once I know that no other fields will be needed I can go in and add the validation. Thank you again for the help :)

?foru
02-26-2009, 02:33 AM
One other quick question...not sure where to put validation because it is showing "fqdn required" whether or not it was blank when I put it above this code section listed below?


<?
if($_GET["cmd"]=="edit" || $_POST["cmd"]=="edit")
{
// I THINK I NEED TO ADD IT HERE...I TRIED BUT COULDN'T GET THE SYNTAX CORRECT
if (!isset($_POST["submit"]))
{
$id = $_GET["id"];
$sql = "SELECT * FROM toast_data WHERE id=$id";
$result = mysql_query($sql);
$myrow = mysql_fetch_array($result);
?>
<br />
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
.......REST OF FORM HERE...................
<input type="hidden" name="cmd" value="edit">
<input type="submit" name="submit" value="submit">
</form>

<? } ?>
<?
if ($_POST["$submit"])
{
$tn = $_POST["tn"];
$acct_number = $_POST["acct_number"];
$port = $_POST["port"];
$fqdn = $_POST["fqdn"];

$sql = "UPDATE toast_data SET tn='$tn', acct_number='$acct_number', port='$port', fqdn='$fqdn' WHERE id=$id";
$result = mysql_query($sql);
echo "<BR><BR><table><tr><td class='confirm'>Thank you! Information updated.</td></tr></table>";
echo "<BR><BR>";
echo "<a href='". $_SERVER['PHP_SELF']. "'>Update another record</a>";
}
}
?>

Thank you

fobos
02-26-2009, 05:09 AM
im sorry you did bring out a couple of mistakes that i had.
1) this is the correct way to display your table.


<tr bgcolor='$row_color'>
<td>".$row['tn']."</td>
<td>".$row['acct_number']."</td>
<td>".$row['port']."</td>
<td>".$row['fqdn']."</td>
<td><a href=\"page.php?id=$id\">Update</a></td>
<td><a onClick=\"return confirm("Are You Sure?")\" href=\"page.php?action=del&id=$id\">Delete</a></td>
</tr>


2) In this one i had "$table", but just put your table name there


if($_REQUEST['action']=="del") {
mysql_query("DELETE FROM tablename WHERE id={$_REQUEST['id']};");
}


And yes there shouldnt be (2) == signs because that would mean nothing

JasonDFR
02-26-2009, 07:12 AM
Since you need values for $tn, $acct_number, $port, and $fqdn before you update your database, you should validate them, 1. After they have been posted, 2 before you query the DB. So:
if ($_POST["$submit"])
{

// I'd do some validation here.

$tn = $_POST["tn"];
$acct_number = $_POST["acct_number"];
$port = $_POST["port"];
$fqdn = $_POST["fqdn"];

$sql = "UPDATE toast_data SET tn='$tn', acct_number='$acct_number', port='$port', fqdn='$fqdn' WHERE id=$id";
$result = mysql_query($sql);
echo "<BR><BR><table><tr><td class='confirm'>Thank you! Information updated.</td></tr></table>";
echo "<BR><BR>";
echo "<a href='". $_SERVER['PHP_SELF']. "'>Update another record</a>";
}
}

First decide what is important about each piece of information being entered.

For example, none of your values can == '' ( nothing ). So test for that.
Are all $acct_numbers numeric? If so, make sure it is numeric. If all $acct_numbers follow a certain pattern, check them against a regular expression.
And make sure the values are safe to enter into the db.

If you need help figuring out how to validate these values, start another thread titled form validation or something like that and ask your questions there. It's better for people searching the forms for stuff about validation and really is a different topic than this thread.

Good luck.

J

?foru
02-27-2009, 01:34 AM
No worries at all fobos, I appreciate you posting what you had. For the update script I am going to pass the id from the search page so I won't need to display the records on the update page but I'm sure someone will put it to good use.

J that is correct the account #'s are only numeric values in this case, and those won't really be changed but they are mainly used to see if multiple pieces of equipment are tied to an account.

The validation works, but I will create a thread to see about stopping the script execution because after the echo the sql statement runs and updates. Thank you both!