-1

我正在尝试在我的网站中添加一个部分,您可以在其中填写一个小表格,它会为您添加社区。当我尝试填写表格并添加新社区时,我收到以下错误。请让我知道我做错了什么以及为什么我不能将这些添加到数据库中?谢谢你的帮助!

代码:

require_once('db.php');

//set the registration variables
$name = addslashes($_POST['name']);
$builder = addslashes($_POST['builder']);
$builderURL = $_POST['builderURL'];

//connect to database
$link = mysql_connect($dbhost, $dbuser, $dbpwd);
if (!$link) {
    die(strip_tags('Could not connect: '.mysql_error()));
}

//add this contest to the database
$stmt = "INSERT INTO hf_neighborhoods (name, builder, builder_url, created_on) VALUES " .
        "('$name', '$builder', '$builderURL', NOW())";
$result = mysql_query($dbname, $stmt);
if(!$result){
    die(strip_tags('Error Adding Neighborhood: '.mysql_error()));
}

//if we made it this far, return a success
echo 'success';
?>

DB Call: 
<?php

$dbhost = 'localhost';
$dbname = 'delsur_2011_dev';
$dbuser = 'delsur2011';
$dbpwd  = 'newsite!';

?>


Error:

<br />
<b>Warning</b>:  mysql_query() expects parameter 2 to be resource, string given in <b>/var/www/vhosts/delsurliving.com/httpdocs/hf/php/addNeighborhood.php</b> on line <b>21</b><br />
Error Adding Neighborhood: 

Now I am receiving this error when I try to change it to that new code?  Is it just not connecting to the database at all now?  I am lost, I wasn't the one that set this file up, I was just told to go and try to fix it so that is what I am trying to do now? Thanks for your help

警告:mysql_real_escape_string():第8/var/www/vhosts/delsurliving.com/httpdocs/hf/php/addNeighborhood.php中用户 'apache'@'localhost' 的访问被拒绝(使用密码:否)警告:mysql_real_escape_string (): 无法在第8行的/var/www/vhosts/delsurliving.com/httpdocs/hf/php/addNeighborhood.php中建立到服务器的链接警告:mysql_real_escape_string(): Access denied for user 'apache'@第9/var/www/vhosts/delsurliving.com/httpdocs/hf/php/addNeighborhood.php中的“localhost”(使用密码:NO)警告:mysql_real_escape_string():无法在





/var/www/vhosts/delsurliving.com/httpdocs/hf/php/addNeighborhood.php在第9
行 添加邻居时出错:未选择数据库

4

1 回答 1

2

你必须改变

$result = mysql_query($dbname, $stmt);

$result = mysql_query($stmt, $link);

但是,不推荐使用 mysql_* 函数,现在它被认为是一种不好的做法。

相反,您应该使用PDOMySQLi!而且,不要使用添加斜杠,至少使用mysql_real_escape_string

编辑:你应该在连接到数据库之后调用 mysql_real_escape_String() ,而不是之前。另外,不要忘记调用 mysql_select_db()!

//connect to database
$link = mysql_connect($dbhost, $dbuser, $dbpwd);
if (!$link) {
    die(strip_tags('Could not connect: '.mysql_error()));
}

mysql_select_db($dbname, $link);

// Sanitize your input at least!
$name = mysql_real_escape_string($_POST['name'], $link);
$builder = mysql_real_escape_string($_POST['builder'], $link);
$builderUrl = mysql_real_escape_string($_POST['builderUrl'], $link);

//add this contest to the database
$stmt = "INSERT INTO hf_neighborhoods (name, builder, builder_url, created_on) VALUES " .
    "('$name', '$builder', '$builderURL', NOW())";
$result = mysql_query($stmt, $link);
...
...
...
于 2013-05-29T19:07:34.417 回答