Basically I can do so it prints out for example one field from the table, but I want to have all of them to different tables or whatever, how would I achieve this? I got this as my save/load code:
// Save/Load data.
$('').ready(function() {
if($.cookie('code')) {
$.ajax({
type: "POST",
url: "ajax/loadData.php",
data: "code=" + $.cookie('code'),
dataType: "json"
success: function() {
var json = $.parseJSON();
var coins = json.coins;
var lvl = json.lvl;
$('#test').html('lvl: ' + lvl + ' coins: ' + coins);
}
});
console.log('Loaded data from the database with the code ' + $.cookie('code'));
} else {
// Generate save&load-code
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 64;
var randomCode = '';
for(var i = 0; i < string_length; i++) {
var num = Math.floor(Math.random() * chars.length);
randomCode += chars.substring(num, num+1);
}
// Save code in cookies & database
$.cookie('code', randomCode);
console.log('Generated and saved code ' + $.cookie('code'));
}
});
Note that I do know that I do not have a save-function/ajax yet, but I'm working on the load feature right now.
This is my loadData.php file:
<?php
include '../inc/_db.php';
$code = $_GET['code'];
$query = mysqli_query($db, "SELECT * FROM data WHERE code='$code'");
while($row = mysqli_fetch_array($query)) {
echo $row['coins'];
}
?>
Simple enough, yeah. This prints out the amount of coins that belongs to the specific user. Here's the table structure:
How would I go about to load both coins AND the lvl field, into different variables or alike, so I can use them properly.
Looks like Joroen helped you out with the ajax side and hopefully you added the comma he was talking about. The php/mysqli part can be written like this:
<?php
include '../inc/_db.php';
$code = $_GET['code'];
$query = mysqli_query($db, "SELECT * FROM data WHERE code='$code'");
$row = mysqli_fetch_array($query));
print json_encode($row);
?>
In reality this code is scary because you're not cleaning any of the incoming data and using it directly in a SQL statement. Since you already know it's only allowing A-Za-z0-9 characters you should check the value of $_GET['code'] to make sure it's safe to use. I also highly recommend using mysqli prepared statements to avoid some of the funny stuff that can happen with tainted input.
this is probably a bad programming practice but that is how i would do it.
while($row = mysqli_fetch_array($query)) {
$return = $row['coins'].",".$row['id'; //separate the send the values as a comma-separated string
echo $return;
}
the js would look like this
$('#coins').load('ajax/loadData.php?code=' + $.cookie('code')); //collect the values here
var values = $(#coins).text(); //save the values in a srting
var array_of_values = values.split(","); //split the string at a delimiter and save the values in an array
mind you, this is not likely to work if the query returns multiple rows
Related
I have an object that I get from a "SHOW tables" query. Unfortunately, I get an array inside an object has a name that changes based on what user is logged in (eg. data[1].Tables_in_kazura). How can I either access what user is logged in or even better rename the result from PHP, from Tables_in_xxx to whatever I want?
$.getJSON("php/loadCategories.php", function(data) {
for (let i = 0; i < data.length; i++) {
console.log(data[i]);
}
});
This is my PHP
$sql = "SHOW tables";
$rows = $db->query($sql);
$length = $rows->num_rows;
$result = array();
for ($i = 0; $i < $length; $i++) {
$row = $rows->fetch_assoc();
array_push($result, $row);
}
echo json_encode($result);
The echo $result gives me:
Object { Tables_in_kazura: "drinks" }
Object { Tables_in_kazura: "food" }
and what ever else the user (user here is kazura) has in his tables.
Since it is based on username, Tables_in_USERNAME will vary and I don't know how I can access the data inside it.
The optimal solution would be that echo json_encode($result); returns Object { categoryname: "drinks" } and so on no matter what user is logged in
If the tables all have the same structure then you can just use raw SQL although this is really not advised as it leaves you open to attack. The problem seems to be that you're using a table per user rather than following a relational convention. But as a short answer, you cant do what you're looking for within a sanitized SQL query as dynamic table names aren't supported.
I figured out a way to get my wanted result in javascript. It's not pretty, but it works.
let propertyName = Object.keys(data[1]).toString();
//Rename the query from Tables_in_USERNAME to categoryname
data = data.map(function(obj) {
obj['categoryname'] = obj[propertyName];
delete obj[propertyName];
return obj;
});
I rename all the object keys to categoryname instead of changing the SQL query.
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]);
}
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 ...
I'm trying to write one row of data into a Google Cloud SQL database, using a prepared statement as described here:
https://developers.google.com/apps-script/guides/jdbc
I have the data stored in an object called valuesByTitle, which looks like this:
{NAME: 'fun event', LOCATION: '123 Main St.'}
The data is inserted into the SQL table if I write everything out like this:
var conn = getConnection(); // connects to db
var stmt = conn.prepareStatement('INSERT INTO events '
+ '(NAME, LOCATION) values (?, ?)');
stmt.setString(1, valuesByTitle['NAME']);
stmt.setString(2, valuesByTitle['LOCATION']);
stmt.execute();
}
However, I would like to automate the process, so I don't have to change the code each time the variables change.
I have two new variables, one for the column names and one for a set of place holders (e.g. "?") for the insert statement.
var columns = Object.keys(valuesByTitle);
var placeholders = columns.map(function(column) {
return "?";
};
Using these, this prepared statement should automatically insert whatever is in the valuesByTitle object (assuming all the values are string values):
var conn = getConnection();
var stmt = conn.prepareStatement("INSERT INTO events (" + columns.join(",") + ") VALUES (" + placeholders.join(",") + ")");
for (i = 0; i < columns.length; i++) {
stmt.setString(i+1, valuesByTitle[columns[i]]);
}
stmt.execute();
For some reason, it's not inserting the data. Surprised not to find any examples either. Is the logic off or is it just not possible to do?
Thanks.
All your code is OK, you simply forgot to close the map() bracket i.e.
var columns = Object.keys(valuesByTitle);
var placeholders = columns.map(function(column) {
return "?";
};
should be
var columns = Object.keys(valuesByTitle);
var placeholders = columns.map(function(column) {
return "?";
});
(note the ending bracket after return "?";})
I have a multidimensional array in php, and i want to get its data from javascript but i didn't work
here my code in php
$managername = $_SESSION['managername'];
$sqls = "select s.*,m.* from rm_allowedmanagers m inner join rm_services s on s.srvid = m.srvid where m.managername = '$managername' ";
$sql = mysql_query($sqls);
$newservices = array();
while($row = mysql_fetch_array($sql))
{
$nsrvid = $row['srvid'];
$nsrvname = $row['srvname'];
$nunitprice = $row['unitprice'];
$nunitpricetax = $row['unitpricetax'];
$ntotal = $nunitprice + $nunitpricetax;
$newservice = array($nsrvid, $nsrvname , $ntotal);
array_push ($newservices, $newservice);
}
and here my java script code
<script>
function changeserviceprice(id)
{
var newservice = $("#newservice").val();
var data = '<?= $newservices ?>';
var asd = data;
var asd2 = data[0][0];
$("#qq4").val(asd);
$("#qq5").val(asd2);
}
</script>
PHP code i think it is work fine, and i think the error is in javascript function.
when i try to print the data using javascript it print the "Array" word when i print the whole row "array", but
it print "a" character when i try to print the first element in the first array!!
try encoding the $newservices array:
var data = <?php echo json_encode($newservices); ?>;