此PHP代码不会写入mySQL,但不会提供错误代码

时间:2013-07-16 20:01:13

标签: php mysql

//connect to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");

//select the database
mysql_select_db($database)
or die("Unable to select database: " . mysql_error());
?>
<head>
<title>Add New Article</title>
</head>
//this is supposed to take the form and put info into variables
<?php
if(isset($_POST['submit'])){
$title = $_POST['1title'];
$category = $_POST['1category'];
$uploader = $_POST['1uploader'];
$date = $_POST['1date'];
$youtubeurl = $_POST['1youtubeurl'];
$thumbnail = $_POST['1thumbnail'];
$content = $_POST['1content'];
}
//this is supposed to take those variables and put it into mysql
$query = "INSERT INTO videos (title, category, content, uploader, youtubeurl,    thumbnail) VALUES('$title', '$category', '$content', '$uploader', '$youtubeurl', '$thumbnail')";

    ?>


<body>
//This is my form where people enter info to be stored to mysql
<form method="POST" action="newvideo.php">
<pre>
Title <input type="text" name="1title" />
Category <input type="text" name="1category" />
Uploader <input type="text" name="1uploader" />
Date <input type="text" name="1date" />
Video URL <input type="text" name="1youtubeurl" />
Thumbnail URL <input type="text" name="1thumbnail" />
Content <textarea name="1content"></textarea>
<input type="submit" name="submit" />



</pre>

</form>
</body>

</html>

3 个答案:

答案 0 :(得分:6)

您定义$query,但之后您永远不会执行该查询......

$query = "INSERT ...";
$result=  mysql_query($query) or die(mysql_error()); // you forgot this line

并注意您编写的代码(如果实际执行查询)将容易受到SQL injection attacks的攻击。<​​/ p>

答案 1 :(得分:5)

嗯,对于初学者来说,你的查询应该在你的if语句中,而不是在它之外(我的猜测是你只想在实际提交表单时进行插入)。

其次,您声明了查询,但实际上从未执行过(请参阅@ MarcB的回答)。

第三,如果您确实执行了该查询,则不会转义输入并且容易受到SQL注入攻击。

答案 2 :(得分:1)

好吧,没有抛出关于转移到MySQLi或PDO的争论,我将按原样回答这个问题。您已指定SQL命令但尚未使用它查询数据库。您需要在SQL命令后运行mysql_query($query)。最好在if语句中。

if(isset($_POST) {
    $query = "INSERT INTO videos (title, category, content, uploader, youtubeurl,    thumbnail) VALUES('$title', '$category', '$content', '$uploader', '$youtubeurl', '$thumbnail')";

    mysql_query($query);

}

如果没有if语句,查询将在页面加载时运行。