-2

I am creating a website where it sends values from a JavaScript object into a MySQL database via PHP

Here is the code:

<!DOCTYPE html>
<html>
<body>
<p>Creating a JavaScript Object.</p>

<p id="demo"></p>

<script>
    var person = {
    firstName : "John",
    lastName  : "Doe",
    age       : 50,
    eyeColor  : "blue"
};

</script>

</body>
</html>

Overall, my question is how to send the objects data to the MySQL using PHP?

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";
?>

If I type the code in before it prints out:

connect_error) {die("Connection failed: " . $conn->connect_error);} echo "Connected successfully";?>

halfer
  • 19,824
  • 17
  • 99
  • 186
  • Modern PHP development encourages the use of a [development framework](http://codegeekz.com/best-php-frameworks-for-developers/) like [Laravel](http://laravel.com/) that gives you a solid foundation for building your application. Find one that suits your style and needs and follow the examples and documentation. Most have a large library of community code you can add in with little effort, avoiding the need to reinvent the wheel. Most of these provide a very easy method for capturing data from an API call and saving it in the database, though the details vary by framework. – tadman Jan 27 '15 at 22:57
  • however it gives me errors about connecting. how would you connect – Daniel Schwartz Jan 27 '15 at 22:58
  • what "it" what "errors" ?? there is no mysql or php of any kind in the code, just some hard coded js variables –  Jan 27 '15 at 22:59
  • but how do i connect? @tadman – Daniel Schwartz Jan 27 '15 at 22:59
  • connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; ?> – Daniel Schwartz Jan 27 '15 at 23:00
  • if i type that in, it returns – Daniel Schwartz Jan 27 '15 at 23:00
  • connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; ?> – Daniel Schwartz Jan 27 '15 at 23:01
  • i have never seen php called *hard*, its the easiest language i have eve seen (not saying that's a good thing) –  Jan 27 '15 at 23:01
  • This may be a duplicate of [How to pass JavaScript variables to PHP?](http://stackoverflow.com/questions/1917576/how-to-pass-javascript-variables-to-php). Also, it is rather broad at present, and may also close for that reason. You may wish to research into AJAX, the topic of the current answer below. – halfer Jan 28 '15 at 00:31

1 Answers1

2

It sounds to me like you are trying to jump from not knowing how to work with PHP and MySQL to also adding JavaScript.

First let me give you an example of how to work with all of those things. Here is the repo with all of these files: https://github.com/Goddard/simplelogin-example.

This is what connects you to the database:

<?php
error_reporting(E_ALL);
ini_set('display_errors',1);

define("__DB_NAME__", 'job');
define("__DB_DSN__", 'mysql:dbname=' . __DB_NAME__ . ';host=127.0.0.1');
define("__DB_USERNAME__", 'root');
define("__DB_PASSWORD__", '');

if(session_id() == '') {
  session_start();
}

if(!isset($_SESSION['username']))
{
    $_SESSION['username'] = NULL;
}

//database setup
try {
    $db = new PDO ( __DB_DSN__, __DB_USERNAME__, __DB_PASSWORD__ );
    $db->query ( "use " . __DB_NAME__);
}

catch ( PDOException $e ) {
    echo 'Could not connect : ' . $e->getMessage ();
}
?>

This is what works with the database information:

<?php

include("db.php");

if(trim(htmlentities(addslashes(filter_input(INPUT_GET, 'type')), ENT_QUOTES)) === "loginUser")
{
    try {
        $username = trim(filter_input(INPUT_GET, 'username'));
        $password = trim(filter_input(INPUT_GET, 'password'));

        $fetch = $db->prepare("SELECT * FROM `users` WHERE user_name = :username");
        $fetch->bindParam(':username', $username, PDO::PARAM_STR);
    $fetch->execute();
        $result = $fetch->fetch(PDO::FETCH_OBJ);

        if($result)
        {
            if(password_verify($password, $result->password_hash))
            {
                $currentDateTime = date('Y-m-d H:i:s');

                $update = $db->prepare("UPDATE `users` SET `last_login` = :lastlogin WHERE `client_id` = :clientid");
                $update->bindParam(':lastlogin', $currentDateTime);
                $update->bindParam(':clientid', $result->client_id);
                $loginUpdate = $update->execute();

                $resultArray['error'] = 0;
                $resultArray['errorMessage'] = "None";
                $resultArray['userName'] = $result->user_name;
                $_SESSION['username'] = $result->user_name;

                echo json_encode($resultArray);
            }

            else
            {
                $resultArray['error'] = 1;
                $resultArray['errorMessage'] = "Incorrect Password";
                echo json_encode($resultArray);
            }
        }

        else
        {
            $resultArray['error'] = 1;
            $resultArray['errorMessage'] = "Incorrect Username";
            echo json_encode($resultArray);
        }

    } catch (PDOException $e) {
        $resultArray['error'] = 1;
        $resultArray['errorMessage'] = $e->getMessage();
        echo json_encode($resultArray);
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Goddard
  • 2,863
  • 31
  • 37