Pass mysql table values to Javascript via PHP - javascript

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";

Related

PHP AJAX - Function not Returning SQL ID

I am trying to get a query to run where it returns the SQL row's id of a user using a collar number through PHP.
For some reason, it is not working and providing an error: trying to access array offset on value of type null. Full Error Message - https://gyazo.com/38367bee5066d16f419a43aab93cbc89
I am not exactly sure how to fix this, I've tried a lot of things. I want the function to return the id so I can then use it where ever needed. I am using PHP's include functions.
UpdatePassword.php
session_start();
include("functions.php");
$id = findUserID(array_key_exists("collar", $_POST));
echo($id);
Functions.php
function findUserID($collar){
$id = "";
include("../connection.php");
$query = "SELECT `id` FROM `users` WHERE collar = '".mysqli_real_escape_string($link, $collar)."'";
if ($result = mysqli_query($link, $query)){
//echo "Query was Successful";
$row = mysqli_fetch_array($result);
return($row['id']);
}
}
Using PHP ternary operator to show one example validating your $_POST input:
$id = ( array_key_exists("collar", $_POST) )
? findUserID($_POST['collar'])
: 0;
That is shorthand for:
if ( true === array_key_exists("collar", $_POST) ) {
$id = findUserID($_POST['collar']);
}
else {
$id = 0;
}
Other validation checks can be included in each method:
$id = (
array_key_exists("collar", $_POST) // key exists
&& "" !== $_POST['collar'] // not empty string
)
? findUserID($_POST['collar'])
: 0; // if not valid, assign default value

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.

Inserting PHP DB result into Javascript array

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>

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]);
}

Trouble passing associative array from javascript to php and insert it into mysql database through prepared statements

http://jsfiddle.net/kqd7m5nb/
Just click on the insert data button, notice an alert box. This is an associative array. These are the values I want to pass into my php file.
In The php file, I get a Post value containing all the data I passed from my ajax data. I decoded It using json_decode. The data is now extracted as a php array of type stdClass. And I am now using prepared statements to insert all of the php array through the for loop statement.
Using Xdebug, the arrow stops inside the for loop of the php file. And after that, nothing gets inserted into my database. I also noticed when evaluating the 'count($value)' on php on xdebug, it returns 1 instead of 3. And evaluating $value[0]->fname in XDEBUG also returns an error.
sample.js
$('#ajax').click(function() {
var values = $('#mytable tbody tr').map(function() {
return {
fname : $('td:eq(0)',this).text(),
lname : $('td:eq(1)',this).text(),
point : parseInt($('td:eq(2)',this).text())
}
});
var valuesDebug = "";
for (var i = 0; i < values.length; i++)
{
valuesDebug += " " + values[i]["fname"] + " " + values[i]["lname"] + " " + values[i]["point"] + "\n";
}
alert(valuesDebug);
var valueStringed = JSON.stringify(values);
$.ajax({
"type":"POST",
"url":"insertData.php",
"data":{value : valueStringed},
"success":function(data){
alert('Done inserting the current table values');
}
});
});
insertData.php
<?php
if (isset($_POST['value']))
{
$value = json_decode(stripslashes($_POST['value']));
}
$mysqli = new mysqli("localhost","root","password","test");
if($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$stmt = $mysqli->prepare("INSERT INTO team VALUES (NULL,?, ?, ?)"); //NULL is auto increment primary key id
$stmt->bind_param('ssi', $fname, $lname, $point);
if (count($value) > 0)
{
for( $i = 0 ;$i < count($value);$i++){
$fname = $value[$i]->fname;
$lname = $value[$i]->lname;
$point = $value[$i]->point;
$stmt->execute();
}
}
$stmt->close();
$mysqli->close();
?>
At a glance you need to be doing:
$stmt->bind_param('ssi', $fname, $lname, $point);
in your for loop as your defining them in the loop, if you do it above as you have - the variables are undefined.
So try:
$stmt = $mysqli->prepare("INSERT INTO team VALUES (NULL,?, ?, ?)");
if (count($value) > 0)
{
for( $i = 0 ;$i < count($value);$i++){
$fname = $value[$i]->fname;
$lname = $value[$i]->lname;
$point = $value[$i]->point;
$stmt->bind_param('ssi', $fname, $lname, $point);
$stmt->execute();
}
}
This code now works.
Please see my original javascript code.
It seems on this part I added an array valuesDebug and copied the contents from the values array through the push method. I don't know how exactly why this works. Is there a way to make this shorter?
BTW The first line is the row cell contents of my table being converted into the values array.
var values = $('#mytable tbody tr').map(function() {
return {
fname : $('td:eq(0)',this).text(),
lname : $('td:eq(1)',this).text(),
point : parseInt($('td:eq(2)',this).text())
}
});
var valuesDebug = [];
for (var i = 0; i < values.length; i++)
{
valuesDebug.push({fname: values[i]["fname"],lname: values[i]["lname"],point: values[i]["point"]});
}
var valueStringed = JSON.stringify(valuesDebug);
// passes valueStringed into ajax ...

Categories

Resources