PDO没有写入MySQL,我哪里出错了?

时间:2012-08-22 13:15:47

标签: php mysql pdo var

我刚刚将我的mysql代码重写为PDO,但我不知道它是否正常工作。我一直在调试,但似乎没有做到正确。这对我来说都是全新的,但是它连接数据库,它从我的vardump中的数据库中读取,但它不会在textarea中发布,甚至不会回应那个问题。写信给数据库吧......我有一种直觉,那就是$ result var正在做一些奇怪的事情,但据我所知,我仔细检查了一切。

<html>
    <head>
    <title>Milan CMS</title>
    </head>

<body>

    <?php
        $host= "";
        $dbname= "";
        $username= "";
        $password= "";
        $dbh = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
        $sth = $dbh->prepare("SELECT * FROM milan WHERE tag='trainingen'");
        $sth->execute();
        $result = $sth->fetchAll();
        var_dump($result);
        echo $result['value'];
        echo $result;   
    ?>
    <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" name="trainingen">
    Trainingen:<textarea name="nametrainingen" rows="10" cols="60"><?php echo $result['value']; ?></textarea></p>
    <input name="submit" type="submit" value="Verzenden"><input type="reset" value="Veld leeg maken">
    </form>

    <?php
        $invoer = $_POST['nametrainingen'];

        if (isset($_POST['submit'])) { //test if submit button is clicked
        $sql = "DELETE FROM milan WHERE tag = 'trainingen'";
        $sql = "INSERT INTO milan (tag, value) VALUES ('trainingen', '$result')";   
        $sth->execute();
        $result = $sth->fetchAll();
        $myFile = "trainingen.json"; 
        $fh = fopen($myFile, 'w') or die("can't open file");
        fwrite($fh, json_encode($result));
        fclose($fh);}
    ?>
<p>
</body>
</html>

var_dump的输出:

array(1) { 
    [0]=> array(6) { 
        ["id"]=> string(1) "0" 
        [0]=> string(1) "0" 
        ["tag"]=> string(10) "trainingen" 
        [1]=> string(10) "trainingen" 
        ["value"]=> string(17) "Hgioejigojerigjer" 
        [2]=> string(17) "Hgioejigojerigjer" 
    } 
} 

1 个答案:

答案 0 :(得分:0)

if (isset($_POST['submit'])) { //test if submit button is clicked
    $sql = "DELETE FROM milan WHERE tag = 'trainingen'";
    $sql = "INSERT INTO milan (tag, value) VALUES ('trainingen', '$result')";   
    $sth->execute();

这只是重新运行$sth的先前内容 - 您需要准备这两个语句然后运行它们。你需要像这样运行它们:

if (isset($_POST['submit'])) { //test if submit button is clicked
    $sql = "DELETE FROM milan WHERE tag = 'trainingen'";
    $sth = $dbh->prepare($sql);
    $sth->execute();
    $sql = "INSERT INTO milan (tag, value) VALUES ('trainingen', '$result')";   
    $sth = $dbh->prepare($sql);
    $sth->execute();

编辑添加:

$result = $sth->fetchAll();
var_dump($result);
echo $result['value'];
echo $result;

$result最终会得到一系列值 - 您必须逐步浏览数组中的每个项目。