PHP:可以从db检索数据但不能插入

时间:2013-09-28 06:26:55

标签: php mysql

我想做的是:

将数据插入到具有两列的表中,并在同一个php页面中显示更新的值。我能够获取数据并显示它但无法插入任何数据。请指导我。

文件名为mypage.php

到目前为止我的代码:

<?php
$con=mysqli_connect("localhost","test","test","test");

// Check connection
if (mysqli_connect_errno($con))
  {
  echo "Failed to connect to mysqli: " . mysqli_connect_error();
  }
  else
  {

    if(isset($_POST['url']) && isset($_POST['desc'])) 
    {
        $url=$_POST['url'];
        $desc=$_POST['desc'];
        $sql=   "INSERT INTO urldesc ".
                "(url,desc) ".
                "VALUES ('".$url."', '".$desc."')";
        echo $sql;
        echo $url;
        echo $desc;
        mysqli_query($con, $sql);
        //mysqli_query($con,"INSERT INTO urldesc (url, desc) VALUES ('". $_POST['url'] ."', '". $_POST['desc'] ."')");
    }
  }

?>

<html>
    <body>
    <form action="mypage.php" method='post'>
        <input type="text" name='url' />
        <input type="text" name='desc' />
        <input type="submit" />
    </form>
        <table border=1>
            <th>URL</th>
            <th>Description</th>
            <?php
            $values=mysqli_query($con,"select * from urldesc");
            if(! $values )
            {
              die('Could not get data: ' . mysqli_error());
            }
            while($row = mysqli_fetch_array($values))
            {
                echo "<tr><td width='200px'><center>".$row['url']."</center></td><td width='600px'><center>".$row['desc']."</center></td></tr>";
            } 
            mysqli_close($con);
            ?>  
        </table>
    </body>
</html>

2 个答案:

答案 0 :(得分:0)

更改以下声明

 $sql=   "INSERT INTO urldesc ".
            "(url,desc) ".
            "VALUES ('".$url."', '".$desc."')";

 $sql=   "INSERT INTO urldesc ".
            "(`url`,`desc`) ".
            "VALUES ('".$url."', '".$desc."')";

答案 1 :(得分:0)

mysqli_qurey的给定参数格式错误。您使用的是mysqli_query($con, $sql),但应该是mysqli_query($sql, $con)

<?php
$con=mysqli_connect("localhost","test","test","test");

// Check connection
if (mysqli_connect_errno($con))
  {
  echo "Failed to connect to mysqli: " . mysqli_connect_error();
  }
  else
  {

    if(isset($_POST['url']) && isset($_POST['desc'])) 
    {
        $url=$_POST['url'];
        $desc=$_POST['desc'];
        $sql=   "INSERT INTO `urldesc` ".
                "(`url`,`desc`) ".
                "VALUES ('".$url."', '".$desc."')";
        echo $sql;
        echo $url;
        echo $desc;
        mysqli_query($sql, $con);
        //mysqli_query($con,"INSERT INTO urldesc (url, desc) VALUES ('". $_POST['url'] ."', '". $_POST['desc'] ."')");
    }
  }

?>