Save results from pdo query to a javascript variable - javascript

I am new to javascript so please be patient with me.
I have a function in php which goes like this:
public function getSubjects() {
$stmt = $this->_db->prepare('SELECT id, subject from subjects');
$stmt->execute();
return $stmt->fetchall();
}
Then I have a variable subs in javascript which is hardocded like this:
var subs = {"Maths":1,"Geography":2,"Chmesitry":3,"Literature":4};
How do I populate the subs variable with the format above from the getSubjects method?

I like to use json_encode to convert the array to json so it can be used as an array of objects in JS.
PHP:
public function getSubjects() {
$stmt = $this->_db->prepare('SELECT id, subject from subjects');
$stmt->execute();
return json_encode($stmt->fetchall());
}
In javascript:
var subs = <?php echo getSubjects(); ?>;
console.log(subs);

Related

send data from php array in javascript forEach loop to url of ajax call

I'm trying to loop through the results of a mysql query in php, the output of the query is an array similar to [10201,10202]. I want to take the results and loop it to the variable named id in my javascript function and loop it through the url of my ajax call. The goal is to take the id and use it in a sql query on another page to change the date of the id in our database.
mysql query:
<?php
// sql query for # print all open orders function
$sql = "SELECT Order_PID
FROM `Order`
WHERE SHIPDATE IS NULL
AND Address1 IS NOT NULL;";
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($query)) {
$order[] = $row['Order_PID'];
}
?>
javascript function:
I'm trying to use a forEach function to iterate through the results of the array.
$('button#printOpenOrders').on('click', function(e) {
if(confirm("Are you sure you want to print all open orders and mark them as pending?")) {
e.preventDefault();
// prints all open orders
window.open("/resources/scripts/allOpenPDF.php");
var arr = $order;
arr.forEach(function(id) { // <====this function
$.ajax({
url: "/resources/scripts/pending-order.php?id=" + id, // <===this variable
datatype : "string",
success : function(data) {
location.reload(true);
}
})
})
}
});
and if it helps here is my callback script
<?php
// login validation
session_start();
if (!isset($_SESSION['loggedin']) && $_SESSION['loggedin'] != true) {
$url = $_SERVER['DOCUMENT_ROOT'].'/index.php';
header("Location: ../../index.php");
}
// establish connection to database
include $_SERVER['DOCUMENT_ROOT'].'/resources/scripts/dbconnect.php';
$conn = openConnection();
// capture id
$id = $_GET['id'];
$pendingDate = date_create_from_format("m/d/Y", "07/26/1996");
$pendingDate = date_format($pendingDate, "Y-m-d H:i:s");
$sql = $conn->prepare("UPDATE `Order`
SET SHIPDATE = ?
WHERE Order_PID = ?");
$sql->bind_param("si", $pendingDate, $id);
$sql->execute();
echo "success";
closeConnection($conn);
?>
If parts of my code don't make sense, I'm new to this and I am using my currently limited knowledge to frankenstein all of this together. Any nudges in the right direction would be super helpful.
You can output $order variable contents, but you need to use PHP and also you must encode it using json format, so this could actually work:
var arr = <?PHP echo json_encode($order); ?>;
But it is error-prone, the syntax is not really nice to read, and if that variable somehow becomes in the format you are not expecting it could lead to another JavaScript syntax error.
But the best way in my opinion would be to make an AJAX request and get those order IDS, and after that you could create another AJAX request that would send all those Order IDS,
so you wouldn't need .forEach stuff and your logic of handling multiple orders need to be modified in order to accommodate for these changes.
But since you already have those IDS in PHP I mean stored in $order variable, you could just encode it and send it all the ids at once in a single request.

shorter way to collect and send data without a form

I have some (15) input, select, and textarea tags on page - without a form
need to collect their values and insert them into a database
this code works fine, but I hope there is a way to short it
on client side - maybe some kind of serialize
on server side - especially on execute statement - maybe some kind of loop
$('#btn_send').on('click', function(){
let obj = {};
$('input, select, textarea').each(function(){
let a = $(this).attr('name');
obj[a] = $(this).val();
});
let str = JSON.stringify(obj);
$.post('reg.php', {fn: 'btn_send', args: [str]}, function(data){
console.log(data);
});
});
reg.php
function btn_send($str){
global $db;
$obj = json_decode($str);
// here are table columns
$a = "name,birth,gender,city,state,gmail,fb,tw,web,phone,occ,food,note,uname,pass";
$b = ':a' . str_replace(',', ', :a', $a);
$sq = "insert into members ($a) values ($b)";
$st = $db->prepare($sq);
$st->execute([
":aname" => $obj->name,
":agender" => $obj->gender,
//... and so on - 15 items
]);
echo 'success';
}
Based on your code sample, it looks like the elements of your object have the same names as the columns in your table. In that case, you can simplify your code by converting the incoming JSON to an array rather than an object and utilising the fact that PDOStatement::execute allows the array keys to not include the : in the names:
$obj = json_decode($str, true);
// here are table columns
$cols = array_keys($obj);
$a = implode(',', $cols);
$b = ':a' . str_replace(',', ', :a', $a);
$sq = "insert into members ($a) values ($b)";
$st = $db->prepare($sq);
$st->execute($obj);
Should the behaviour of execute change in the future, you can make an array with the keys preceded with : using array_combine and array_map:
array_combine(array_map(function ($k) { return ":$k"; }, $cols), $obj)
You would then pass this array to execute in place of $obj.
Something I made not sure if it even compiles, just was bored this is how I would do the 15 items or so part.
function btn_send($str){
global $db;
$obj = json_decode($str);
// here are table columns
$a = "name,birth,gender,city,state,gmail,fb,tw,web,phone,occ,food,note,uname,pass";
$b = ':a' . str_replace(',', ', :a', $a);
$sq = "insert into members ($a) values ($b)";
$st = $db->prepare($sq);
$sqlArray = array();
foreach($obj as $key => $value) {
$sqlArray[]= array(":a".$key => $value);
}
$st->execute($sqlArray);
echo 'success';
}
Edit: I looked at Nick's answer it seems you don't even need to do all the hard stuff I did, you can just pass $obj wow they made it so easy now

Return multiple results with AJAX from sql query in php

Hello I am realizing simple AJAX request and would like to be able to store the results from the SQL SELECT query into 3 different ajax variables.
Where 2 of them will store one variable and the other one have to store foreach results.
Let's say my AJAX request is the following:
$.post('includes/check_number.php', {'date':date, 'userid':userid}, function(data) {
$("#time-result").html(data.result01);
$("#time-sum-result").html(data.result02);
Where I will have 2 results result01 and result02
In the current state of my script inside the mysql select request what is returning like data is the following:
$stmt = $con->prepare( $sql );
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
foreach($stmt as $row) {
echo "<tr>
<td>".$row['clientname']."</td>
<td>".$row['taskname']."</td>
<td>".$row['department']."</td>
<td>".$row['note']."</td>
<td>".$row['caseid']."</td>
<td>".$row['time']."</td>
</tr>";
}
I would like to put the result of the forreach as it is inside the echo, where it will contains various iterations and then for result02 for example would like to put only one row of the same query for example like: $row['date']
In this case
data.result01 - will have all the code of the <tr></tr>
data.result02 - will have only one variable which is date.
Question is how to dump the foreach into result01 and in the same time to put in result02 only one row from the same query. $stmt
Export all your data first then use it with jquery ?
Something like :
PHP :
foreach($stmt as $row) {
$arr_out[] = $row;
}
echo json_encode($arr_out);
exit();
JQUERY :
var result1 = "";
$.post('includes/check_number.php', {'date':date, 'userid':userid}, function(data) {
$.each(data, function(key, item) {
result1 += "<tr><td>"+item.clientname+"</td>[...]<td>"+item.time+"</td></tr>";
result2 = item.date;
});
$("#time-result").html(result1);
}
I didn't test this code, hope it will help you.

nested javascript array to php array

I have a javascript array :
disharray = ([aa,11,],[bb,22])
I send this to php as a json object using - var jsoncvrt = JSON.stringify(disharray);
How do I extract the value of the nested arrays so that I can access values like:
$a = aa and $b = 11?
I use the below code but get the output as
aa11
bb22
Please note, my server uses php 5.2
$data = json_decode(stripcslashes($_POST['strings']));
foreach ($data as $d => $v) {
foreach ($v as $v1 => $value) {
echo $value;
}
}
Your code is fine. Just add this at the top of the code
$values = array();
Now change the inner foreach loop to
if( sizeof($v) == 2 ){
$values[$v[0]] = intval($v[1]);
}
Now to access, say the value corresponding to 'aa' just use $values['aa']
You can insert it into a table using the following code
$con = mysqli_connect(HOSTNAME, USERNAME, PASSWORD, DBNAME);
$query = "INSERT INTO tablename (key, value) VALUES(?, ?);";
$stmt = $con->prepare($query);
if( $stmt ){
foreach ($values as $key => $value){
$stmt->bind_param("sd", $key, $value);
$stmt->execute();
}
$stmt->close();
}
$con->close();
In the $query variable, the '?' stands for wild card character that can take any value and it is set by calling bind_param() function. In the bind_param function, the 's' stands for string and the 'd' stands for integer data type. This is the right way to execute database queries as they void the possibility of SQL Injections.

print json_encode of a MySQL SUM() function

I am trying to print with JSON a SUM() of a price.
Currently I am trying:
$query="SELECT SUM(cost) FROM `Service`";
$result = mysql_query($query);
$json = array();
while($row = mysql_fetch_array($result))
{
$json['cost'] = $row['cost'];
}
print json_encode($json);
mysql_close();
This returns null.
If I try SELECT cost FROM Service instead, it returns the last cost from the database.
What Im I doing wrong?
supply an ALIAS on the column passed on the aggregate function
SELECT SUM(cost) totalCOST FROM `Service`
so you can fetch the columnName
$json['cost'] = $row['totalCOST'];

Categories

Resources