Hello Everyone,

I am a bit new at programming so please go lightly on me 🙂 I am trying to make an auto complete textbox from a mysql table called form test with two fields, id and name, and have had success. Herein lies the problem. I would like to be able to edit that field with the autocomplete information as well. The edit form works however, it does not show any autocomplete suggestions like I would have hoped for.

I will post the code and files below. Any help would be greatly appreciated. Also before I get flamed on no injection protection I understand that, I am just trying to get the basics working before adding protection.

Thank you all very much!

Here is my testadd.php form

<html>
<head>
     <script type="text/javascript"
        src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script type="text/javascript"
        src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
        <link rel="stylesheet" type="text/css"
        href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />

    <script type="text/javascript">
            $(document).ready(function(){
                $("#name").autocomplete({
                    source:'testgetautocomplete.php',
                    minLength:1
                });
            });
    </script>
</head>



<!----- Start Add Form ------>
<?php
    include_once('db.php');

if(isset($_POST['name'])
)
{
 $name = $_POST['name'];       

 ?>

  <?php 
  if(mysql_query("INSERT INTO formtest VALUES('','$name')"))
	echo "Boat type $name Created and Added Successfully!";
  else
	echo "Oops! There was a problem. Please try again. If you have seen this error more than once please call UYS Support and tell them: ".mysql_error();
}
?>

<?php


$res = mysql_query("SELECT * FROM formtest ORDER BY name");


?>

<form action="testadd.php" method="POST">
<br />
<br />
<br />
<br />
<h1>Add a New User</h1>
<table class="center">
<tr>
<td>Enter a New Name: </td><td><input type="text" id="name" name="name" /></td>
</tr>
<tr>

<td></td><td><input type="submit" value=" Add >>> "/></td>
</tr>
</table>
</form>

<!----- End Add Form ------>

<!----- Start Table List ------>

<h1>Existing Names</h1>
<table class="results">

<?php


/* ********* Table Headers ********** */

  echo "<tr>";

  echo "<td>" . " " . "</td>";
  echo "<td>" . "ID" . "</td>";
  echo "<td>" . "Name" . "</td>";
  echo "<td>" . " " . "</td>";

  echo "</tr>"; 

/* ********* Table data loop ********* */

while( $row = mysql_fetch_array($res)) {

  echo "<tr>";
  echo "<td>" . "<a href='testedit.php?edit=$row[id]'>Edit</a>" . "</td>";
  echo "<td>" . $row[id] . "</td>";  
   echo "<td>" . $row[name] . "</td>";       
   echo "</tr>";  

   }
?>
</table>

<!----- End Table List ------>


</body>
</html>

testgetautocomplete.php form code is: (password and db info left out obviously 🙂

<?php
 mysql_connect('localhost', ' ', ' ');
 mysql_select_db(" ");

 $term=$_GET["term"];

 $query=mysql_query("SELECT * FROM formtest where name like '%".$term."%' order by name ");
 $json=array();

while($student=mysql_fetch_array($query)){
     $json[]=array(
                'value'=> $student["name"],
                'label'=>$student["name"]." - ".$student["id"]
                    );
}

 echo json_encode($json);

?>

testedit.php form code is as follows:

<html>
<head>

 <script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript"
    src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
    <link rel="stylesheet" type="text/css"
    href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />

    <script type="text/javascript">
            $(document).ready(function(){
                $("#newname").autocomplete({
                    source:'testgetautocomplete.php',
                    minLength:1
                });
            });
    </script>


<title>UYS Edit Page</title>



</head>

<body>



<!----- Start Edit Form ------>

<?php

include_once('db.php');



if( isset($_GET['edit']) )

{

	$id = $_GET['edit'];

	$res= mysql_query("SELECT * FROM formtest WHERE id='$id'");

	$row= mysql_fetch_array($res);

}



if( isset($_POST['newname']))

{

	$newname = $_POST['newname'];



    $id  	 = $_POST['id'];

	$sql     = "UPDATE formtest SET name='$newname' WHERE id='$id'";

	$res 	 = mysql_query($sql)

                                or die("Could not update".mysql_error());

	echo "<meta http-equiv='refresh' content='0;url=testadd.php'>";

}



?>

<table class="centerwithroom">

<form action="testedit.php" method="POST">

<tr>

<td>New Name </td><td><input type="text" name="newname" value="<?php echo $row[1]; ?>"/></td>

</tr>


<td></td><td><input type="submit" value=" Update "/></td>

</tr>

<input type="hidden" name="id" value="<?php echo $row[0]; ?>"/>


</form>
</table>

<!----- End Edit Form ------>


</body>
</html>

    sorry, i have jquery on the brain as well lol. I meant javascript + php question 🙂

      Have you tried accessing each of your PHP pages in your browser to make sure they all work? I.e., are you sure there are no mistakes in your code?

      Also, that Jquery "autocomplete" function looks like a bit of a black box. Are you sure you have referenced all the appropriate javascript files? I don't think "autocomplete" is part of the basic jquery library.

        sneakyimp;11034811 wrote:

        Have you tried accessing each of your PHP pages in your browser to make sure they all work? I.e., are you sure there are no mistakes in your code?

        Also, that Jquery "autocomplete" function looks like a bit of a black box. Are you sure you have referenced all the appropriate javascript files? I don't think "autocomplete" is part of the basic jquery library.

        All pages work correctly, and I meant to say javascript, thus my reply to my thread 🙂

          if "All pages work correctly" then you have no problem, right? 😉

            seriously? can you help or just troll with rhetorical questions?

              The point I'm trying to make is that you need to be more exact in your descriptions of what is happening. "It doesn't work" doesn't tell us anything about what you have tried or what is failing.

              In your case, you say that "all pages work correctly" which is almost as bad. What, exactly, did you try and what was the response? E.g., "I loaded testgetautocomplete.php in my browser and got nothing but a blank page" would be more helpful.

              I looked quickly at the jquery UI autocomplete page and it does not appear to have any javascript references beyond what you have so I think your JS and CSS look OK. I did notice a couple of things:
              You don't include a <div> tag with class="ui-widget" like the example there.
              You don't have a label for your text input
              * The id that you refer to in testedit.php when you try to set up your autocomplete ("#newname") does not match the id of any inputs in your HTML. your autocomplete text input should have an id="newname".

                Also, this code kinda sucks. You call all these mysql commands (read the link in my signature about not using mysql) without even checking whether the commands worked or returned an error:

                 <?php
                 mysql_connect('localhost', ' ', ' ');
                 mysql_select_db(" ");
                
                 $term=$_GET["term"];
                
                 $query=mysql_query("SELECT * FROM formtest where name like '%".$term."%' order by name ");
                 $json=array();
                
                while($student=mysql_fetch_array($query)){
                     $json[]=array(
                                'value'=> $student["name"],
                                'label'=>$student["name"]." - ".$student["id"]
                                    );
                }
                
                 echo json_encode($json);
                
                ?> 

                  sorry for my lack of clarity. as i stated i am new to programming 🙂 i have given up on this anyhow and and moving on to just simply trying to have a dropdown list that pulls names from a names table as the selector in my php edit form. if you know anything in that area i could try to be as specific as possible? 🙂

                    The first trick is to get the names from a table. That's pretty basic. Try reading the examples for [man]mysqli_query[/man] and you should be able to get it working. REMEMBER TO CHECK FOR ERRORS when you try to connect, when you run a query, etc. If there's a problem with your SQL, it will help you figure out what the problem is.

                    Also check to make sure any results are returned. Your query might not return any results.

                      Thanks for the direction. I need to get up to date on mysqli, being self taught I didn't even know about it until I saw your signature. Knowing in advance my code is sloppy and I have a long way to go, can you see my problem in this code? I will try to be as descriptive as possible.

                      I have two mysql tables, one called brokerlist with two fields id and name. the second table is called boatlist with three fields id, brokername, and boatname. The brokername field contains the value of the brokerlist.id field and a text entered boatname.

                      I have created php add-forms to add data to both tables that are working properly. I have created a php edit form with text boxes to edit the brokerlist table that works properly. My problem lies in the form I call testeditboat.php. What I am trying to do is allow the user to change the field brokername in the testeditboat.php form with a dropdown box that populates from the mysql table called brokerlist but also uses the select selected to show the current entry first.

                      Where my form currently stands is it submits the request and will change any value in the boatname field, but will not update the brokername field.

                      Thank you all in advance very much for your help, I hope I have been descriptive enough.

                      <?php
                      
                      include_once('db.php');
                      
                      
                      
                      if( isset($_GET['edit']) )
                      
                      {
                      
                      	$id = $_GET['edit'];
                      
                      	$res= mysql_query("SELECT * FROM boatlist WHERE id='$id'");
                      
                      	$row= mysql_fetch_array($res);        
                      
                          $brokerlistquery = mysql_query("SELECT * FROM brokerlist");
                      
                       }
                      
                      
                      
                      if( isset($_POST['newbrokername']) &&
                          isset($_POST['newboatname']))
                      
                      {
                      
                      	$newbrokername = $_POST['newbrokername'];
                          $newboatname = $_POST['newboatname'];
                      
                      
                      
                          $id  	 = $_POST['id'];
                      
                      	$sql     = "UPDATE boatlist SET brokername='$newbrokername', boatname='$newboatname' WHERE id='$id'";
                      
                      	$res 	 = mysql_query($sql)
                      
                                                      or die("Could not update".mysql_error());
                      
                      	echo "<meta http-equiv='refresh' content='0;url=testaddboat.php'>";
                      
                      }
                      
                      
                      
                      ?>
                      
                      <table class="centerwithroom">
                      
                      <form action="testeditboat.php" method="POST">
                      
                      <tr>
                      
                      
                      
                      
                      <td>New Broker Name </td><td>
                      <select name='newbrokername'>
                        <?php
                          while ($brokerlistrow = mysql_fetch_array($brokerlistquery)) {
                        ?>
                      <option value="<?php echo $row[brokername]; ?>" <?php if ($row[brokername] == $brokerlistrow[id]) { echo selected; } ?> ><?php echo $brokerlistrow[name]; ?></option>
                      <?php } ?> </select>
                      </td>
                      
                      <tr>
                      <td>Boat Name:</td><td><input type="text" name="newboatname" value="<?php echo $row[boatname]; ?>"/></td>
                      </tr>
                      
                      
                      </tr>
                      
                      <td></td><td><input type="submit" value=" Update "/></td>
                      
                      </tr>
                      
                      <input type="hidden" name="id" value="<?php echo $row[id]; ?>"/>
                      
                      
                      </form>
                      </table>

                        Hello, and welcome to PHPBuilder.

                        Please try and use the [noparse]

                        [/noparse] tags around your code; this can help us in debugging due to its syntax highlighting, and it keep the page length shorter in the event code excerpts are very long.

                        stvnkrs10;11034839 wrote:

                        Thanks for the direction. I need to get up to date on mysqli, being self taught I didn't even know about it until I saw your signature.

                        In its most basic form, it's replacing "mysql" with "mysqli" in all your function calls and adding the connection identifier as a first parameter to them:

                        //OLD
                        $conn = mysql_connect($host,$user,$pass);
                        $sel = mysql_select_db($dbname);
                        $sql = "select foo from bar;";
                        $res = mysql_query($sql);
                        
                        //NEW
                        $conn = mysqli_connect($host,$user,$pass,$dbname); // no more need for "select_db" for the initial connection
                        $sql = "select foo from bar;";
                        $res = mysqli_query($conn,$sql); //first param necessary; this allows for easy management of multiple connections.
                        

                        MySQLi is also[SUP][/SUP] object-oriented, so the "New" example above could be written as:

                        $conn = new Mysqli($host,$user,$pass,$dbname);
                        $sql = "select foo from bar;";
                        $res = $conn->query($sql); //first param NOT necessary, because you've specified the object initiated above.
                        

                        [SUP]*[/SUP]I'd say "finally object-oriented", but as the mysqli extension is nearing its tenth birthday, that hardly seems logical or fair to PHP...

                        Where my form currently stands is it submits the request and will change any value in the boatname field, but will not update the brokername field.

                        It appears to me via casual inspection that this line:

                        <option value="<?php echo $row[brokername]; ?>" <?php if ($row[brokername] == $brokerlistrow[id]) { echo selected; } ?> ><?php echo $brokerlistrow[name]; ?></option>

                        Will not product HTML source with a

                        name='brokername'

                        attribute; this would be a possible explanation for your problem.

                          Excellent. Thank you kindly for both of your replies! I went and bought a mysqli book to begin reading over the weekend to get me up to speed. I have tried a couple things and am pretty close to a solution, I think 🙂

                          I changed the line above to:

                          <option value="<?php echo $brokerlistrow[name]; ?>" <?php if ($row[brokername] == $brokerlistrow[id]) { echo selected; } ?> ><?php echo $brokerlistrow[name]; ?></option>
                          <?php } ?> </select>

                          Now it shows the correct selected value as first in the list and when I submit, it saves the actual physical name as opposed to the id associated with the name. Any ideas how to get the value from the id.brokerlist to save as opposed to the name.brokerlist?

                          Here is my complete edit code wrapped in the tags as you suggested 🙂

                          
                          <?php
                          
                          include_once('db.php');     
                          
                          if(isset($_GET['edit']))
                          
                          {
                          
                          $id = $_GET['edit']; 
                          
                          $res= mysql_query("SELECT * FROM boatlist WHERE id='$id'"); 
                          
                          $row= mysql_fetch_array($res);   
                          
                          $brokerlistquery = mysql_query("SELECT * FROM brokerlist");
                          
                          print_r($row);
                          
                          }
                          
                          
                          if( isset($_POST['newbrokername']) && isset($_POST['newboatname']))    
                             {    
                               $newbrokername = $_POST['newbrokername'];
                               $newboatname = $_POST['newboatname'];     
                               $id= $_POST['id'];
                          
                               $sql = "UPDATE boatlist SET brokername='$newbrokername', boatname='$newboatname' WHERE id='$id'";
                          
                               $res= mysql_query($sql) or die("Could not update".mysql_error());
                          
                               echo "<meta http-equiv='refresh' content='0;url=testaddboat.php'>";
                          
                          }
                          
                          
                          
                          ?>
                          
                          <table class="centerwithroom">    
                          <form action="testeditboat.php" method="POST">
                          <tr>
                          <td>New Broker Name </td><td> <select name='newbrokername'> <?php while ($brokerlistrow = mysql_fetch_array($brokerlistquery)) { ?> <option value="<?php echo $brokerlistrow[name]; ?>" <?php if ($row[brokername] == $brokerlistrow[id]) { echo selected; } ?> ><?php echo $brokerlistrow[name]; ?></option> <?php } ?> </select> </td> <tr> <td>Boat Name:</td><td><input type="text" name="newboatname" value="<?php echo $row[boatname]; ?>"/></td> </tr> </tr> <td></td><td><input type="submit" value=" Update "/></td> </tr> <input type="hidden" name="id" value="<?php echo $row[id]; ?>"/> </form> </table>

                            also i forgot to include the result of the print_r($row) is Array ( [0] => 4 [id] => 4 [1] => 6 [brokername] => 6 [2] => Kims Boat [boatname] => Kims Boat )

                            just in case it helps 🙂

                              the correct brokerlist.id is 6 for this selected name.

                                by changing the row to

                                <option value="<?php echo $brokerlistrow[id]; ?>" <?php if ($row[brokername] == $brokerlistrow[id]) { echo selected; } ?> ><?php echo $brokerlistrow[name]; ?></option>
                                <?php } ?> </select>

                                it now all works correctly, thank you all for your guidance, now on to mysqli changes 🙂

                                  Please please please always use the

                                   tags around your code.
                                  
                                  When referring to an element of an associative array like $row[brokername], you should put the associative key ("brokername" in this case) in either single or double quotes:
                                  [code=php] echo $brokerlistrow["id"];

                                    thank you again for all the advice imp! i will change that asap. when yo have time could you tell me why? is it for parsing of the variable or are there other reasons as well? 🙂

                                      You should use quotes because it's proper syntax. While PHP will work if you don't use the quotes, it results in an error of type E_NOTICE being thrown. For example, this script creates an associative array and tries to refer to it without using quotes:

                                      <?php
                                      $v = array("key" => "here is my value");
                                      echo $v[key];
                                      ?>
                                      

                                      It does output the value, but the script throws an error saying that it sees an "unexpected constant". Here's the output:

                                      PHP Notice:  Use of undefined constant key - assumed 'key' in /var/www/foo.php on line 4
                                      PHP Stack trace:
                                      PHP   1. {main}() /var/www/foo.php:0
                                      here is my value
                                      

                                        EDIT: Woops, disregard... where did that second page come from?! :o