0

我刚刚将我的 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" 
    } 
} 
4

1 回答 1

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最终得到一个值数组 - 您必须逐步遍历数组中的每个项目。

于 2012-08-22T13:18:38.283 回答