[英]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_*
方法,而應使用PDO
或mysqli
API,請參見http://www.php.net/manual/zh/mysqlinfo.api.choosing.php
另請參閱關於此的stackoverflow帖子: mysqli或PDO-優缺點是什么?
有些PDO
准備語句的例子與PDO
: http://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.