php pdo test | LSABLOG

首页 » Program » PHP&&Mysql » 正文

php pdo test

I did a php pdo test,firstly I created a database named pdotest,then I created a table named books and inserted some records for test.Finally I used pdo to get thoes records.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>pdotest</title>
<style type="text/css">
<!--
body,td,th {
    font-size: 18px;
}
-->
</style></head>

<body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">

        <table width="400" border="0" cellpadding="0" cellspacing="0">
          <tr>
            <td height="30" align="center"><strong>id</strong></td>
            <td align="center"><strong>bookname</strong></td>
            <td align="center"><strong>bookprice</strong></td>
            <td align="center"><strong>edit</strong></td>
          </tr>
          
    <?php
$dbms='mysql';                      
$host='localhost';                  
$dbName='pdotest';          
$user='root';                       
$pass='root';                   
$dsn="$dbms:host=$host;dbname=$dbName";
try {
    $pdo = new PDO($dsn, $user, $pass);     
    $query='select * from books';   
    $result=$pdo->prepare($query);          
    $result->execute();
    echo 'errorcode:'.$pdo->errorCode();
    echo '<br/>';
    print_r($pdo->errorInfo());                     
    while($res=$result->fetch(PDO::FETCH_ASSOC)){       
    ?>    
          <tr>
            <td height="22" align="center" valign="middle"><?php echo $res['id'];?></td>
            <td align="center" valign="middle"><?php echo $res['bookname'];?></td>
            <td align="center" valign="middle"><?php echo $res['bookprice'];?></td>
            <td align="center" valign="middle"><a href="#">delete</a></td>
          </tr>
<?php 
    }
          } catch (PDOException $e) {
    die ("Error!: " . $e->getMessage() . "<br/>");
}
          ?>
        </table>
        </td>
</body>
</html>

If you want to see the error code when the sql is error,you should use $pdo->query($query) instead of prepare and execute,I don’t know why.

Comment