How to use javascript variable in php sql query
I am running a mysql select query in php like this Show
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:
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:
php:
Otherwise, you could use:
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
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. Writing in the DataBaseThe JavaScript function below collects the variables and posts them to the savesettings.php file. 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. 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 . " At this point we’re able to write to the database, let’s see how to read the data. Reading from the DataBaseJust 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. 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 "
Bài Viết Liên QuanQuảng CáoCó thể bạn quan tâmToplist được quan tâm#1
Top 7 sự tích hồ gươm - ngữ văn lớp 6 20234 tháng trước#2
Top 7 gdcd 6 bài 1 kết nối tri thức 20234 tháng trước#3
Top 7 ý nghĩa của xây dựng gia đình văn hóa 20234 tháng trước#4
Top 6 mẫu hợp đồng mượn đất làm nhà xưởng 20234 tháng trước#5
Top 3 tổng tài biến thái tôi yêu anh tập 27 20234 tháng trước#6
Top 6 kết thực phim mỹ nhân vô lệ 20234 tháng trước#7
#8
Top 8 đề tài và chủ de của tác phẩm tắt đèn 20234 tháng trước#9
Top 5 tiểu sử của thầy thích pháp hòa 20234 tháng trướcQuảng cáoXem NhiềuTop 10 tiền đạo hay nhất thế giới 2023 năm 20241 tuần trướcCọng tác viên r và d là làm gì năm 20249 giờ trướcSo sánh iphone 7 và sony z5 năm 20241 tuần trướcBảng giá xe i10 lăn bánh gia bao nhiêu năm 20242 ngày trướcThể thức kỹ thuật trình bày văn bản năm 20246 ngày trướcBộ đề ôn thi toán tuyển sinh lớp 10 năm 20244 ngày trướcQuảng cáoChúng tôiTrợ giúpBản quyền © 2021 Học Tốt Inc.
|