如何通过php代码在mysql服务器上添加用户?

时间:2016-11-29 18:25:31

标签: php mysql authentication

我已经创建了简单的代码,必须通过PHP在mysql上添加用户,但它并没有。这是代码。

<form action='' method='post'>
Login: <input type='text' name='login' /> <br/>
Pass: <input type='pass' name='pass' /> <br/>
<input type='submit'>
</form>

<?php
$c=mysql_connect('localhost','test','test');

$login=$_POST['login'];
$pass=$_POST['pass'];

$t="CREATE USER '".$login."'@'localhost' IDENTIFIED BY PASSWORD '".$pass."';";

if($login!=NULL){
  if($q=mysql_query($t,$c))
  {
    echo "CREATED!";
  }else{
    die('ERROR: ' . mysql_error());
  }
}
?>
  

错误:密码哈希值应为41位十六进制数

它有什么不对吗?

2 个答案:

答案 0 :(得分:0)

取出PASSWORD这个词。通过使用该关键字,它建议您提供哈希值。 dev.mysql.com/doc/refman/5.5/en/create-user.html

你想要这个:

$t="CREATE USER '".$login."'@'localhost' IDENTIFIED BY '".$pass."';";

答案 1 :(得分:0)

试试这个:

 <?php
 $host="localhost";
 $user="root";
 $password="";
 $con = mysqli_connect("localhost","root","","mydb");
 // Check connection
 if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }
?>

<!DOCTYPE html>
  <head>
      <title>MyExample</title>
    <meta charset="UTF-8"/>
</head>
<body>
    <h1>Create user in MySQL by FORM</h1>
    <form action="<?php $_SERVER['PHP_SELF']?>" method="POST">
        <label for="username">Username</label>
        <input type="text" id="username" name="username" />
        <label for="password">Password</label>
        <input type="password" id="password" name="password"/>
        <button type="submit" name="send">Send</button>
    </form>
</body>
</html>
 <?php 
    if (isset($_POST['send'])) {
        $username = $_POST['username'];
        $password = $_POST['password'];
        mysqli_query($con,"CREATE USER '".$username."'@'".$host."' IDENTIFIED BY '".$password."'");
        mysqli_close($con);
    }
  ?>