I wrote some code a while back to retrieve a player's saved score when they logged into the website. It used AJAX, and looked a little something like this:
Javascript:
function getHighScore(user){
$.get("getScore.php?userName="+user,function(data){
console.log(data);
output = data;
});
}
PHP:
<?php
$username = strval($_GET['userName']);
$con = mysqli_connect('localhost','XXXX','XXXX','XXXX');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
} else {
$sql="SELECT * FROM users WHERE username = '".$username."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$wealth = $row['wealth'];
echo $wealth;
}
}
mysqli_close($con);
//return $wealth;
?>
I was faced with the fact today that I would have to grab a whole bunch of data from a database, so I had a look at the old high score code I wrote. I'll attach a screenshot of what the table looks like that I will be retrieving info from. Anyway, I need to grab info from 6 columns and 10 rows. I need to assign a PHP variable to the data from P1, P2, P3 etc on MON1; P1, P2, P3 etc on TUE1; so on and so forth until we reach P6 on FRI2. I'm really quite new to PHP, so what would be the best way to go around doing this?
I apologise if I worded the question strangely. Feel free to ask if you didn't understand something.
Thank you!
PS: Ignore the P#_WORK columns. I don't need to refer to them right now
https://ibb.co/gq8u5a
I'd suggest you use an object to store everything, using the "day" column as key, and as value the P* columns in another. Here's some code you can use right away:
<?php
$con = mysqli_connect('localhost','XXXX','XXXX','XXXX');
if(!$con) exit('Could not connect: ' . mysqli_error($con));
$username = $_GET['userName'];
$sql = "SELECT * FROM TABLE WHERE username = '%s'";
$results = $con->query(sprintf($sql, $con->escape_string($username))); // Always escape parameters to prevent SQL injection attacks
$data = new stdClass; // An empty object
while($result = $results->fetch_object()){
$day = $result->day; // Use the day as the key of the object
$data->{$day} = $result;
}
// Now we output the results below by accesing the data in a chain-like fashion by accesing the "data" object
echo $data->MON1->P1 . '<br>'; // will output "Geo E"
echo $data->FRI1->P4 . '<br>'; // will output "Maths"
echo $data->THU2->P6 . '<br>'; // will output "DT"
Be sure to replace "TABLE" in the SQL query with the actual table name, as that wasn't visible in the screenshot you attached.
Related
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.
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
I am using this javascript fetch code to get data from php
async sendRequest(selectValue=this.selectValue){
const fetchResponse = await fetch('/server/getLastWords.php?select='+selectValue);
const fetchJSON = await fetchResponse.json();
await console.log(fetchJSON);
}
this is php code which communicates with MYSQL and sends data to javascript
<?php
header('Content-Type: application/json');
include 'db/db_connection.php';
$mysqli = new mysqli('localhost','root','','worddb');
if(connectDB($mysqli)){
$mysqliQuery = "SELECT * FROM wordlist ORDER BY wordIndex DESC LIMIT ?";
$stmt = $mysqli->stmt_init();
if(!$stmt->prepare($mysqliQuery)){
print "Failed to prepare statement\n";
}else{
$stmt->bind_param("i", $_GET['select']);
$stmt->execute();
$result = $stmt->get_result();
$resultJSON;
foreach($result as $resultArray){
$resultJSON = json_encode($resultArray);
echo $resultJSON;
}
}
}
?>
and this php returns
{"wordIndex":94,"english":"seemingly","korean":"\uc678\uacac\uc0c1\uc73c\ub85c,
\uac89\ubcf4\uae30\uc5d0\ub294","swedish":"till synes","synonyms":"apparently","example":"Seemingly,
he borrowed the money from the bank"}
{"wordIndex":93,"english":"evade","korean":"\ud53c\ud558\ub2e4,
\ud68c\ud53c\ud558\ub2e4","swedish":"undvika","synonyms":"elude, evoid","example":"He is using the
same tactics of distract and evade as the Chancellor used during his speech"}
{"wordIndex":92,"english":"eclipse","korean":"\uac00\ub9ac\ub2e4, \ube5b\uc744
\uc783\uc74c","swedish":"f\u00f6rm\u00f6rka","synonyms":"blocking, beating","example":"Her work was
in eclipse for most of the 20th century"}
{"wordIndex":91,"english":"impede","korean":"\uc9c0\uc5f0\uc2dc\ud0a4\ub2e4",
"swedish":"f\u00f6rhindra","synonyms":"delay, hinder","example":"This will impede learning,
essentially causing more problems than solutions"}
{"wordIndex":90,"english":"exposure","korean":"\uc704\ud5d8\uc5d0 \ub178\ucd9c,
\ud3ed\ub85c","swedish":"exponering","synonyms":"subjection, uncovering","example":"God knows you
probably saved my life, at least from exposure or pneumonia"}
I know it shows unexpected token { because php is returning multiple json object because
when I did echo just one json object it works fine.
$resultJSON;
foreach($result as $resultArray){
$resultJSON =json_encode($resultArray);
}
echo($resultJSON);
but my php needs to send all items ,but I don't know how to do that because console shows unexpected token {}
I read this post before posting my question
Why am I getting unexpected '}'?
but solution in this post was to add semicolon, but I have semicolons in my code..
Transform your results in an array :
$resultJSON = array();
foreach($result as $resultArray){
$resultJSON[] = $resultArray;
}
Then output the array :
echo json_encode($resultJSON);
It goes wrong here:
$resultJSON;
foreach($result as $resultArray){
$resultJSON = json_encode($resultArray);
echo $resultJSON;
}
You output:
echo json1;
echo json2;
echo json3;
However, on the clientside the output is collected and treated as one json. So javascript will work with json1json2json3. And that's not a valid json.
If you don't have to do anything else then sending the result back
echo json_encode($result);
would do.
I have a MySQL database ($database) set up, with a table ("gigdata") and column names as follows:
id
clientname
day
month
year
postcode
status
entered
Each column name has a few rows of test data under it. I have successfully connected to the database using PHP's mysqli class, as below.
So far, I have written this PHP:
//Connect to database
$conn = new mysqli(localhost, $username, $password, $database);
//Check connection
if ($conn->connect_error) {
die("Failed to connect to MySQL: " . $conn->connect_error);
}
echo "<p>Connected to database</p>";
//Select data from database
$sql = "SELECT id, clientname, day, month, year, postcode, status, entered FROM gigdata";
$result = mysqli_query($conn, $sql);
//Create an empty array
$gigarray = array();
//Check data exists, if YES store in array
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
foreach ($row as $r) {
array_push($gigarray, $r);
}
}
} else {
echo "0 results";
}
I'm then echoing the JSON string into Javascript, which works fine:
var gigdata = <?php echo json_encode($gigarray) ?>;
QUESTION
My aim is to adapt the original PHP so that the JSON ends up formatted such that:
each database row is a new array element
each database column name is the name in each JSON name/value pair
each database field is the value in each JSON name/value pair
Hope this makes sense, and thanks a lot in advance.
There's actually a very helpful mysqli function for getting all data from a result, exactly how you want it - mysqli_fetch_all
Try:
json_encode(mysqli_fetch_all($result, MYSQLI_ASSOC));
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.