I'm totally new to php and learning.

I have a table name persons which has columns

  • FirstName
  • LastName
  • Gender
  • Subject
  • Hobbies

The Task: was to dynamically populate a drop down list with the data of FirstName, display the selected record of the name chosen in the drop down list only and update the last name of the displayed record.

The Problem: I need a better way to this, so far I was not able to update the last of one row only- all the last names would be updated. And the variable $name which carries the value of the selected gives an error "undefined index" when I place it in the IF condition for changing last name at the bottom of the script, so I had to send the value to the submit type button and from there perform the task.

The Question Is the problem happening because of the scope of the variable $name? is there any other better way to do this without using the submit button?

            <!DOCTYPE>
            <html>
            <head>

            <title>Update Data</title>
            </head>

            <body>


            <form name="form_update" method="post">

            <?php
            $con=mysqli_connect("localhost","root","","ismat_db");
            //============== check connection
            if(mysqli_errno($con))
            {
                echo "Can't Connect to mySQL:".mysqli_connect_error();
            }
            else
            {
                echo "Connected to mySQL</br>";
            }
            //==========connection code end

            //==========dynamic drop down start
            echo "<select name= 'FirstName' >";

            echo '<option value="">'.'--- Please Select Person ---'.'</option>';

            $query = mysqli_query($con,"SELECT FirstName FROM persons");

            while($row=mysqli_fetch_array($query))
            {

                 echo "<option value='". $row['FirstName']."'>".$row['FirstName'].'</option>';

            }

            echo '</select>';
            echo '&nbsp;';
            echo '<input type="submit" name="submit" value="Submit"/>';

            //-------------displaying associated row from db

            if(isset($_POST['FirstName'])) //getting name of drop down box which has value that is first name
            {

                    $name = $_POST['FirstName']; //store the name into a variable

                    $chosenname = $name; //store the name into another variable


                    $fetch="SELECT Firstname,LastName,Gender,Subject,Hobbies FROM persons WHERE Firstname = '".$name."'";

                    $result = mysqli_query($con,$fetch);
                    if(!$result)
                    {
                    echo "Error:".(mysqli_error($con));
                    }

                    echo '<table border="1" align="center">'.'<tr>'.'<td align="center">'. 'From Database'. '</td>'.'</tr>'; //Outer table first row

                    //inner table columns
                    echo '<tr>'.'<td>'.'<table border="1">'.'<tr>'.'<td>'.'First Name'.'</td>'.'<td>'.'Last Name'.'</td>'.'<td>'. 'Gender' .'</td>'.'<td>'. 'Subject'. '</td>'.'<td>'. 'Hobbies' .'</td>'.'</tr>';


                    while($data=mysqli_fetch_row($result))  
                        {


                        echo ("<tr><td>$data[0]</td><td>$data[1]</td><td>$data[2]</td><td>$data[3]</td><td>$data[4]</td></tr>");


                        }

                    echo '</table>'.'</td>'.'</tr>'.'</table>';

                    //---------to update last name only

                    echo '<br/>'.'<br/>'.'<br/>';

                    //echo 'First Name:'.'<input type="hidden" name="fn" value="'.$karma.'"/>';
                    echo '<br/>';
                    echo 'Change Last Name:'. '<input type="text" name="updated"/>';
                    echo '<br/>';
                    echo '<input type="submit" name="sub" value="'.$chosenname.'"/>'; //passed the value of the name to the button
                    echo '<br/>';

                    $recieved = "";
                    $ta = "";
                    $fku="";
                    echo '<br/>';


                    if(isset($_POST['sub']))
                {


                            echo '<br/>';

                        //$fku=$_POST['fn'];
                        //echo "hi".$fn;
                        $recieved = $_POST['sub'];
                        echo "Hello:".$recieved; //so first name has been fetched here from the button value
                        echo '<br/>';
                        $ta = $_POST['updated']; //fetched value from text area
                        echo "The Last Name is"." ".$ta;
                        echo '<br/>';
                        $queryu = "UPDATE persons SET LastName ='".$ta."' WHERE FirstName = '".$recieved."'";
                        echo '<br/>';
                            if (!mysqli_query($con,$queryu))
                                {
                                    die('Error: ' . mysqli_error($con));
                                }
                                echo "Last Name is updated in the record with "." " .$ta;

                }   

            }

            ?>
            </form>
            <br/><br/><br/>
            <a href="main.html"> Go back to Main Page </a>
            </body>
            </html>

Recommended Answers

All 2 Replies

First you need to create a primary key id. What if you have 10,000 people in a database , more than likely a few of them will have the same first name. So we can use your primary key id for the selection. Also put an index on id and first name. It makes your queries faster when indexed.

I changed some in your code so you can study what I did. It works as expected on my machine. Also you can read about variable scope in PHP here

Here are my changes:
Line 27 - Added id to the Select
Line 30 - Put $row['id'] into memory.
Line 47 - Selected id again in the query so we can add it to the data array stack at 0 on line 62.

Line 97 Passed $id to the update. This is where it was failing.

<!DOCTYPE>
    <html>
        <head>

            <title>Update Data</title>
        </head>

        <body>


            <form name="form_update" method="post">

                <?php
                $con = mysqli_connect("localhost", "root", "", "ismat_db");
                //============== check connection
                if (mysqli_errno($con)) {
                    echo "Can't Connect to mySQL:" . mysqli_connect_error();
                } else {
                    echo "Connected to mySQL</br>";
                }
                //==========connection code end
                //==========dynamic drop down start
                echo "<select name= 'FirstName' >";

                echo '<option value="">' . '--- Please Select Person ---' . '</option>';

                $query = mysqli_query($con, "SELECT id,FirstName FROM persons");

                while ($row = mysqli_fetch_array($query)) {
                    $id = $row['id'];
                    echo "<option value='" . $row['FirstName'] . "'>" . $row['FirstName'] . '</option>';
                }

                echo '</select>';
                echo '&nbsp;';
                echo '<input type="submit" name="submit" value="Submit"/>';

                //-------------displaying associated row from db

                if (isset($_POST['FirstName'])) { //getting name of drop down box which has value that is first name
                    $name = $_POST['FirstName']; //store the name into a variable


                    $chosenname = $name; //store the name into another variable


                    $fetch = "SELECT id,Firstname,LastName,Gender,Subject,Hobbies FROM persons WHERE Firstname = '" . $name . "'";

                    $result = mysqli_query($con, $fetch);
                    if (!$result) {
                        echo "Error:" . (mysqli_error($con));
                    }

                    echo '<table border="1" align="center">' . '<tr>' . '<td align="center">' . 'From Database' . '</td>' . '</tr>'; //Outer table first row
                    //inner table columns
                    echo '<tr>' . '<td>' . '<table border="1">' . '<tr>' . '<td>' . 'ID' . '</td>' . '<td>' . 'First Name' . '</td>' . '<td>' . 'Last Name' . '</td>' . '<td>' . 'Gender' . '</td>' . '<td>' . 'Subject' . '</td>' . '<td>' . 'Hobbies' . '</td>' . '</tr>';


                    while ($data = mysqli_fetch_row($result)) {


                        echo ("<tr><td>$data[0]</td><td>$data[1]</td><td>$data[2]</td><td>$data[3]</td><td>$data[4]</td><td>$data[5]</td></tr>");
                    }

                    echo '</table>' . '</td>' . '</tr>' . '</table>';

                    //---------to update last name only

                    echo '<br/>' . '<br/>' . '<br/>';

                    //echo 'First Name:'.'<input type="hidden" name="fn" value="'.$karma.'"/>';
                    echo '<br/>';
                    echo "You are changing Last Name of  ID :  $id" . '<input type="text" name="updated"/>';
                    echo '<br/>';
                    echo '<input type="submit" name="sub" value="' . $chosenname . '"/>'; //passed the value of the name to the button
                    echo '<br/>';

                    $recieved = "";
                    $ta = "";
                    $fku = "";
                    echo '<br/>';


                    if (isset($_POST['sub'])) {


                        echo '<br/>';

                        //$fku=$_POST['fn'];
                        //echo "hi".$fn;
                        $recieved = $_POST['sub'];
                        echo "Hello:" . $recieved; //so first name has been fetched here from the button value
                        echo '<br/>';
                        $ta = $_POST['updated']; //fetched value from text area
                        echo "The Last Name is" . " " . $ta;
                        echo '<br/>';
                        $queryu = "UPDATE persons SET LastName ='" . $ta . "' WHERE id = '" . $id . "'";
                        echo '<br/>';
                        if (!mysqli_query($con, $queryu)) {
                            die('Error: ' . mysqli_error($con));
                        }
                        echo "Last Name is updated in the record with " . " " . $ta;
                    }
                }
                ?>
            </form>
            <br/><br/><br/>
            <a href="main.html"> Go back to Main Page </a>
        </body>
    </html>

The code I posted above has bugs in it. I rewrote the code for you. I used get instead of post. Unless your posting to a different script it is far less stressful to use get or request. I have double checked this code so it works. I coded it so you don't have to leave the page . You can continue changing last names all day using $_GET. This code can show you how powerful $_GET is. Sorry earlier for that post, it's been a long night.

<?php echo "
<!DOCTYPE>
<html>
    <head>

        <title>Update Data</title>
    </head>

    <body>


        <form name=\"form_update\" method=\"get\">";


            $con = mysqli_connect("localhost", "root", "", "ismat_db");

             // Attempt Connect
            if (mysqli_errno($con)) {
                echo "Can't Connect to mySQL:" . mysqli_connect_error();
            } else {
                echo "Connected to mySQL</br>";
            }

            // Drop menu id
            echo "<select name= 'id' >";

            echo '<option value="">' . '--- Please Select Person ---' . '</option>';

            $query = mysqli_query($con, "SELECT id, Firstname FROM persons");

            while ($row = mysqli_fetch_array($query)) {

                $fName = $row['Firstname'];
                $id = $row['id'];


                // Passing vars to dropdown . ID is value - First Name is String
                echo "<option value='" . $id . "'>" . $fName . '</option>';
            }

            echo '</select>';
            echo '&nbsp;';
            echo '<input type="submit" name="submit" value="Submit"/>';


            if (isset($_GET['id']) && isset($id)) { // is id set?
                $id = $_GET['id']; // Get the id via url string


                // Get record via id
                $result = mysqli_query($con, "SELECT id,Firstname,Lastname,Gender,Subject,Hobbies FROM persons WHERE id = '" . $id . "'") or die(mysqli_errno($con));



                echo '<table border="1" align="center">' . '<tr>' . '<td align="center">' . 'From Database' . '</td>' . '</tr>'; //Outer table first row
                //inner table columns
                echo '<tr>' . '<td>' . '<table border="1">' . '<tr>' . '<td>' . 'ID' . '</td>' . '<td>' . 'First Name' . '</td>' . '<td>' . 'Last Name' . '</td>' . '<td>' . 'Gender' . '</td>' . '<td>' . 'Subject' . '</td>' . '<td>' . 'Hobbies' . '</td>' . '</tr>';


                while ($data = mysqli_fetch_row($result)) {


                    // echo data array
                    echo ("<tr><td>$data[0]</td><td>$data[1]</td><td>$data[2]</td><td>$data[3]</td><td>$data[4]</td><td>$data[5]</td></tr>");
                }

                echo '</table>' . '</td>' . '</tr>' . '</table>'; // End table


                echo '<br/>' . '<br/>' . '<br/>';


                echo '<br/>';
                echo "You are changing Last Name of  ID :  $id :" . '<input type="text" name="updated"/>';
                echo '<br/>';

                // Hidden button value via Complex Curly
                echo "<INPUT TYPE=HIDDEN NAME='updateID' value='{$id}'/>"; 

                echo '<input type="submit" name="sub" value="Change Last Name"/>'; 
                echo '<br/>';



                if (isset($_GET['sub']) && isset($id)) {


                    $update_textfield = $_GET['updated']; //fetched value from text area
                    echo "The Last Name is" . " " . $update_textfield;
                    echo '<br/>';

                    // Notice : $id changed to updateID. This allows us to update without leaving the page.
                    $queryu = "UPDATE persons SET LastName ='" . $update_textfield . "' WHERE id = '" . $_GET['updateID'] . "'";
                    echo '<br/>';
                    if (!mysqli_query($con, $queryu)) {
                        die('Error: ' . mysqli_error($con));
                    }

                    echo "Last Name is updated in the record number " . $_GET['updateID'] . " with " . $update_textfield;

                }
            }
       echo "
        </form>
        <br/><br/><br/>
        <a href=\"main.html\"> Go back to Main Page </a>
    </body>
</html>"; 
?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.