How to use javascript variable in php sql query

I am running a mysql select query in php like this


var1 and var2 are javascript variables on the same page. I know client side variable cannot be passed to server side. But is there any workaround as the variables are in the same page.

asked May 2, 2014 at 19:45

2

In order for you to make this happen - I believe - you have to use AJAX.

The code will look like this:

        $.ajax({
            url: 'your_script.php',
            type: 'POST',
            data: {var1: javascript_var_1, var2: javascript_var_2},
            success: function(data) {
                console.log("success");
            }
        });

Your PHP will look similar to this (without keeping in mind the JSON encode:


Then you can JSON encode the results and pretty much output them on the success. Your php script - however - must live on another php file.

Also, escape your data. Use prepared statements.

answered May 2, 2014 at 19:52

JJPPJJPP

7692 gold badges10 silver badges26 bronze badges

2

In theory, you could pass the vars to php via some sort of ajax call. I think it would go something like...

JavaScript:

var data = {
    'var1': $('selector').val(),
    'var2': $('selector').val()
};

$.ajax({
    type: 'post',
    url: 'path-to-your-file.php',
    data: data,
    timeout: 50000
}).done(function(response) {
    console.log(response);
}).fail(function(error) {
    // uh-oh.
});

php:

Otherwise, you could use:

  • cookie
  • hidden input

php:

NOTE: you will want to sanitize the data. Using raw cookie and/or input values could lead to some less than desirable results.

answered May 2, 2014 at 19:57

DamonDamon

3,6868 gold badges41 silver badges88 bronze badges

Use Method Post in AJAX or Form!! To send js variable in Php and receive it in php using $_post[ name_of_obj ];

answered May 2, 2014 at 19:56

How to use javascript variable in php sql query

ashbuildsashbuilds

1,39116 silver badges33 bronze badges

We will show you the way how to save JavaScript variables to a PHP/MySQL DataBase easily and securely. In my demonstration we’ll go through an example in which we want to store an array for my users. The users can be identified by their unique names.

Log in to to your cPanel hosting, find the “MySQL Databases” in the menu and create a new database. Create a user and add it to the database, checking all privileges. We’ll use this user to connect to the DB.

Open phpMyAdmin and you should see the new DB in the list. Select it and make a new table. In my example I’ll call it usertimes.
Set to auto increment (A_I) the primary key and make sure the name field is a unique value. We’ll store the current save date and the rest of the variables depends on your specifications. Save the settings when it’s done. My database is ready to receive input.

How to use javascript variable in php sql query

Writing in the DataBase

The JavaScript function below collects the variables and posts them to the savesettings.php file.
The #saveWarningText div will display the success message returned from the PHP file or the error message if something went wrong.
The three variables we’re passing are the name, amount and times because the id is automatically incremented and the date can be generated on the server side.

function saveUserTimes() {
    $.post("savesettings.php",
    {
        name: $("#userName").val(),
        amount: aGlobalVariable,
        times: '1,2,3,4,5,6,7',
    },
    function(data,status){
        document.getElementById("saveWarningText").innerHTML = data;
        $( "#saveWarningText" ).fadeIn(100);
        setTimeout(function(){ $( "#saveWarningText" ).fadeOut(100); }, 3000);
    });
}

Create a PHP file to decode the post parameters and insert them into the DB.
At the beginning of the file we specify the database connection string.
Next we receive the three variables passed with the post method and escape the string to avoid SQL injections and ensure security.
Remember that JavaScript is executed on the client-side so everyone check and see the parameters we’re posting to our PHP file. Knowing our post variables hackers can try to execute database queries through our file. This is why beside the string escaping I’m also testing the length of the ‘times’ string and I’m not allowing to store it if the data is too large. You can include additional security steps to avoid hackers. Allowing only a limited amount of queries from one IP address can reduce the risk that someone will flood our database.
In the following lines we create the $sql query. We insert into the usertimes database table the name, date, amount and times variables. The id is automatically set, and the date is using the CURDATE() query. In case the current name value already exists in the database the 3 other variables are updated in that row. This is how the duplicate key is handled in my example.

Contents of savesettings.php file:

$servername = "localhost";
$username = "databaseUserName";
$password = "userPassword";
$dbname = "databaseName";

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

$name = mysqli_real_escape_string($conn, $_POST['name']);
$amount = mysqli_real_escape_string($conn, $_POST['amount']);
$times = mysqli_real_escape_string($conn, $_POST['times']);

if (strlen($times) > 200000) {  $times = "";    }

$sql = "INSERT INTO usertimes (name,date,amount,times)
VALUES ('$name', CURDATE(), '$amount', '$times') ON DUPLICATE KEY UPDATE    
date=CURDATE(), amount='$amount', times='$times'";

if ($conn->query($sql) === TRUE) {
    echo "Page saved!";
} else {
    echo "Error: " . $sql . "
"
. $conn->error; } $conn->close(); ?>

At this point we’re able to write to the database, let’s see how to read the data.

Reading from the DataBase

Just like for the writing, we need a JavaScript function to send the variable to the PHP file and to process the retrieved data.

function openUserTimes(username) {
    $.post(
        "returndata.php",
        { name: username },
        function(response) {
            var myvariable = response.amount;
            var times = response.times;

            console.log('Retreived data: ', myvariable, times);
        }, 'json'
    );  
}

The only data we send in this example is the user name for which we want to get the two variables and log them in the console.

The PHP file starts with the connection string, then receives the username posted from the JavaScript. Next is the SQL query which selects everything in the DB table where the name field matches the current username.
Finally we package the returned data into JSON format which can be easily decoded by JavaScript.

The JSON format generated by the PHP:

{"name":"JohnDoe","date":"2017-02-01","amount":"4","times":"1,2,3,4"}

Contents of returndata.php file:

header('Content-type: application/json');

$servername = "localhost";
$username = "databaseUserName";
$password = "userPassword";
$dbname = "databaseName";

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

$name = mysqli_real_escape_string($conn, $_POST['name']);

$sql = 'SELECT * FROM usertimes WHERE name ="'. $name. '"';

$result = $conn->query($sql);
$response = array();

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $response['name'] = $row["name"];
        $response['date'] = $row["date"];
        $response['amount'] = $row["amount"];
        $response['times'] = $row["times"];
    }
    echo json_encode($response);
} else {
    echo "  0 results";
}
$conn->close();     
?>

How use JavaScript variable in SQL Query PHP?

php $var1 = $_POST['var1']; $var2 = $_POST['var2']; $getvalue="SELECT id,name from table1 WHERE column1='$var1' and column2='$var2'"; $result=mysql_query($getvalue) or die(mysql_error()); while($row=mysql_fetch_array($result)){ extract($row); echo $name; } ?>

Can I use JavaScript variable in PHP?

The way to pass a JavaScript variable to PHP is through a request. This type of URL is only visible if we use the GET action, the POST action hides the information in the URL. Server Side(PHP): On the server side PHP page, we request for the data submitted by the form and display the result. $result = $_GET [ 'data' ];

How use JavaScript variable on same page in PHP?

You can easily get the JavaScript variable value on the same page in PHP. Try the following codeL. php echo "