通过html向mysql表添加新值

时间:2016-04-29 12:24:29

标签: php html mysql css

我试图通过我的网页在mysql上添加新元素到我的数据库。

这是我到目前为止所得到的

<form action="MyCurrentPage.php" method="post" >
<label for="playername"> Player </label>
<input type="text" name="addplayer" id="playername"/>
<input type= "submit" value="submit" name="submit"/>
</form>

和这个

<?php
 if (isset($_POST['submit'])) {
     $addplayerv=$_POST['addplayer'];
     $mysqli->select_db("player", $player);

     $sql="INSERT INTO player (nameofplayer) VALUES ('".$addplayerv."')";
    $mysqli->query($sql, $mysqli);
    $mysqli->close($mysqli);
     }


?>

我收到以下错误:

  • 注意:未定义的变量:播放器
  • 警告:mysqli :: select_db()需要1个参数,2个给定
  • 警告:mysqli :: query()期望参数2为整数,对象 给定
  • 警告:mysqli :: close()需要0个参数,1个给定

4 个答案:

答案 0 :(得分:0)

您尚未声明$player您应该先执行此操作。 如果您使用select_db(),则$mysli函数是不必要的: $mysqli = new mysqli("localhost", "user", "password", "database");

在使用此行执行以下步骤后,您的查询应该执行: mysqli_query($mysqli,"INSERT INTO player (nameofplayer) VALUES ('".$addplayerv."')");

答案 1 :(得分:0)

从错误中可以看出;  1.您似乎没有数据库连接。  2.首选PDO到mysqli _

我会这样做:

<?php
//DATABASE CONNECTION CONFIGURATION:
defined("HOST")     or define("HOST",   "localhost");           //REPLACE WITH YOUR DB-HOST
defined("DBASE")    or define("DBASE",  "my_database");         //REPLACE WITH YOUR DB NAME
defined("USER")     or define("USER",   "root");                //REPLACE WITH YOUR DB-USER
defined("PASS")     or define("PASS",   "root");                //REPLACE WITH YOUR DB-PASS


if (isset($_POST['submit'])) {
    $playerName     = htmlspecialchars(trim($_POST['addplayer']));  //PROTECT AGAINST ATTACKS

    try {
        $dbh        = new PDO('mysql:host='.HOST.';dbname='. DBASE,USER,PASS);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $stmt       = $dbh->prepare("INSERT INTO player (nameofplayer) VALUES (:name)");
        $stmt->bindParam(':name', $playerName);
        $stmt->execute();

        //GARBAGE COLLECTION 
        $dbh        = null;
    }catch(PDOException $e){
        echo $e->getMessage();
    }


}

我希望这会有所帮助......

答案 2 :(得分:0)

<?php
    if (isset($_POST['submit'])) {
        $addplayerv=$_POST['addplayer'];
        $mysqli->select_db("player");

        $sql="INSERT INTO player (nameofplayer) VALUES ('".$addplayerv."')";
        $mysqli->query($sql);
        $mysqli->close();
    }
?>

select_db()需要一个参数:您正在使用的数据库的名称 query()只需要sql查询 close()不期望任何参数。

答案 3 :(得分:0)

使用此代码: -

$con=mysqli_connect($host,$username,$password,$dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();}
if (isset($_POST['submit'])) 
{
$addplayerv=$_POST['addplayer'];
mysqli_select_db($con,"player");
$sql="INSERT INTO player (nameofplayer) VALUES ('".$addplayerv."')";
mysqli_query($con,$sql);

} mysqli_close($ CON);

这将100%有效。