我希望通过php在mysql中创建一个数据库但我得到访问被拒绝错误。这是代码:
<form action = "createdb.php" method = "post">
<label for = "dbname">database name to be created</label><br>
<input type = "text" name = "dbname" /><br>
<input type = "submit" name = "submit" value = "submit"/>
</form>
<?php
if(isset($_POST['submit'])){
$server = 'localhost';
$uname = 'root';
$pass = 'jooko';
$dbname = $_POST['dbname'];
$createdb = "CREATE DATABASE `$dbname`";
$connect = mysql_connect(`$server`,`$uname`,`$pass`);
//$queryuse = "USE '$dbname'";
$result = mysql_query($createdb, $connect);
if(!$result){echo mysql_error();}
?>
任何帮助将不胜感激。谢谢。
答案 0 :(得分:0)
弃用通知: Don't use mysql_*
functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDO或MySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial。
此外,函数参数中的反引号也会导致问题。这就是PDO的用法。
<form action = "createdb.php" method = "post">
<label for = "dbname">database name to be created</label><br>
<input type = "text" name = "dbname" /><br>
<input type = "submit" name = "submit" value = "submit"/>
</form>
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$server = 'localhost';
$uname = 'root';
$pass = 'jooko';
$dbname = $_POST['dbname'];
try {
$pdo = new PDO("mysql:host=".$server.";", $uname, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbname = "`".str_replace("`", "``", $dbname)."`";
$pdo->query("CREATE DATABASE IF NOT EXISTS ".$dbname);
echo 'Database created.';
}catch (Exception $e){
echo $e->getMessage();
}
}
?>
如果您仍然有访问被拒绝的问题,请检查root密码是否正确。
答案 1 :(得分:0)
我做到了。问题是登录数据的$ connect变量中的后引号。不得不删除$ uname和$ pass的后引号...不知道为什么它必须是这样但它的工作原理。谢谢。