PHP利用mysql获取数据的方法

Published
2022-06-22
浏览次数 :  190

方法一利用Mysqli的函数

$result = mysqli_query($con,$sql);

        //方法一 用while循环,用到的是mysqli_fetch_assoc 函数,每查询一次获取一行
        if($result) {
            while($row=mysqli_fetch_assoc($result)) {
                $id = $row['id'];
                $name = $row['name'];
                $email = $row['email'];
                $mobile = $row['mobile'];
                $password = $row['password']; ?>
                <tr>
                    <th scope="row"><?php echo $id ?></th>
                    <td><?php echo $name ?></td>
                    <td><?php echo $email ?></td>
                    <td><?php echo $mobile ?></td>
                    <td><?php echo $password ?></td>
                    <td>
                        <button class="btn btn-primary"><a href="update.php?updateid=<?php echo $id ?>" class="text-white">Update</a></button>
                        <button class="btn btn-danger"><a href="delete.php?deleteid=<?php echo $id ?>" class="text-white">Delete</a></button></td>
                </tr>
                <?php 
            }
        }

        // if($result) {
        //     $rows = $result->fetch_all(MYSQLI_ASSOC);
        //     //$row = mysqli_fetch_assoc($result);
        //     var_dump($rows);
        // }

方法二利用connect的object

$start = $conn->real_escape_string($_POST['start']);
    $limit = $conn->real_escape_string($_POST['limit']);
    $sql = $conn->query("SELECT id,countryName FROM country LIMIT $start,$limit");

    if ($sql->num_rows > 0) {
      $response = "";
      while($data = $sql->fetch_array()) {
        $response .= '
          <tr>
            <td>'.$data['id'].'</td>
            <td id="country_'.$data['id'].'">'.$data['countryName'].'</td>
            <td>
            <input type="button" onclick="edit('.$data['id'].')" value="Edit" class="btn btn-primary">
            <input type="button" value="View" class="btn">
            <input type="button" value="DELETE" class="btn btn-danger">
            </td>
          </tr>
        ';
        
      } 
      exit($response);

  • 标签1
  • 标签1
  • 标签1
Top