更新:
这个问题已得到解答
我有一个简单的表单,用户可以更新他们的mysql数据库。我使用mysql_
连接到数据库但是已经了解到pdo是一种更好的方法,因为mysql_
被折旧了。
下面是OLD方式的完整形式,然后是完整形式的新方式。 新方法产生错误
老路:
<?php
$host = 'ip_address';
$user = 'user_name';
$password = 'password';
$link = mysql_connect($host, $user, $password);
$selected = mysql_select_db('db_name', $link);
if(!isset($_POST['text-input']))
?>
<form method="post">
%slice%
<input type="submit" value="Submit" />
</form>
%[if !edit]%
<?php
%[repeat items]%
$form_input%id=repeatIndex% = $_POST['element-%id=repeatIndex%'] ;
%[endrepeat]%
$query = 'INSERT INTO `table_name` (%[repeat items]%%[endif]%%html="Edit Me"%%[if !edit]%,%[endrepeat]%) VALUES (%[repeat items]%"' . $form_input%id=repeatIndex% . '",%[endrepeat]%);';
$query = preg_replace('/,\);/',');',$query);
$query = preg_replace('/,\) /',')',$query);
mysql_query($query);
?>
%[endif]%
新方式:
<?php
db = new PDO('mysql:host=ip_address;dbname=db_name;', 'user_name', 'password');
?>
<form method="post">
%slice%
<input type="submit" value="Submit" />
</form>
%[if !edit]%
<?php
%[repeat items]%
$form_input%id=repeatIndex% = $_POST['element-%id=repeatIndex%'] ;
%[endrepeat]%
$query = 'INSERT INTO `table_name` (%[repeat items]%%[endif]%%html="Edit Me"%%[if !edit]%,%[endrepeat]%) VALUES (%[repeat items]%"' . $form_input%id=repeatIndex% . '",%[endrepeat]%);';
$query = preg_replace('/,\);/',');',$query);
$query = preg_replace('/,\) /',')',$query);
mysql_query($query);
?>
%[endif]%
抛出的错误是:
Warning: mysql_query() [function.mysql-query]: Access denied for user
'kuler'@'localhost' (using password: NO) in
/home/path_to/index.php on line 125
Warning: mysql_query() [function.mysql-query]: A link to the server could not be
established in /home/path_to/index.php on line 125
我希望我提供了足够的信息。
答案 0 :(得分:1)
解决方案如下:
<?php
//Connection vars
$host = '%id=server%';
$user = '%id=username%';
$password = '%id=password%';
$databasename = '%id=database%';
//This block establishes the connection
try{
//
$connectiondetails = "mysql:host={$host};dbname={$databasename}";
$db = new PDO($connectiondetails , $user , $password);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
//Check if all the input fields of the form have been submitted
if(
%[repeat items]%
isset($_POST['element-%id=repeatIndex%'])&&
%[endrepeat]%
(true===true)
){
//The variables to read the output
%[repeat items]%
$form_input%id=repeatIndex% = $_POST["element-%id=repeatIndex%"] ;
%[endrepeat]%
//DB
global $db; //must set this, otherwise can't access the db
$query = 'INSERT INTO `%id=table%` (%[endif]%%[repeat items]%%html="Edit Me"%%[if !edit]%,%[endif]%%[endrepeat]%%[if !edit]%)%[endif]% %[if !edit]%VALUES (%[repeat items]%"' . $form_input%id=repeatIndex% . '",%[endrepeat]%);';
$query = preg_replace('/,\);/',');',$query);
$query = preg_replace('/,\) /',')',$query);
$db->query($query);
//[DB]
}
?>