dousao8152 2011-11-03 06:10
浏览 69
已采纳

转换为PDO类型mysql_fetch_array

I would like to ask for assistance on how to convert the code below to PDO type especially the mysql_fetch_array. I can make it work properly using this code but I want to convert to PDO.

 <?php

    $query = "SELECT * from name";
    $result = mysql_query($query);

    $cols = 6;
    echo "<table>";
    do {
        echo "<tr>";
        for ($i = 1; $i <= $cols; $i++) {

            $row = mysql_fetch_array($result);
            if ($row) {
                $name = $row['fname'];
    ?>
                    <td>
                    <table>
                    <tr valign="top">
                    <td>
                    <?php echo '<input type="checkbox" name="name[]" id="name[]" value="' . $name . '"/>' . $name . "
"; ?>
                    </td>
                    <td width="30">&nbsp;</td>   
                    </tr>
                    </table>
                    </td>
    <?php
            } else {
                echo "<td>&nbsp;</td>";
            }
        }
    } while ($row);
    echo "</table>";
    ?>
  • 写回答

1条回答 默认 最新

  • douyan8070 2011-11-03 06:24
    关注

    First off, you can read more at http://php.net/pdo.

    $dsn = 'mysql:dbname=testdb;host=127.0.0.1';
    $user = 'dbuser';
    $password = 'dbpass';
    
    try {
        $dbh = new PDO($dsn, $user, $password);
    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
    }
    
    $query = "SELECT * from name";
    
    $stmt = $dbh->prepare($query);
    
    $stmt->execute();
    
    // Start your html col/row setup
    
    // Loop through your cols
    
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    

    For your example it's not necessary to 'prepare' however it is a good practice when you start passing values to your query.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作