Add values to database on button click [closed]

You’re mixing server-side code and client-side code. A lot.

Server-side code (PHP in this case) executes on the server when the page is requested. It executes in its entirety, and then displays the page. This is your server-side code:

$servername = "";
$username = "root";
$password = "ahmed2001";
$db = "html";
$conn = mysqli_connect($servername, $username, $password, $db);
if(!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$user = $_POST['value'];
$pass = $_POST['value2'];
$em = $_POST['value3'];
$sql = "INSERT INTO players (username, password, email)
VALUES ('$value', '$value2', '$value3')";
if (mysqli_query($conn, $sql)) {
    echo "New record created succeddfully !";
} else {
    echo "Error : " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);

When the page first loads, there are no $_POST values. (And even if there were, you’re not using those values in your SQL query. You’re using variables that were never defined.) So you’re just inserting empty strings into your database. (Also note that this code has a SQL injection vulnerability. You’ll want to read up on that.)

Then, after this code has executed, the page is rendered in the browser and the client-side code executes. This is your client-side code:

function myFunction() {
    New record created succeddfully !
}

For one thing, this isn’t valid JavaScript code. For another thing, this function doesn’t do anything. You’re undoubtedly getting an error in your browser’s console, so you should take a look at that. But even if you remove that line of non-code, you still just have an empty function. You can call that function all you like, it won’t do anything.

You’re going to want to start with some introductory tutorials on PHP, to be honest. Basically, in order for the client-side code to send values to the server-side code, those values need to be posted to the server in a request of some kind. It can be a form post, or maybe an AJAX request, or possibly something else. But you can’t mix the server-side code and the client-side code.

Leave a Comment