Inserting PHP DB result into Javascript array - javascript

How can i insert PHP db result query to a javascript array. I have set of values in my Database and I want to get those values and store it in a javascript array. This is my query
$query = $db->query("SELECT * FROM members");
while ($row = $query->fetch_assoc()) {
echo $row['names'];
}
And I want to store it in a javascript array like this
var names = ['John','Chris','Leo'];
This is my code but im getting an error.
var names = [
<?php while ($row = $query->fetch_assoc()) {
echo $row['skill'];
} ?>
];

Do this instead.
$names = [];
<?php while ($row = $query->fetch_assoc()) {
$names[] = $row['skill'];
}
$javaScriptArray = json_encode($names);
?>
JavaScript is run on the browser while PHP is run on the server. They don't really integrate with each other. To make the array available in javascript do something like this.
<script>
var arr = <?php echo $javaScriptArray; ?>;
</script>

Related

Passing array to JS as values

I want to pass an array from PHP to Javascirpt so I just get a list of values - currently I get JSON format - which I know because I'm using JSON_ENCODE I'm just hoping/wondering is there a way to pass it as a simple set of values or to parse it afterwards?
Apologies I'm quite new to this :)
I've tried a few different things from previous answers to similar questions, but none seem to do the trick.
<?php
$user = 'xxx';
$pass = 'xxx';
$connection_string = 'connectionstringtomysqldatabase';
$connection = odbc_connect( $connection_string, $user, $pass );
$sqlstring = "SELECT FIELD1 FROM TABLE.ITEM where IASOHQ<>0 FETCH FIRST 10 ROWS ONLY";
$result = odbc_exec($connection, $sqlstring);
while ($info = odbc_fetch_array($result)) {
$content[] = $info;
}
?>
<script type="text/javascript">
var content = <?php echo json_encode($content); ?>;
</script>
I want...
var content = [68,116,49,57,13,11,46,47,14,79]
I get...
var content = [{"FIELD1":"68"},{"FIELD1":"116"},{"FIELD1":"49"},{"FIELD1":"57"},{"FIELD1":"13"},{"FIELD1":"11"},{"FIELD1":"46"},{"FIELD1":"47"},{"FIELD1":"14"},{"FIELD1":"79"}];
You are getting this result because your array is multi-dimensional with associative second level keys i.e. it looks like
$content = [['FIELD1' => 68], ['FIELD1' => 116], ..., ['FIELD1' => 79]];
This is because odbc_fetch_array returns an associative array for each row. To fix your data format, just change this line:
$content[] = $info;
to
$content[] = $info['FIELD1'];
That will give you an array that looks like your desired result of
[68,116,49,57,13,11,46,47,14,79]
Just add ' to make it a value. Change
var content = <?php echo json_encode($content); ?>;
to
var content = '<?php echo json_encode($content); ?>';
var myObject = JSON.parse(content);
Iterate over the array then.
Just change this peace of php code. I think that all of the index of array is FIELD1
...
while ($info = odbc_fetch_array($result)) {
$content[] = $info['FIELD1'];
}
...
Just
echo json_encode(array_values($content));
it will work;

MySQL data from PHP to Javascript with JSON

I am trying to use a code that will take data from a mySQL database bind that data to a variable, put all the resulting $x into a PHP array, and finally convert it to JSON format. I then take the JSON into javascript to handle the data from the data base there.
Please see my code:
<?php
//bind to $x
$mysqli = new mysqli('localhost', 'root', 'root', 'mytable');
if ($stmt = $mysqli->prepare("SELECT x FROM data")) {
$stmt->bind_result($x);
$OK = $stmt->execute();
}
//put all of the resulting $x into a PHP array
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $x;
}
//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($result_array);
if ($stmt = $mysqli->prepare("SELECT data.y FROM data")) {
$stmt->bind_result($y);
$OK = $stmt->execute();
}
//put all of the resulting y into a PHP array
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $y;
}
//convert the PHP array into JSON format, so it works with javascript
$json_array2 = json_encode($result_array);
?>
<script>
var xv = <?php echo $json_array; ?>;
var yv = <?php echo $json_array2; ?>;
var storage = [];
for(var i=0;i<100;i++)
{
var x = xv[i];
var y = yv[i];
var json = {x: x, y: y};
storage.push(json);
}
My question is why is the page displaying this as an output and not transferring the data to the arrays
"prepare("SELECT x FROM data")) { $stmt->bind_result($x); $OK = $stmt->execute(); } //put all of the resulting names into a PHP array $result_array = Array(); while($stmt->fetch()) { $result_array[] = $x; } //convert the PHP array into JSON format, so it works with javascript $json_array = json_encode($result_array); /* if ($stmt = $mysqli->prepare("SELECT data.y FROM data")) { $stmt->bind_result($y); $OK = $stmt->execute(); } //put all of the resulting names into a PHP array $result_array = Array(); while($stmt->fetch()) { $result_array[] = $y; } //convert the PHP array into JSON format, so it works with javascript $json_array2 = json_encode($result_array); */ ?>"
In those lines you have wrong code:
var xv = "<?php echo $json_array; ?>";
var yv = "<?php echo $json_array2; ?>";
You are printing output from json_encode into a double quoted section. This means when PHP render that page, output will be like that:
var xv = "[...smth]";
After those lines you are trying to get a value from array inside for but xv and xz variables are not type of object they are strings. Instead of this do it like that:
var xv = <?=$json_array;?>;
var yv = <?=$json_array2;?>;
The xv and yv is a string since you used json_encode.
You can use JSON.parse to convert the string into json.
var xv = "<?php echo $json_array; ?>";
xv = JSON.parse(xv);
var yv = "<?php echo $json_array2; ?>";
yv = JSON.parse(yv);
var storage = [];
for(var i=0;i<100;i++)
{
var x = xv[i];
var y = yv[i];
var json = {x: x, y: y};
storage.push(json);
}
First: if you're seeing PHP code in your output, you need to check your server and PHP configuration. Your PHP script is being interpreted by the web server as plain text and just spitting out the raw code instead of executing it through the PHP interpreter.
Second: embedding PHP in Javascript is less than ideal. You should have a PHP script to handle the MySQL querying, then fetching the output in Javascript with an AJAX request. Additionally, the way you're mutating the data is redundant and suboptimal.
This will retrieve your results from the database and encode it as JSON:
<?php
// connect, query, bind results
$result = [];
$mysqli = new mysqli('localhost', 'user', 'pass', 'db');
if ($stmt = $mysqli->prepare("SELECT x,y FROM table")) {
$stmt->execute();
$stmt->bind_result($x,$y);
while ( $stmt->fetch() ) {
$result[] = [
'x' => $x,
'y' => $y
];
}
echo json_encode($result);
}
?>
This is a basic AJAX example to retrieve the output from the PHP script:
<script>
function fetchMyStuff() {
// basic ajax example
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if ( xhr.readyState == 4 ) {
console.log(
JSON.parse( xhr.responseText )
);
}
}
xhr.open('GET', 'myscript.php', true);
xhr.send();
}
fetchMyStuff();
</script>
You'll see the resulting object in the console corresponding to your query results:
[{x:'x1':y:'y1'},{x:'x2',y:'y2'},...]
Personally, I don't like the limitations of prepared statements and would prefer a much more optimized approach for my PHP file:
<?php
$mysqli = new mysqli('localhost', 'user', 'pass', 'db');
echo json_encode(
$mysqli->query("SELECT x,y FROM table")->fetch_all( MYSQLI_ASSOC )
);
?>
This leverages the mysql-nd module to perform all the work of fetching the full result set as an associative array and encoding it in only a few lines.

Pass mysql table values to Javascript via PHP

I am trying to take all of the rows MYSQL table and ultimately have them end up in an interactive HTML table. I currently have no problem inserting values into my table using a $.post function, I just cannot return them, at least, not all of them.
Here is my JS code:
function load() {
$.post(
"Returnsmedb.php",
function (response) {
var firstname = response.fname;
var lastname = response.lname;
var username = response.uname;
var email = response.email;
var password = response.password;
console.log(response);
}, 'JSON'
);
}
PHP:
<?php
header('Content-type: application/json');
$servername = "localhost";
$username = "SME";
$password = "mypass";
$db = "p3";
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM pendingusers";
$result = $conn->query($sql);
$response = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
// $response[] = $row[];
$response['fname'] = $row["fname"];
$response['lname'] = $row["lname"];
$response['uname'] = $row["uname"];
$response['email'] = $row["email"];
}
echo json_encode($response);
} else {
echo "0 results";
}
$conn->close();
?>
I am thinking the easiest thing to do would be to store each row in an array, but I am not sure. It currently returns my $response array, but all of the values are null, except for 'email', which has the correct value, but it is from the last row of my DB table. Also, it only returns one row.
Any help / guidance would be much appreciated.
Thanks!
Your problem is that in this loop:
while($row = $result->fetch_array()) {
// $response[] = $row[];
$response['fname'] = $row["fname"];
$response['lname'] = $row["lname"];
$response['uname'] = $row["uname"];
$response['email'] = $row["email"];
}
You keep overwriting the same keys in $response, so at the end of the loop, only the values from the last DB row will be found. you could fix this by doing
while($row = $result->fetch_array()) $response[] = $row;
However if you'll be capturing all results, there is no need to loop through them. Just use fetch_all and you will get the full table right away.
$response = $result->fetch_all(MYSQLI_ASSOC)
As a sidenote, I would be really careful about sending everything unfiltered from your DB to the browser like this. Consider at least adding a LIMIT clause to your query so that if your table has thousands of rows, everything doesn't get sent:
$sql = "SELECT * FROM pendingusers LIMIT 50";
Finally, be explicit about the columns you want, so that you don't leak unwanted information if your DB gets new sensitive columns in the future
$cols = 'fname, lname, uname, email';
$sql = "SELECT $cols FROM pendingusers LIMIT 50";

Sending PHP array to JavaScript issue

I have an AJAX POST function that runs a PHP file that queries a MySQL database. It uses the "CONCAT" option in MySQL and then adds each row it receives into an array. I need to get that array from PHP to JavaScript, how would I go about doing this?
I've tried looking it up but nothing that I found either I didn't understand how to actually implement it, or it just flat out didn't work.
$sql_query = substr($sql, 0, -3);
$result = $connection->query($sql_query);
if (!$result) {
die("Invalid Query: " . mysqli_error());
}
$rowCount = mysqli_num_rows($result);
echo "Total Bans: " . $rowCount . "\r\n";
echo "\r\n";
$bans = [];
while ($row = $result->fetch_row()) {
for ($x = 0; $x < $rowCount; $x++) {
array_push($bans, $row[$x]);
}
}
I included that part of my PHP code if you need it.
I tried this:
echo(json_encode($bans));
.
success: function(data) {
document.getElementById('outputtext').innerHTML = '';
var array = new Array();
array = data;
document.getElementById('outputtext').innerHTML = array;
}
That returns everything, but adds a lot of "," between them.
Example of an index in the array:
[05-18] Daedalus banned EXAMPLE_USERNAME(EXAMPLE_GUID / EXAMPLE_IP) for EXAMPLE_REASON
I want all the lines from the $bans array to be put into an array in JavaScript.
When you usage echo(json_encode($bans)); that convert php array to json array. To use json in javascript you should first Parse that array like this
success : function(data){
result = JSON.parse(data) ;
}
Now you check this data console.log(result);
Access particular data through key like this
name = result.name;
This place in your code is wrong:
while ($row = $result->fetch_row()) {
for ($x = 0; $x < $rowCount; $x++) {
array_push($bans, $row[$x]);
}
}
Because you cycle trough records with while and inside once more with for. Use only while:
while ($row = $result->fetch_row()) {
array_push($bans, $row);
}
Will pull all rows and without nulls.
In your case when you have only single column in your return from database you should use:
while ($row = $result->fetch_row()) {
array_push($bans, $row[0]);
}

Fetch 5 Columns and their value from Mysql query and translate into PHP

I am unable to find a simple and elegant solution to solve this after several tries.
In essence I would like a way to fetch the 5 fields taken from this query and assign them to PHP variables then latterly Javascript variables.
<?php
include_once('connect.php');
$result = mysqli_query($conn, " SELECT DISTINCT IPdestport as destport,COUNT(*) as count FROM PACKETSFORIP GROUP BY destport ORDER BY count DESC LIMIT 5;");
while($row[] = mysqli_fetch_array($result))
{
$destport1 = $row[1][ 'destport' ];
$destport2 = $row[2]['destport'];
$destport3 = $row[3]['destport'];
$destport4 = $row[4]['destport'];
$destport5 = $row[5]['destport'];
$count1 = $row[1]['count'];
$count2 = $row[2]['count'];
$count3 = $row[3]['count'];
$count4 = $row[4]['count'];
$count5 = $row[5]['count'];
}
?>
Here is more code of how I will eventually translate these PHP variables into Javascript variables in order to process them into a google chart
var destport1 = "<?php echo $destport1 ?>";
var destport2 = "<?php echo $destport2 ?>";
var destport3 = "<?php echo $destport3 ?>";
var destport4 = "<?php echo $destport4 ?>";
var destport5 = "<?php echo $destport5 ?>";
var count1 = "<?php echo $count1 ?>";
var count2 = "<?php echo $count2 ?>";
var count3 = "<?php echo $count3 ?>";
var count4 = "<?php echo $count4 ?>";
var count5 = "<?php echo $count5 ?>";
Any help would be very much appreciated. Thanks.
You can save a lot of repetitive code by using arrays.
To simplify the first step (assign them to PHP variables) just convert the result set into an array:
$destPorts = mysqli_fetch_all($result);
$destPorts will contain all of the rows from the result set. If you want to access the 'count' column of the second row, use:
$destPorts[1]['count']
Or to access the 'destport' column of the fourth row, use:
$destPorts[3]['destport']
Since the values are stored in the $destPorts array, there is no need to convert them into separate variables.
You can do something similar in JavaScript. Instead of creating separate variables, store the data in a JavaScript object:
var destPorts = <?php echo json_encode($destPorts); ?>
Now you can access the values stored in the destPorts JavaScript variable. To access the 'count' column of the second row, use:
destPorts[1].count
Or to access the 'destport' column of the fourth row, use:
destPorts[3].destport
When you store your result rows in arrays and objects instead of simple numerically indexed variables, your code is less repetitive and more flexible. You no longer need to know how many results are in the database; you can simply loop over the array or object and access all of the data.
For anyone searching for this in future this is the solution i eventually utilised. Found it in a previous web application i'd coded.
<?php
include_once('connect.php');
$result = mysqli_query($conn, " SELECT DISTINCT IPdestport as destport,COUNT(*) as count FROM PACKETSFORIP GROUP BY destport ORDER BY count DESC LIMIT 5;");
$portsarray = Array();
$countarray = Array();
while($row = mysqli_fetch_array($result))
{
$portarray[] = array('destport'=>$row['destport'], 'count'=>$row['count']);
echo $row['count'];
}
$portarray = json_encode($portarray);
?>
The above code fetches each port and the count of packets going to that port and this is latterly converted into javascript to be fed into a google chart, but i'll just show the part that fetches the PHP array and puts the variables contained within into javascript variables.
var obj = <?php echo $portarray; ?>;
for(var i= 0; i < obj.length; i++) {
var json = obj[i];
destport = json.destport;
numberofpackets = json.count;
destport = destport.toString();
numberofpackets= parseInt(numberofpackets);

Categories

Resources