Python Post - PHP Request - php

I'm trying to create a php page which takes data from my python code and show them as a table.
r = requests.post('http://localhost/index.php', data={"iv":a,"ven":b,"hem":c,"card":d,"ecg":e})
print(r.text)
In above code, I post data then print it to check if everything is okay. My r.text output
<table><tr><th>IV Pump</th><th>Ventilator</th> <th>Heart Monitor</th><th>Cardiac Machine</th><th>Echocardiogram</th></tr><tr><td>off</td><td>on</td><td>off</td><td>off</td><td>off</td></tr></table>
which seems fine because I can get a,b,c,d,e (on/off basically). However when I open my index.php I cannot see those "on"s and "off"s. I am newbie on server things, PHP, etc. My mistake is probably very dummy. Should I store post data in somewhere? My index.php:
<?php
$iv=$_REQUEST['iv'];
$ven=$_REQUEST['ven'];
$hem=$_REQUEST['hem'];
$card=$_REQUEST['card'];
$ecg=$_REQUEST['ecg'];
echo '<table>';
echo '<tr>';
echo '<th>IV Pump</th>';
echo '<th>Ventilator</th> ';
echo '<th>Heart Monitor</th>';
echo '<th>Cardiac Machine</th>';
echo '<th>Echocardiogram</th>';
echo '</tr>';
echo '<tr>';
echo '<td>';
echo $iv;
echo '</td>';
echo '<td>';
echo $ven;
echo '</td>';
echo '<td>';
echo $hem;
echo '</td>';
echo '<td>';
echo $card;
echo '</td>';
echo '<td>';
echo $ecg;
echo '</td>';
echo '</tr>';
echo '</table>';
?>
My r.text is ok, but in web page I cannot see request data, the table cells are empty. What is the difference? As I know r.text returns the page content, so index.php must be wrong, I guess it is about storing the data.

When you make a HTTP request to a server, that server will return the rendered webpage to that user. This means requests will get back the correct response.
However when you open a web page in a browser, you are making a new request to that server which will render the page again. Since you aren't passing the $_REQUEST['iv'] etc. values this time, the table will appear blank.
You have a few options depending on what you want to do:
Store the information in a database
You can store that information in a database. Some databases for example are SQLite3 or MySQL. I've omitted the exact database insertion/reading implementation since it differs between which database you pick.
A simple method might be:
<?php
$iv=$_REQUEST['iv'];
// insert other variables etc.
// Check if this is a POST request
if ($_SERVER['REQUEST_METHOD'] === "POST") {
// INSERT DATA INTO YOUR DATABASE AS APPROPRIATE
// You can also echo back the table if you want
// Else it might be a GET request
} elseif ($_SERVER['REQUEST_METHOD'] === "GET") {
// READ DATA FROM DATABASE
// echo table with the data from the database
}
?>
Use URL parameters
Alternatively you can use URL parameters to encode your data like so:
# In your Python code
# Notice that requests.post changed to requests.get and data changed to params
r = requests.get('http://localhost/index.php', params={"iv":a,"ven":b,"hem":c,"card":d,"ecg":e})
# You can now access this specific URL to see the populated table
# The URL will look something like http://localhost/index.php?iv=a&ven=b/
print(r.url)
Note that this requires you to visit that specific URL and doesn't work if you visit the base URL (i.e. https://localhost/index.php) without the parameters.

Related

The best way to convert the name of a PHP array to a string [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
I have an HTML table, linked to PHP $_SESSION data, to which I wish to add a Delete button to every row that deletes not only that row from the HTML table, but also from the $_SESSION variable.
This is the code that populates my table:
tableData.php
// echo the table headings
echo <<<HERE
<tr>
<th>CityID</th>
<th>State</th>
<th>City</th>
<th></th>
</tr>
HERE;
if (isset($_SESSION['cityData']))
{
foreach($_SESSION['cityData'] as $city)
{
echo "<tr>";
// print each row of data
foreach($city as $data)
{
echo "<td>" . $data . "</td>";
}
//echo '<td><button action="<?php unset(' . $_SESSION['cityData'][key($_SESSION['cityData'])] . ')?>">Delete Row</button></td>';
echo "</tr>";
}
}
The line that I commented out,
echo '<td><button action="<?php unset(' . $_SESSION['cityData'][key($_SESSION['cityData'])] . ')?>">Delete Row</button></td>';
is the line that creates the button that I am trying to create, to do what I am wanting it to do. I am trying to figure out the best way to name the array that I want gone.
P.S. I know, I should have it invoke some other function that does both tasks, it is just, if I pass the array in like I did, it will complain of " Array to string conversion ". Is there a way to do what I am trying to do, cleanly?
It's just not that simple. You need to get your buttons to submit to a link, and then have the PHP unset the content.
foreach($_SESSION['cityData'] as $index => $city) //added $index =>
{
echo "<tr>";
// print each row of data
foreach($city as $data)
{
echo "<td>" . $data . "</td>";
}
echo '<td><form method="post" action=""><input type="hidden" name="delete" value="' . $index . '"><input type="submit" value="Delete Row"></form></td>';
echo "</tr>";
}
So I added a form that a button that will submit to data that indicates the row number, so when your client clicks on the button, it will submit them and the row number will be passed as a POST variable.
At the top of tableData.php, you can then have logic handling the delete. Simply check if the delete is set, and then attempt to unset from there.
if (isset($_POST['delete']))
unset($_SESSION['cityData'][$_POST['delete']]);
You will want to have further validation that checks if POST delete within the bounds of $_SESSION['cityData'], but the basic idea is there.
You're mixing client-side and server-side code the wrong way here :(
The "client" is something like a user's browser. When a user clicks that button on their browser, it will run client-side code (i.e. JavaScript) - your PHP won't exist anymore at that stage so you don't have access to that array.
PHP is executed when a page has been requested from your server. That's when you can perform whatever computation you need and then deliver a textual response (via echo for example) back to the user's browser or whatever the client may be.
That button should make another request to your server so you can use PHP to delete the row. Then your PHP server should echo a response back to the requesting browser so users can know if it worked or not.
The link on the button will need to be provided some additional details, like the index of the row that the user wants to delete, so the PHP script doesn't delete the wrong one. See Dave Chen's answer below for some example code.

Php returning array from json, but I need the data as a string

So I'm setting up a little page for myself to see my online transactions in dogecoin.
I have the RPC server/client connection established and working correctly.
The listtransactions method provides me with the transaction history as an array, which breaks down into its elements. I embed these in a table.
That all works correctly. what I WANT is to take the transaction ID and make it linkable to the dogecoin blockchain record.
Here is the code, and then I will note which lines have the issue:
for($i=count($json)-1; $i>=0; $i--){
echo '<tr>';
echo '<td>'.$json[$i]['address'].'</td>'."\n";
//echo '<td>'.$json[$i]['category'].'</td>'."\n";
echo '<td>'.$json[$i]['amount'].'</td>'."\n";
//echo '<td>'.$json[$i]['confirmations'].'</td>'."\n";
echo '<td>'."<a href='https://dogechain.info/tx/$json[$i]['txid']'>".$json[$i]
['txid'].'</a> </td>'."\n";
echo '</tr>';
}
echo '</table></center>';
?>
The line containing the hyperlink is where it screws up. You can see how it is displaying at http://www.suchco.in/
an example link it gives me is: https://dogechain.info/tx/Array%5B
what it should be is: https://dogechain.info/tx/ fab3b949cb3a71e79fa6b631d5d16aa7268b77dc3626e2fb2e711f1b43adc08d
how can I make this happen?
Put { } around your array variables in a string.
Try:
{$json[$i]['txid']}
Instead of:
$json[$i]['txid']
OR
Do string concatenation
echo '<td>'."<a href='https://dogechain.info/tx/".$json[$i]['txid']."'>"

PHP echo button onclick function

For a little "webshop project" I create a table with PHP and echo"..." function. The table displays some values and in the last cells, there shall be a button which enables the user to delete the corresponding row (or better said, purchase). The data is held in a database and read out while the page loads and than displayed in the table.
I use a "purchase id" to find out which rows have to be deleted, and it works fine if I just implement the function itself. The problem is that I can't get the function working as "onclick" event for the button.
So, some code:
function delete_purchase($purchase_id){
mysql_query("DELETE FROM purchase WHERE purch_id = '$purchase_id'");};
That's the PHP function which deletes the rows, easy enough.
$result = mysql_query("SELECT purchase.purch_id, item.name, purchase.amount, purchase.purch_date, delivery.meaning, item.weight FROM purchase, item, delivery WHERE purchase.cust_id='$cust_id' AND delivery.del_id = purchase.delivered AND purchase.item_id = item.item_id");
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['amount'] . "</td>";
echo "<td>" . $row['weight'] * $row['amount'] . "</td>";
echo "<td>" . $row['purch_date'] . "</td>";
echo "<td>" . $row['meaning'] . "</td>";
echo "<td><button onclick=\"delete_purchase('" . $row['purch_id'] . "')\">Kill</button></td>";
echo "</tr>";
}
And this is the part which doesn't seem to work. I get the variable and some other values from the database and insert them into my table as long as there are values. Everything is displayed, even the buttons; but clicking on them doesn't do anything.
Source code of the website seems fine:
<td><button onclick="delete_purchase('138')">Kill</button></td>
Hope everything's clear, and you guys have some ideas what's wrong. If you need to know additional stuff, just ask and I'll see what I can do.
onclick="delete_purchase('138')"
calls a Javascript function called delete_purchase, which doesn't seem to exist in your code. You only have a PHP function with that name.
Since all PHP is executed on the server side, the HTML will be built long before the client ever sees the code and therefore you will never be able to call the delete_purchase PHP function from the client side.
The only two ways to get around this are:
- Create a delete_purchase JS function that then calls a PHP file through the use of AJAX.
- Don't call the onclick JS function at all and make the button a regular form submit that you then catch on the server side to delete the purchase. This however would involve a complete page refresh.
Your delete_purchase() function is defined in server-side which is not available in client side. You need to send a request to server and send the id, for example:
?action=delete&id=1
Then you can validate it on server side and call the function
<?php
if(isset($_GET['action']) && $_GET['action'] == 'delete'){
//do some staff
}
?>
you try to call a PHP-function directly from HTML (from browser)
this is impossible!
you may call it using 2 ways:
1) AJAX-call of php-script which will delete the purchase
2) redirect browser to php-script which will delete the purchase and then redirects you back

php processing a dynamically generated form

I'm using php to generate an html page that displays blog/thread items, and I am using javascript to show/hide some of the details. The problem is that I am generating unique IDs for each set of hidden content, which contains a form to process the input. In processing the form, I need to know which blog item was edited - I want to use $_POST. I'm pretty new to javascript, and I'm thinking that there is probably a solution I can use there.
I want the post to save the text to the mysql database (so call one of my php functions that I have working) and tell me what the text was and what the threadId is.
Here is the php code snipet, where $threadDetailItem is an array that has my thread data in it.
foreach ($threadData as $threadDetailItem)
{
// display main line (a bunch of code here ...)
// append button to edit or delete the post for admin
if ( isset ($_SESSION['isAdmin']) && $_SESSION['isAdmin'] == 'Y'){
// edit link opens content, and delete pops up a confirmation box
$el = sprintf ("editThreadLink_%d", $threadDetailItem['blogThreadId']);
$ec = sprintf ("editThreadContent_%d", $threadDetailItem['blogThreadId']);
$link1 = sprintf ("<a id=\"%s\" href=\"javascript:toggle('%s', '%s');\">+</a>", $el, $ec, $el);
$msg .= sprintf ("<li id=\"field6\">%s</li>\n", $link1);
}
$msg .= "</ul>\n";
echo $msg;
// now that the row is printed, lets add the hidden content if admin so they can edit
if ( isset ($_SESSION['isAdmin']) && $_SESSION['isAdmin'] == 'Y'){
// hidden content to enable editing of the posting
$msg = sprintf ("<div id=\"%s\" style=\"display: none\">\n", $ec);
echo $msg;
echo "<form name=\"form\" method=\"post\" action=\"\">\n";
$msg = sprintf ("<textarea id=\"%s\" name=\"%s\">%s</textarea>\n",
$ec, $ec, $threadDetailItem['threadTitle']);
echo $msg;
$msg = sprintf ("<button type=\"submit\"> %s</button>\n", $lang->get('BLOG POST'));
echo $msg;
echo "</form>\n";
echo "</div>";
}
}
Suggestions on good ways to handle this event are much appreciated. Thanks in advance.
The fields in the data are: blogThreadId, threadTitle, username, createdOn, lastUpdated, displayed (not used) and threadDetails (array containing the posting information).
I was able to use $_POST along w/ the ID in a hidden field to enable my php scripts to know which thread was being edited. It is working

Display personal messages list

I have a personal message system in my website done simply with php/sql. Actually I am facing the trouble to display them using jquery. The db has as fields: message_id, message_from, message_to, message_topic, message_subject and message_status. The way I am showing the message_topic is repeating eight times the following:
echo '<table><tr><td>';
retrieve_msg_topic($result);
echo '</td></tr>'; //of course I won't make 8 tables!!!
the function called is:
function retrieve_msg_topic($result)
{
if($row = mysql_fetch_assoc($result))
{
echo $row['usernombre'];
$message_topic = stripslashes($row['message_topic']);
echo '<div id="msg'.$row['message_id'].'">';
echo $message_topic;
echo '</div>';
//this will return: <div id="msgN">message topic (title, commonly subject)</div>
}
} //end function retrieve msg topic
So far I have a list on a table with the last eight messages sent to the user. The following row is reserved for pagination (next/prior page) and, after that, another row showing the message I select from the list presented, like we see in Outlook. Here is my headache. My approach is to call another function (8 times) and have all of them hidden until I click on one of the messages, like this:
echo '<tr><td>';
retrieve_msg_content($result);
retrieve_msg_content($result); //repeat 8 times
echo '</td></tr></table>';
the function this time would be something like this:
function retrieve_msg_content($result)
{
if($row = mysql_fetch_assoc($result))
{
echo '<script type="text/javascript">
$(document).ready(function(){
$("#msg'.$row['message_id'].'").click(function(){
    $(".msgs").hide(1000);
$("#'.$row['message_id'].'").show(1000);
});
});
</script>';
echo '<div class="msgs" id="'.$row['message_id'].'" style="display: none">'
.$row['message_subject'].
'</div>';
}
/* This function returns:
// <script type="text/javascript">
// $(document).ready(function(){
// $("#msgN").click(function(){
// $(".msgs").hide(1000);
// $("#N").show(1000);
// });
// });
// </script>
// <div class="msgs" id="N" style="display: none">Message subject (body of message)</div>
*/
} //end function retrieve msg content/subject
I could simply explain that the problem is that it doesn't work and it is because I do if($row = mysql_fetch_assoc($result)) twice, so for the second time it doesn't have any more values!
The other approach I had was to call both the message_topic and message_subject in the same function but I end up with a sort of accordion which is not what I want.
I hope I was clear enough.
The easiest way to fix your troubles would be to copy the results of the MySQL query into an array
while($row = mysql_fetch_assoc($result)) {
$yourArray[] = $row;
}
And then use that to build your tables.
edit: What I meant was more along the lines of this:
while($row = mysql_fetch_assoc($result)) {
$yourArray[] = $row;
}
echo '<table>';
foreach($yourArray as $i) {
retrieve_msg_topic($i);
}
echo '<tr><td>';
foreach($yourArray as $i) {
retrieve_msg_content($i);
}
echo '</tr></td></table>';
And then removing everything to do with the SQL query from those functions, like this:
function retrieve_msg_topic($result) {
echo '<tr></td>'$result['usernombre'];
echo '<div id="msg'.$result['message_id'].'">';
echo stripslashes($result['message_topic']);
echo '</div><td></tr>';
}
Right now you're doing some weird key mojo with ret[0] being the topic and $ret[1] being the message, which isn't a good practise. Also, I don't see the declaration of $i anywhere in that code.
The error suggests that the result is empty or the query is malformed. I can't be sure from the code I've seen.
A few other notes: it seems weird that you're using stripslashes() on data that's directly from the DB. Are you sure you're not escaping stuff twice when inserting content into the DB?
Always use loops instead of writing something out x times (like the 8 times you said in your question). Think of a situation where you have to change something about the function call (the name, the parameters, whatever). With loops you have to edit 1 place. Without, you need to edit 8 different places.
BTW, another solution to this problem would be using AJAX to load content into the last cell. If you're curious, I could show you how.
more edits:
For AJAX, build your message list as usual and leave the target td empty. Then, add a jQuery AJAX call:
$('MSG_LIST_ELEMENT').click(function() {
var msgId = $(this).attr('id').replace('msg','');
$.get(AJAX_URL+'?msgID='+msgId,function(data) {
$('TARGET_TD').html(data);
})
});
Replace the capitalized variables with the ones you need. As for the PHP, just echo out the contents of the message with the ID $_GET['msgID'].
However, make sure you authenticate the user before echoing out any messages, so that someone else can't read someone's messages by switching the id number. Not sure how authentication works on your site, but this can be done by using session variables.

Categories