Page 1 of 2 12 LastLast
Results 1 to 10 of 15

Thread: working w/ code that searches mySQL db but want to update as well

  1. #1
    Join Date
    Jul 2008
    Posts
    138
    Thanks
    13
    Thanked 1 Time in 1 Post

    Default working w/ code that searches mySQL db but want to update as well

    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.

    PHP 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 $s ;

    // now you can display the results returned
      
    while ($rowmysql_fetch_array($result) OR ($rowmysql_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 ;
      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
    PHP Code:
    $sql="UPDATE $tbl_name SET tn='$tn', acct_number='$acct_number', port='$port', fqdn='$fqdn'"
    Thank you for any help!

  2. #2
    Join Date
    Oct 2008
    Posts
    60
    Thanks
    2
    Thanked 7 Times in 7 Posts

    Default working w/ code that searches mySQL db but want to update as well

    ?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

  3. #3
    Join Date
    Jul 2008
    Posts
    138
    Thanks
    13
    Thanked 1 Time in 1 Post

    Default

    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.
    Code:
    <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...

    PHP Code:
    <? //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.

  4. #4
    Join Date
    Oct 2008
    Posts
    60
    Thanks
    2
    Thanked 7 Times in 7 Posts

    Default working w/ code that searches mySQL db but want to update as well

    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 Code:
    <?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 Code:
    <?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 Code:
    <?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);
    }
    ?>

  5. #5
    Join Date
    Jul 2008
    Posts
    138
    Thanks
    13
    Thanked 1 Time in 1 Post

    Default

    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.

  6. #6
    Join Date
    Jul 2008
    Posts
    138
    Thanks
    13
    Thanked 1 Time in 1 Post

    Default

    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...
    PHP Code:
    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.

  7. #7
    Join Date
    Oct 2008
    Posts
    60
    Thanks
    2
    Thanked 7 Times in 7 Posts

    Default

    ?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.

  8. #8
    Join Date
    Jul 2008
    Posts
    138
    Thanks
    13
    Thanked 1 Time in 1 Post

    Default

    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.

  9. #9
    Join Date
    Jul 2008
    Posts
    138
    Thanks
    13
    Thanked 1 Time in 1 Post

    Default

    I did spot an extra space in the part of the connection code which I caught after I added
    Code:
    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
    PHP Code:
    <input type="text" name=="fqdn" value="<?php echo $myrow["fqdn"?>" size=35>
    Update statement
    PHP Code:
    $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.

  10. #10
    Join Date
    Apr 2008
    Location
    Limoges, France
    Posts
    395
    Thanks
    13
    Thanked 61 Times in 61 Posts

    Default

    <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.

    PHP Code:
    if ( empty($_POST['fqdn']) )
        echo 
    'fqdn is required'
    Last edited by JasonDFR; 02-25-2009 at 07:38 AM. Reason: I can't spell

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •