我试图通过我的网页在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);
}
?>
我收到以下错误:
答案 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%有效。