2014-10-29 31 views
1

我的代碼有問題。我正在嘗試將新帖子添加到表格事件中。我很困惑,因爲我在同一個網站的其他地方使用過這段代碼(但是它使用mysqli_query註冊新用戶)。 mysqql_error返回「無數據庫中選擇」無法使用mysql和php爲表添加值

這是代碼:

<?php 
$add_title = $_POST['add_title']; 
$add_happen = $_POST['add_happen']; 
$add_created = date('Y-m-d'); 
$add_content = $_POST['add_content']; 
$add_author = $_POST['add_author']; 

//connect to 
    //localhost 
$db_host = "localhost"; 
$db_username = "root"; 
$db_password = ""; 
$db_dbname = "zhp2"; 
$db_con = mysql_connect($db_host, $db_username, $db_password, $db_dbname); 

$query = " 
    INSERT INTO events (title, happen, created, content, author) 
    VALUES ('$add_title', '$add_happen', '$add_created', '$add_content', '$add_author')) 
"; 

$retval = mysql_query($query, $db_con); 
if(! $retval){ 
    die('Could not enter data: ' . mysql_error()); 
} 
else{ 
    echo "Entered data successfully\n"; 
} 

mysql_close($db_con); 

//header('Location: ../../index.php?link=events');?> 

我要修復使用試錯法的不同組合打兩mysql_query中mysqli_query它試圖

+4

請,或不使用'mysql_ *'功能(http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php),它們不再維護和[正式棄用](https://wiki.php.net/rfc/mysql_deprecation)。學習[準備的語句](http://en.wikipedia.org/wiki/Prepared_statement),並使用[PDO](http://us1.php.net/pdo)或[MySQLi](http:// us1.php.net/mysqli)。[本文](http://php.net/manual/en/mysqlinfo.api.choosing.php)將幫助你決定。 [防止SQL注入!](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – 2014-10-29 17:06:03

+0

你有一個額外的)在$查詢語句的末尾。 .. – Rich701 2014-10-29 17:09:58

回答

4

那麼,你需要選擇數據庫! ;)mysql_connect()的第四個參數不是數據庫名稱。您需要單獨連接到MySQL服務器。

使用mysql_select_db()功能:

$db_host = "localhost"; 
$db_username = "root"; 
$db_password = ""; 
$db_dbname = "zhp2"; 
$db_con = mysql_connect($db_host, $db_username, $db_password); 
mysql_select_db($db_dbname, $db_con); 

,當然所有的強制性約SQL injection警告,消毒數據,deprecation of mysql_* functions

0

您需要選擇要連接到使用mysql_select_db功能的數據庫:

// make $db_dbname the current db 
$db_selected = mysql_select_db($db_dbname, $db_con); 
if (!$db_selected) { 
    die ("Can't use $db_dbname : " . mysql_error()); 
} 

詳情參見PHP手冊:http://php.net/manual/en/function.mysql-select-db.php

3

你感到困惑mysql_connectmysqli_connect功能的方式你傳遞這些參數。在您的例子:

$db_con = mysql_connect($db_host, $db_username, $db_password, $db_dbname); 

你逝去的第四個參數,它是數據庫名稱但不會工作,你應該只通過三個第一(主機,用戶名,密碼),然後調用mysql_select_db()

$db_con = mysql_connect($db_host, $db_username, $db_password); 
mysql_select_db($db_dbname, $db_con); 

mysqli這是做它的更好方式,因爲mysql_功能都非常脆弱,從php被棄用,你可以通過四個要素喜歡這裏:

$db_con = mysqli_connect($db_host,$db_username, $db_password, $db_dbname) or die("Error " . mysqli_error($link)); 

這是接近你正在嘗試做的,但在一個正確的mysqli_方式。