douci1918 2019-04-16 06:30
浏览 57

无法从PDO中的函数获取数据到ajax

I have made a class employee and have function of select that should return the values to add_data.php and using that data , it should be in option tag of select that is the ajax for country state and city.

employee.php

 <?php
class employees{
    function __construct(){
        try {
                $this->con= new PDO("mysql:host=myserver;dbname=dhruv_thakkar", 'uname', 'pass');
                $this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                }

        catch(PDOException $e)
                {
                echo "Connection failed: " . $e->getMessage();
                }
      }

      function insert($name,$email,$password,$birth_date,$gender,$postcode,$phno,$street_address){
          try {

              $name=$this->name=$name;
              $email=$this->email=$email;
              $password=$this->password=$password;
              $birth_date=$this->birth_date=$birth_date;
                $gender=$this->gender=$gender;
                $postcode=$this->postcodde=$postcode;
                $phno=$this->phno=$phno;
                $street_address=$this->street_address=$street_address;

                $d1 = date('Y-m-d',(strtotime($birth_date)));
                $sql = "INSERT INTO employees(name, email,gender,password,street_address,postcode,phone_number,profile_pic,status,register_date,birth_date)
                VALUES ( '$name', '$email','$gender ','$password','$street_address','$postcode','$phno','pic123','1',NOW(),'$d1')";
              $this->con->exec($sql);
              echo "New record created successfully";
          }
          catch(PDOException $e)
          {
              echo $sql . "<br>" . $e->getMessage();
          }

          $this->con= null;
      }

      function select_country(){
         $sql= "SELECT *from country";
         $result =$this->con->query($sql);
        return $result;
      }
}

$obj= new employees();
?>

add_data.php

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include 'employee.php';
    session_start();
    $username=$_SESSION['username'];
    $password=$_SESSION['password'];

    if(isset($_SESSION['username'])){

        if(isset($_POST['logout'])){
                session_destroy();
                header('location:index.php');
        }

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

           $name=$_POST['name'];
           $email=$_POST['email'];
           $password=$_POST['password'];
           $birth_date=$_POST['birth_date'];
          echo  $gender=$_POST['gender'];
           $postcode=$_POST['postcode'];
           $phno=$_POST['phno'];
           $street_address=$_POST['street_address'];

           $obj->insert($name,$email,$password,$birth_date,$gender,$postcode,$phno,$street_address);

        }

    }
    else {
        header('location:index.php');
    }

?>
    <!doctype html>
    <html lang="en">
      <head>
      <style>

.sidebar-sticky{
      border-right: 3px solid #aaacaf;
    height:1000px;
}
    .col-centered{
      align-items: center;
        }
    </style>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
        <!-- Bootstrap CSS -->  
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

      </head>
      <body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
  <a class="navbar-brand" href="#">Admin Panel</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>

    </ul>

    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>
    &nbsp;&nbsp;&nbsp;
    <form action="" method="post"  class="form-inline my-2 my-lg-0">
        <input type="submit" value="logout" name="logout"  class="btn btn-outline-danger my-2 my-sm-0 ">
    </form>

      </div>  
</nav>

  <!--Side Bar Now  -->
      <div class="container-fluid sidea">
      <div class="row">

        <nav class="col-md-2 d-none d-md-block bg-light sidebar">
        <?php 
            include 'sidebar.php';
        ?>
      </nav>
        <div class="col-sm-10">
            <div class="container">

            <h2>Add User Here</h2>
            <br>
            <form action="" method="post" enctype="multipart/form-data">

                    <input type="text" class="form-control" placeholder="Enter Name" name="name"> 
                    <br><br>

                    <input type="text" class="form-control" placeholder="Enter Email"  name="email"> 
                    <br><br>


                    <input type="text" class="form-control" placeholder="Enter Password"  name="password"> 
                    <br><br>

                    <label>Upload Your Profile Picture Here</label>
                    <input type="file"  name="photo"> 
                    <br><br>

                    <label>Enter Your BirthDate</label>
                     <input type="date" class="form-control"  name="birth_date"> 
                    <br><br>

                    <label>Select Gender</label>&nbsp;&nbsp;<br>
                    <label><input type="radio" value="M" name="gender">Male</label> <br>
                    <label><input type="radio" value="F" name="gender">Female</label>
                    <br><br>


                    <input type="text" class="form-control" placeholder="Enter Street Address"  name="street_address"> 
                    <br><br>

<?php
?>              
<select value="" id="country">
    <?php 
    $result=$obj->select_country();
    print_r($data);
    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) { 
            ?>
    <option value="<?php echo $row['country_id']; ?>">
<?php
        echo $row['country_name'];
?>
   </option>
    <?php
    }

}
else{
    echo '<option value="">Country not available</option>';
}

?>
</select>        
  <select id="state">
    <option value="">Select country first</option>
</select>

<select id="city">
    <option value="">Select state first</option>
</select>


                    <br><br>
                    <input type="text" class="form-control" placeholder="Postcode"  name="postcode"> 
                    <br><br>

                    <input type="text" class="form-control" placeholder="Phone No"  name="phno"> 
                    <br><br>

                    <input type="submit" class="btn btn-success"  value=" Add Data" name="submit"> 

            </form>
            </div>
        </div>
    </div>


    </div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){
    $("#country").change(function(){
        var countryID = $(this).val();
        if(countryID){
            $.ajax({
                type:'POST',
                url:'ajaxData.php',
                data:'country_id='+countryID,
                success:function(html){
                    $('#state').html(html);
                    $('#city').html('<option value="">Select state first</option>'); 
                }
            }); 
        }else{
            $('#state').html('<option value="">Select country first</option>');
            $('#city').html('<option value="">Select state first</option>'); 
        }
      });

    $('#state').on('change',function(){
        var stateID = $(this).val();
        if(stateID){
            $.ajax({
                type:'POST',
                url:'ajaxData.php',
                data:'state_id='+stateID,
                success:function(html){
                    $('#city').html(html);
                }
            }); 
        }else{
            $('#city').html('<option value="">Select state first</option>'); 
        }
    });
});
</script>    
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
      </body>
    </html> 

Here I country are not getting displayed. It always goes in else loop and shows country not available.

  • 写回答

1条回答 默认 最新

  • duanao3204 2019-04-16 07:25
    关注

    You are mixing up mysqli and PDO database extensions. Pick one and be consistent.

    Change the select() method of employees class and <select>...</select> block in the following way,

    class employees{
        ...
        function select_country(){
            $sql= "SELECT *from country";
            $result =$this->con->query($sql);
            return $result->fetchAll();
        }
        ...
    }
    

    and

    <select value="" id="country">
        <option value="">Select a country<option>
        <?php 
        $result = $obj->select_country();
        $count = count($result);
        // print_r($data);
        if ($count > 0) {
            // output data of each row
            foreach($result as $row){ 
                ?>
                <option value="<?php echo $row['country_id']; ?>">
                <?php
                    echo $row['country_name'];
                ?>
                </option>
                <?php
            }
        }else{
            echo '<option value="">Country not available</option>';
        }
        ?>
    </select> 
    

    Sidenote: Learn about prepared statement because right now your query is susceptible to SQL injection attack. Also see how you can prevent SQL injection in PHP.

    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值