I tested your code and found that your submit button was one of the things at fault, including an improperly place semi-colon in:
$query = "INSERT INTO scoreboard (name,percent) VALUES ('$getname','$percentage');"
Which should read as:
$query = "INSERT INTO scoreboard (name,percent) VALUES ('$getname','$percentage')";
Tested using the following form and PHP
<form method="post" action="">
<center>
<font color="green">Your name Max length is 15</font>
<input type="text" name="username" maxlength="15">
<input type="submit" name="submit" value="Submit">
</center>
</form>
<?php
if (isset($_POST['username']))
{
$link = mysqli_connect("myhost","myusername","mypw","mydatabase") or die("Error " . mysqli_error($link));
// $getname = $_POST['username'];
$getname = mysqli_real_escape_string($link,$_POST['username']);
$percentage = "10";
$query = ("INSERT INTO scoreboard (name,percent) VALUES ('$getname',$percentage)");
$result = mysqli_query($link, $query);
if(!$result){
printf("Error message: %s", mysqli_error($link));
}
else {
echo "Data properly inserted with the value of <b>$getname</b> and <b>$percentage</b>";
}
}
?>
NOTE: You will be better off using the code below in order to check if the field is empty. Otherwise, clicking on the submit button without anything inside, will produce an entry in DB with a blank name field.
if (empty($_POST['username'])) {
die("<div align='center'>Enter your name</div>");
}
else
{
// rest of code
Plus as stated by Hanky 웃 Panky, you should sanitize your variables like this, as done in my working example:
$getname = mysqli_real_escape_string($link,$_POST['username']);
Here is a safer (parametrized) method as taken from an example on SO here
Quick note: If you are going to use $percentage = 10;
instead of $percentage = "10";
then you will need to use $stmt->bind_param("si", $unsafe_variable,$percentage);
otherwise, your percentage will be treated as a string, as opposed to an integer and will be thrown an error. s
is for string
and i
is for integer
.
<form method="post" action="">
<center>
<font color="green">Your name Max length is 15</font>
<input type="text" name="username" maxlength="15">
<input type="submit" name="submit" value="Submit">
</center>
</form>
<?php
if (empty($_POST['username'])) {
die("<div align='center'>Enter your name</div>");
}
else
{
$mysqli = new mysqli("myhost","myusername","mypw","mydatabase");
// Check that connection was successful.
if($mysqli->connect_errno > 0) {
die('Connection failed [' . $mysqli->connect_error . ']');
}
$percentage = "10";
$unsafe_variable = $_POST["username"];
$stmt = $mysqli->prepare("INSERT INTO scoreboard (name,percent) VALUES (?,?)");
// TODO check that $stmt creation succeeded
// "s" means the database expects a string
$stmt->bind_param("ss", $unsafe_variable,$percentage);
$stmt->execute();
$stmt->close();
$mysqli->close();
echo "<div align='center'>Data written to DB</div>";
}
?>