doushun4666 2011-11-21 08:02
浏览 29

你如何使用php PDO fetchobject()方法与sqlite获取主键字段?

Schema is:
sqlite> .schema posts
CREATE TABLE posts (
id integer primary_key auto_increment,
title text,
content text
);

...

sqlite> .mode line
sqlite> select id,title, content from posts;
     id = 
  title = title
content = content in here

     id = 
  title = a new title
content = new content

.... My entire index.php. This is supposed to be a trivial example.

   // Insert a post into the DB
if (isset($_POST['title']) && isset($_POST['content'])) {
   try {
         // Fill in the values
         $title = $_POST['title'];
         $content = $_POST['content'];

         # echo "title=".$title.", content=".$content;   

         // Create a prepared statement
         $stmt = $db->prepare("INSERT INTO posts (title, content) VALUES (:title, :content);");
         $stmt->bindParam(':title', $title);
         $stmt->bindParam(':content', $content);

         $stmt->execute();
      } catch (Exception $e) {
         die ($e);
   }
}

// Get posts from database
try {
   $posts = $db->prepare('SELECT id, title, content FROM posts;');
   $posts->execute();
} catch (Exception $e) {
   die ($e);
}

?>

<h1>Posts - SQLite Example</h1>

<?php while ($post = $posts->fetchObject() ): ?>
<br/>     
<h2><?php echo $post->title ?></h2>
<?php echo $post->content ?>
<a href="<?php echo $_SERVER['PHP_SELF']; ?>?action=delete&id=<?php echo $post->id ?>"><br/>Delete Post</a>
<?php endwhile; ?>

<hr />

<h2>Add new Post</h2>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

<p>
<label for="title">Title:</label>
<input type="text" name="title" />
</p>

<p>
<textarea name="content" rows="8" cols="50"></textarea>

My problem is that $post->id is empty, but should have been mapped to the $post variable according to the documentation for fetchObject().

I really am just trying to get the primary key of the row I'm displaying so as to add a delete link.

Note that I can open, read, and write the database without issue. Also title and content are retrieved properly but I'm just stuck on getting the id field from the object returned by fetchObject().

It seems sqlite may never actually be putting anything in the id field of the table.

UPDATE:The answer may have been here all along. It was actually a sqlite issue not a php one.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 2024-五一综合模拟赛
    • ¥15 下图接收小电路,谁知道原理
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
    • ¥15 手机接入宽带网线,如何释放宽带全部速度
    • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
    • ¥15 ETLCloud 处理json多层级问题
    • ¥15 matlab中使用gurobi时报错
    • ¥15 这个主板怎么能扩出一两个sata口
    • ¥15 不是,这到底错哪儿了😭