PDO插入数据库

扫码查看
本文介绍了PDO插入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过很多教程,它们介绍了使用PDO进行插入的多种不同方式.他们似乎都没有为我工作.似乎无法让我发送到数据库.我使用FETCH连接和检索数据没有问题,但似乎无法发布该数据.

I've seen so many tutorials with so many different ways to insert using PDO. None of them seem to work for me. Can't seem to get mine to send to the database. I have no issue connecting and retreiving the data using FETCH but can't seem to post this data.

任何有关使我的帖子正常工作以及使用标题或元刷新进行重定向的帮助都将很不错.我是html表单的$ _POST.连接到数据库工作正常,但无法获取数据.

Any help with getting my post to work and redirect using the header or meta refresh would be nice. I am $_POST from an html form. Connecting to the db works just fine but can't get the data in.

   $hostdb = 'myremoteip';
   $namedb = 'cpdemo';
   $userdb = 'root';
   $passdb = 'mypassword';

   $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);

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

         $fname = $_POST['fname'];
         $lname = $_POST['lname'];
         $title = $_POST['title'];
         $photo = $_POST['photo'];

   $stmt = "INSERT INTO row_users (fname,lname,title,photo)
         VALUES (:first,:last,:title,:photo)";

   $q = $conn->prepare($stmt);
   $results = $q->execute(array(
        ":first"=>$fname,
        ":last"=>$lname,
        ":title"=>$title,
        ":photo"=>$photo
    ));
    echo 'User Added<br/>';
    }

      header ('Location:../insertUser.html');
    exit();

推荐答案

按照OP的要求,注释导致答案(关闭问题并标记为已解决).

As requested by OP, comment leading to an answer (to close the question and marked as solved).

我按原样"测试了您的代码,并且工作正常.

I tested your code "as is", and it worked fine.

我唯一可以说的可能是问题,除非满足您设置的if(isset($_POST['fname']))

The only thing I can tell that could be the issue is, that your insert won't happen unless it meets the conditional statement you've set if(isset($_POST['fname']))

检查您的HTML表单的元素是否确实命名?

Check to see if your HTML form's elements are indeed named?

<input type="text" name="fname">等.如果其中之一未命名或有错字,则整个查询将失败.

I.e. <input type="text" name="fname"> etc. If one of those are not not named or has a typo, then your whole query will fail.

这篇关于PDO插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 06:51
查看更多