popeye
popeye

Reputation: 291

PHP Javascript Mysql Insert

I am trying to use java-script prompt to insert values into MySQL. I have a html file and a php file.

The html files saved as Test.html:

 <button onclick="myFunction()">Create Project</button>

<script>
  function myFunction() {
      var project = prompt("Please enter project name");
      if (project != null && project !="") {
          $.post("conn.php", { project : project });
      }
  }
  </script>

The conn.php:

<?php
$servername = "localhost";
$username = "root";
$password = "Password";
$dbname = "db1";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$proj = $_POST['project'];
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";


if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?> 

The conn.php works perfectly and inserts values if I remove the post parameter.

For example, instead of this:

$proj = $_POST['project'];
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";

if i use:

$proj = "NewProject";
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";

NewProject gets inserted into the database.

I am not sure if I am missing something in my index.html which is not posting the value in the prompt to php script. I have tried echo $_POST['project']; instead of inserting into MySQL. The echo is missing.

Upvotes: 1

Views: 3851

Answers (1)

Sanjay Kumar Singh
Sanjay Kumar Singh

Reputation: 937

I have run your given code, it runs only i have added the jquery link above script code

Please check this correction,

<button onclick="myFunction()">Create Project</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
  function myFunction() {
      var project = prompt("Please enter project name");
      if (project != null && project !="") {
          $.post("conn.php", { project : project },function(response){
             console.log(response);
         });
      }
  }
  </script>

and also i have added isset() function with $_POST param in conn.php file

<?php
$servername = "localhost";
$username = "root";
$password = "Password";
$dbname = "db1";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$proj = isset($_POST['project'])?$_POST['project']:'';
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";


if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?> 

Upvotes: 4

Related Questions