Load data from database according to the number th

2019-09-20 08:30发布

问题:

Hello i have a form as you can see in the image below...

... In which form I load the first data from my database table...

what i want is that when i click on a number on the top of the list, to load the appropriate data.

My code is the below (html form code is not included) ...

<?php
                $username = $_SESSION["username"];

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

                    $id = $_POST['idWork'];
                    $job_title = mysql_real_escape_string($_POST["job_title"]);
                    $company = mysql_real_escape_string($_POST["company"]);
                    $website = mysql_real_escape_string($_POST["website"]);
                    $start_date = mysql_real_escape_string($_POST["start_date"]);
                    $end_date = mysql_real_escape_string($_POST["end_date"]);
                    $start_year = mysql_real_escape_string($_POST["start_year"]);
                    $end_year = mysql_real_escape_string($_POST["end_year"]);
                    $work_history = mysql_real_escape_string($_POST["work_history"]);
                    if($start_year > $end_year)
                    {
                        echo '<script>ErrorMessage()</script>';
                        $id=$id-1;
                        $good = false;
                    }
                    else
                    {
                        $good = true;
                    }
                    if($good == true){

                    $query="UPDATE work
                            SET job_title = '$job_title', company = '$company', website = '$website', start_date='$start_date', end_date='$end_date', start_year='$start_year', end_year='$end_year', work_history='$work_history'
                            WHERE id='$id' AND username='$username'";

                        mysql_query($query)or die(mysql_error());
                        if(mysql_affected_rows()>=0){
                            echo "<p>Record Updated<p>";
                            echo "<script type='text/javascript'>;
                                    window.location='addCV.php';
                                  </script>";
                        }else{
                            echo "<p>Error Updating Record<p>";
                            echo "<script type='text/javascript'>;
                                    window.location='addCV.php';
                                  </script>";
                        }
                    }
                }
                else{
                  //first time, initialize as you wish. Probably need to get the first id for this user, using another query
                  $id = 0;
                }

                if($query = mysql_query("SELECT job_title,company,website,start_date,end_date,start_year,end_year,work_history FROM work WHERE id>'$id' AND username='$username' order by id asc limit 1") or die(mysql_error()))
                {
                    if(mysql_num_rows($query)>=1){
                        while($row = mysql_fetch_array($query)) {
                        $job_title = $row['job_title'];
                        $company = $row['company'];
                        $website = $row['website'];
                        $start_date = $row['start_date'];
                        $end_date = $row['end_date'];
                        $start_year = $row['start_year'];
                        $end_year = $row['end_year'];
                        $work_history = $row['work_history'];
                        }
                    }

                }
            ?>
            <script>
                $(document).ready(function(){
                    $("#updateWork").click(function(){
                        $("#idW").css("display","none");
                        var r = parseInt($("#idW").val(),10)+1;
                        $("#idW").val(r);
                    });
                });
            </script>
            <p><input type="button" value="Work History" id="SlideMeWorkHistoryButton" style="color: #F87F25; background: black; font: bold 22px Tahoma; width: 16em;  height: 2em; border-radius:7px; padding:4px;"/></p>              
            <div id="SlideMeWorkHistoryForm">
                <?php
                $sql = "SELECT id FROM work WHERE username='$username' order by id asc limit 10;";

                $result = mysql_query($sql);
                if ($result != 0) {


                    $num_results = mysql_num_rows($result);
                    for ($i=0;$i<$num_results;$i++) {
                        $row = mysql_fetch_array($result);
                        $id = $row['id'];
                        echo '<a href="' .$id. '">' .$id. '</a>';
                    }

                }

回答1:

Try this, changes explained in comments:

<?php
                $username = $_SESSION["username"];

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

                    $id = $_POST['idWork'];
                    $job_title = mysql_real_escape_string($_POST["job_title"]);
                    $company = mysql_real_escape_string($_POST["company"]);
                    $website = mysql_real_escape_string($_POST["website"]);
                    $start_date = mysql_real_escape_string($_POST["start_date"]);
                    $end_date = mysql_real_escape_string($_POST["end_date"]);
                    $start_year = mysql_real_escape_string($_POST["start_year"]);
                    $end_year = mysql_real_escape_string($_POST["end_year"]);
                    $work_history = mysql_real_escape_string($_POST["work_history"]);
                    if($start_year > $end_year)
                    {
                        echo '<script>ErrorMessage()</script>';
                        $id=$id-1;
                        $good = false;
                    }
                    else
                    {
                        $good = true;
                    }
                    if($good == true){

                    $query="UPDATE work
                            SET job_title = '$job_title', company = '$company', website = '$website', start_date='$start_date', end_date='$end_date', start_year='$start_year', end_year='$end_year', work_history='$work_history'
                            WHERE id='$id' AND username='$username'";

                        mysql_query($query)or die(mysql_error());
                        if(mysql_affected_rows()>=0){
                            echo "<p>Record Updated<p>";
                            echo "<script type='text/javascript'>;
                                    window.location='addCV.php';
                                  </script>";
                        }else{
                            echo "<p>Error Updating Record<p>";
                            echo "<script type='text/javascript'>;
                                    window.location='addCV.php';
                                  </script>";
                        }
                    }
                }
                // add the below check 
                else if(isset($_GET['idWork'])){
                  // user clicked on one of the id links to get here
                  // set $id to the value of the GET parameter for key "idWork"
                  $id = $_GET['idWork'];
                }
                else{
                  // first time, initialize as you wish. Probably need to get the first id for this user, using another query
                  // I went ahead and added this for you...
                  if($query = mysql_query("SELECT job_title,company,website,start_date,end_date,start_year,end_year,work_history FROM work WHERE username='$username' order by id asc limit 1") or die(mysql_error())){
                      if(mysql_num_rows($query)>0){
                        while($row = mysql_fetch_array($query)) {
                             $id = $row['id'];
                        }
                      }
                      else{
                          echo '<script>ErrorMessage()</script>';
                      }
                  }
                }

                if($query = mysql_query("SELECT job_title,company,website,start_date,end_date,start_year,end_year,work_history FROM work WHERE id>'$id' AND username='$username' order by id asc limit 1") or die(mysql_error()))
                {
                    if(mysql_num_rows($query)>=1){
                        while($row = mysql_fetch_array($query)) {
                        $job_title = $row['job_title'];
                        $company = $row['company'];
                        $website = $row['website'];
                        $start_date = $row['start_date'];
                        $end_date = $row['end_date'];
                        $start_year = $row['start_year'];
                        $end_year = $row['end_year'];
                        $work_history = $row['work_history'];
                        }
                    }

                }
            ?>
            <script>
                $(document).ready(function(){
                    $("#updateWork").click(function(){
                        $("#idW").css("display","none");
                        var r = parseInt($("#idW").val(),10)+1;
                        $("#idW").val(r);
                    });

                    // listen for clicks on the id links
                    $('[data-row-id]').click(function(e){
                            e.preventDefault();
                            var fileName = 'thisFile.php?idWork='; //change "thisFile.php" to the name of this file in your project, the "?" starts the GET parameters, idWork= sets the key for the GET parameter  
                            var id = $(this).data('row-id'); // this gets the id that we stored in the link's data attribute
                            var url = fileName+id;  // then we add that id as the value for the "idWork" key
                            window.location= url; // esentially refresh this page with the id set as a GET parameter and make use of the logic we already have to load the info
                    });
                });
            </script>
            <p><input type="button" value="Work History" id="SlideMeWorkHistoryButton" style="color: #F87F25; background: black; font: bold 22px Tahoma; width: 16em;  height: 2em; border-radius:7px; padding:4px;"/></p>              
            <div id="SlideMeWorkHistoryForm">
                <?php
                $sql = "SELECT id FROM work WHERE username='$username' order by id asc limit 10;";

                $result = mysql_query($sql);
                if ($result != 0) {


                    $num_results = mysql_num_rows($result);
                    for ($i=0;$i<$num_results;$i++) {
                        $row = mysql_fetch_array($result);
                        $id = $row['id'];
                        echo '<a href="#" data-row-id="'.$id.'">' .$id. '</a>';
                    }

                }
                ?>


回答2:

You can do this with ajax request. Jquery provides us with easy app interface.

There could be endless approaches, but for illustrating purposes, here is how i would do this.

  • have each anchor element a representative attribute, could be class selector: <a href="#" class="num" change_form_to="1"> 1 </a><a href="#" class="num" change_form_to="3"> 2 </a> ..etc

or you could make jQuery to decide, what information to POST based on element's value.. your preference

  • see, which number user clicked $('a').on('click',function(){var clicked = $(this).attr('change_form_to')}) so here variable holds this custom attributes value $(this).text() or like this to get text literal jQuery

  • then make a call to php script $.ajax({type:'POST',url:'dbh.php',data:{idWork:clicked},success: function(res){populate(res)}}) and when success function is called, the response has came for you to call your custom made populate function


All to geather:

$('a').on('click',function(){

   var clicked = $(this).attr('change_form_to');
   $.ajax({
      type:'POST',
      url:'dbh.php',
      data:{idWork:clicked},
      success: function(res){
         console.log(res);
         //populate(res); could look like this if your php script dies with just outputing json_encode on some assoc array 
         var j = JSON.parse(res);
         $('form input.name').value(j.name) ...etc
         }
    })

});

Your question states you want to get data from database but in your sql syntax you have UPDATE logic



标签: php jquery forms