用户访问被拒绝' @' localhost'。试图插入PHP Mysql数据

时间:2017-12-28 09:58:04

标签: php mysql database permissions user-permissions

我试图将数据插入我的数据库,但我得到的错误是: 用户访问被拒绝' @' localhost' (使用密码:否)

奇怪的是我可以从我的数据库中选择数据,它也会将这些数据显示在我的表单字段中。

http://sayhey.nl/mealapp/add-ingredients.php

但是当我尝试通过此表单插入新数据时,它会拒绝访问'错误。看起来没有设置用户名或密码,但实际上我确实这样做了:

//Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$database = "databasename";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

这是代码的其余部分:

<?php
//Connect
include 'connect.php';
$ingredient_sql = "SELECT id, name FROM ingredient_cat";
$ingredient_cat_result = $conn->query($ingredient_sql);
?>
<div id="wrapper">
    <form method = "post" action = "<?php $_PHP_SELF ?>">
        <input name="ingredient_name" type="text" id="ingredient-name" />
        <select name="ingredient_cat" id="ingredient-cat">
            <?php
             while($row = $ingredient_cat_result->fetch_assoc()) {
                echo '<option value="'.$row["id"].'">'.$row["name"].'</option>';                 
             }
            ?>
        </select>
        <select name="ingredient_unit" id="ingredient-unit">
            <option value="stuks">stuks</option>
            <option value="gram">gram</option>
            <option value="liter">liter</option>
        </select>
        <input type="submit" name="add" value="Add ingredient" />
    </form>
</div>  
<?php
if(isset($_POST['add'])) {
    $ingredient_name = $_POST['ingredient_name'];
    $ingredient_cat = $_POST['ingredient_cat'];
    $ingredient_unit = $_POST['ingredient_unit'];
    mysql_query("INSERT INTO ingredient(name, unit, cat) VALUES('".$ingredient_name."', '".$ingredient_unit."', ".$ingredient_cat.")")or die(mysql_error());
}
?>

有人知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

您正在混合PDOprocedural way ...

mysql_query(替换为$conn->query(