Ciaran Quigley
Ciaran Quigley

Reputation: 15

How do I send data from my javascript/php code to mySQL server?

I'm having major problems uploading data to mySQL server, and have no clue how to go about it. I have searched up solutions and this is my current attempt:

function documentReady(){
      $.ajax({
        type: "POST",
        url: "/phpServerContent.php",
        data: {CollegeID: simData.userID, FirstName: "Bob", LastName: "Smith", ClassID: simData.userClassSelected},
        cache: false,
        success: function(html){
        } 
      });
};

and this is my PHP:

 <?php
 mysql_connect("localhost","root");
  mysql_select_db("userdatagravsim");
  $result_set=mysql_query("SELECT*FROM users");
  $num_messages=mysql_num_rows($result_set);


   $CollegeID=$_POST["CollegeID"];
   $FirstName=$_POST["FirstName"];
   $LastName=$_POST["LastName"];
   $ClassID=$_POST["ClassID"];

   $query=mysql_query("INSERT INTO users(CollegeID,FirstName,LastName,ClassID)values('$name','$guessnum','$taskid','$effort')");

   if($query){
      echo "Your comment has been sent";
      }
   else{
      echo "Error in sending your comment";
       }

    ?>

I'm very new to programming, this is for A-level coursework. I am also unsure about how to view the echo flags to indicate if the upload has worked or not.

Upvotes: 1

Views: 46

Answers (1)

toximorph
toximorph

Reputation: 48

First of all, I recommend you not to use mysql_query as it's depreciated and risky.

I think the best way is to use PDO_MySql extension in order to connect to your database and to make request.

This is what you should do to my mind:

<?php       
    private static $dns = "mysql:host=localhost;dbname=userdatagravsim";
    private static $user ="root";
    private static $password = "";
    static $connexion =new PDO($dns, $user, $password);
?>

This code wil connext you to the database, yo can put it in a specific file (db_connect.php for example) and call it with require_once when you need to do request.

Now for the request:

<?php
    require_once 'path_to_db_connect.php';

    $request = $connect->prepare('INSERT INTO users(CollegeID,FirstName,LastName,ClassID) values(?,?,?,?);');
    //The ? will be replace when query will be execute
    $request->execute(array($name,$guessnum,$taskid,$effort));

    if(!$request){
        echo 'Error with INSERT';
    } 
    else {
        echo 'INSERT success';
    }
?>

Hope it helps !

Upvotes: 1

Related Questions