我正在尝试将数据插入我的数据库,但是这个查询失败了,我不知道为什么。我刚刚收到“错误更新数据库”输出。
表格详细信息
name varchar(80)
sitename varchar(80)
pages text
colors text
navigation text
content text
PHP
<?php
$name = $_POST['name'];
$sitename = $_POST['sitename'];
$pages = $_POST['pages'];
$color = $_POST['colors'];
$navigation = $_POST['navigation'];
$content = $_POST['content'];
mysql_connect("localhost","csuwebdev","") or die ('Error: ' . mysql_error());
mysql_select_db("csuwebdev");
$query = "INSERT INTO draft (name, sitename, pages, colors, navigation, content) VALUES ( '".$name."', '".$sitename."', '".$pages."', '".$color."', '".$navigation."', '".$content."')";
mysql_query($query) or die ('Error updating database');
echo "Submission received...";
?>
HTML
<form method="POST" action="processDraft.php">
Your name<br>
<input type="text" name="name"><br>
Name of website<br>
The pages that will comprise the website and a brief description of each. A minimum of 4 is required (Home, About, Contact, and Resume)<br>
<textarea rows="4" cols="100" name="pages">
</textarea><br>
What colors might you use for the background, content background, header text, and paragraph text?<br>
<textarea rows="4" cols="100" name="colors">
</textarea><br>
What will the navigation buttons look like, and where will they be placed?<br>
<textarea rows="4" cols="100" name="navigation">
</textarea><br>
Where will you put your main content for each page?<br>
<textarea rows="4" cols="100" name="content">
</textarea><br>
<input type="submit">
</form>
最佳答案
将代码重写为
$conn=mysql_connect("localhost","csuwebdev","") or die ('Error: ' . mysql_error());
mysql_select_db("csuwebdev",$conn);
在对表进行查询之前,您需要将数据库连接传递给 mysql_select_db
。
自 PHP 5.5.0
起,此 (mysql_*
) 扩展已弃用,并将在未来删除。相反,应该使用 MySQLi
或 PDO_MySQL
扩展。切换到 PreparedStatements
可以更好地抵御 SQL 注入(inject)攻击!
上述代码的 PDO 版本。 [虽然没有测试]
$dbh = new PDO('mysql:host=localhost;dbname=csuwebdev', 'username', 'password');
$stmt = $dbh->prepare("INSERT INTO draft (name, sitename,pages,colors,navigation) VALUES(?,?,?,?,?)");
$stmt->execute(array($name,$sitename,$pages,$color,$navigation));
关于php - SQL 查询失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22655415/