繁体   English   中英

无法使用php将数据插入数据库

[英]Unable to insert data into database with php

我在使用表单将数据发布到数据库中时遇到问题。 我敢肯定,这是非常基本的东西,但我还是很困:/

我可以使用select from database例程从数据库中获取内容。 因此,我知道与数据库的连接可能不是问题。

这是我的“ upload.php”:

<html>
<head>
<title>Upload</title>
</head>
<body>

    <form action="action.php" method="post">

        <fieldset class="first">
             Name: 
        <input type="text" name="author" />
        Heading:
          <input type="text" name="heading" />

        Text:
        <textarea type="text" name="thecontent"> </textarea>
        </fieldset>


        <fieldset>
        <input type="submit"/> 
            </fieldset>
    </form>



</body>
</html>

这是我的“ action.php”:

<html>
<head>

<title>Send!</title>
</head>

<body>

<?php

 ini_set('display_errors', 1); error_reporting(E_ALL); 

$link = mysql_connect('localhost','name','pasword')
or die ("Unable to connect"); 

$mydb = mysql_select_db('the_database',$link)
or die ("No database found"); 

$author = $_POST['author']; 
$heading = $_POST['heading'];
$thecontent = $_POST['thecontent'];

$mysql_query="INSERT INTO articles ('heading', 'author', 'content')
 VALUES ('$heading','$author','$thecontent')" or die(mysql_error());   

echo "This was send: $author $heading $thecontent <br> ";


 mysql_close()

?> 

</body>
</html>

所有帮助将不胜感激!

齐格干杯

感谢所有的帮助! 我正在尝试使用mysqli插入数据,但仍无法正常工作,这是我在action.php中的新代码:

<html>
<head>

<title>Send!</title>
</head>

<body>

<?php

 ini_set('display_errors', 1); error_reporting(E_ALL); 
$DB_HOST = 'localhost';
$DB_USER = '**';
$DB_PASS = '***';
$DB_NAME = '***';
@ $db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
echo 'Error.';
exit();
}

$author = $_POST['author']; 
$heading = $_POST['heading'];
$thecontent = $_POST['thecontent'];

$query = 'INSERT INTO articles ('heading', 'author', 'content')
 VALUES ('$heading','$author','$thecontent')';   

$result = $db->query($query);
    if ($result) {
    echo $db->affected_rows."This was added.";
    } 
    else {
    echo "somethings gone very wrong.";
    }

$db->close();




?> 

</body>
</html>

我在做错人吗? 非常感谢帮助!

齐格干杯

您构建了INSERT字符串,但从未调用过使用它真正实现对数据库的插入的方法。

此外,不建议使用旧的mysql_*方法,而应使用PDOmysqli API,请参见http://www.php.net/manual/zh/mysqlinfo.api.choosing.php

另请参阅关于此的stackoverflow帖子: mysqli或PDO-优缺点是什么?

有些PDO准备语句的例子与PDOhttp://www.php.net/manual/en/pdo.prepare.php

$mysql_query="INSERT INTO articles    ('heading', 'author', 'content')
 VALUES ('$heading','$author','$thecontent')";
mysql_query($mysql_query);
//required to run the query..

And mysql_close(); // missing :p

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM