I am looking for the cleanest way I could do the following.
<?php
function display_data($label, $yes_no, $model) {
$return = "<tr><th><label>".$label."</label></th><td>";
if ($yes_no == '1') { $return .= "Yes"; } else { $return .= "No"; }
$return .= "</td><td>";
if (isset($model)) {
$return .= $model;
}
$return .= "</td></tr>";
return $return;
}
?>
<table>
<thead>
<tr>
<th>Make</th>
<th>Yes/No</th>
<th>Model</th>
</tr>
</thead>
<tbody>
<?php
echo display_data("Ford", $car_form["available"], $car_form["avail_model"]);
echo display_data("Honda", $car_form["available"], $car_form["avail_model"]);
?>
</tbody>
</table>
I want to be able to EDIT the body contents of the table by just clicking on any of them, with say jquery. Changing the value and once I click out of it, it saves with AJAX.
So I should be able to click into any of the Yes/No or Model rows and change them. I'm going to have a lot of data, so I am not sure how to do this in large scale. I just don't want to have to create a individual jquery function, and divs for every single piece of data I have. If anyone can think of a cleaner way, that would be awesome.
Everything I have now, is working correctly, I just have not implemented a CRUD like system into this yet.
Related
This is probably a stupid question, but I'm new to coding so here goes :-).
I'm trying to create a simple plugin for WordPress. The plugin gets data from a MySQL database and echos out a table with the results. My problem is when I use echo the plugin is places first on the page even if i put the shortcode in the middle of the page. I understand that is because I use echo instead of return. I just don't get how to use return in my case. Any help would be much appreciated :-).
Here's my code:
$get_runners = $connection->prepare('SELECT first_name, last_name, nick_name, FROM database WHERE status = :status ORDER BY first_name ASC');
$get_runners->execute([status=>'success']);
// Create the table
echo '
<table id="Table" class="start-list-table">
<thead>
<tr class="start-list-tr">
<th scope="col">Name</th>
<th scope="col">Club</th>
</tr>
</thead>
<tbody>
';
// Get the runner object:
$runners = $get_runners->fetchAll();
foreach($runners as $runner){
if($runner->nick_name)
{
$runner_name = $runner->first_name.' "'.$runner->nick_name.'" '.$runner->last_name;
}
else
{
$runner_name = $runner->first_name.' '.$runner->last_name;
}
echo '
<tr class="start-list-tr">
<td data-label="Name">'.$runner_name.'</td>
<td data-label="Club">'.$runner->club.'</td>
</tr>';
}
echo '</tbody>
</table>';
}
add_shortcode( 'startlist', 'create_startlist' );
You want to assign your output to a variable, instead of echoing:
$get_runners = $connection->prepare('SELECT first_name, last_name, nick_name, FROM database WHERE status = :status ORDER BY first_name ASC');
$get_runners->execute([status=>'success']);
// Create the table
$output = '
<table id="Table" class="start-list-table">
<thead>
<tr class="start-list-tr">
<th scope="col">Name</th>
<th scope="col">Club</th>
</tr>
</thead>
<tbody>
';
// Get the runner object:
$runners = $get_runners->fetchAll();
foreach($runners as $runner){
if($runner->nick_name)
{
$runner_name = $runner->first_name.' "'.$runner->nick_name.'" '.$runner->last_name;
}
else
{
$runner_name = $runner->first_name.' '.$runner->last_name;
}
$output .= '
<tr class="start-list-tr">
<td data-label="Name">'.$runner_name.'</td>
<td data-label="Club">'.$runner->club.'</td>
</tr>';
}
$output .= '</tbody>
</table>';
return $output;
}
add_shortcode( 'startlist', 'create_startlist' );
This uses concatenation to continue to fill the variable through your function. You then set the return to the $output variable.
Firstly read more about Shortcodes Output : https://codex.wordpress.org/Shortcode_API#Output
There are two ways that I can think of at this moment.
Using ob_start... basically you need to wrap you code in ob_start()
function create_startlist() {
ob_start();
/* CODE HERE */
return ob_get_clean();
}
Second is to use a concatenation operator
function create_startlist() {
$output = '';
$output .= 'OUTPUT HERE';
return $output;
}
Okay, I've narrowed this down to one key function.
It seems impossible, but every time I've "echo"ed it, this function always says that the variable array I'm using to store my data is no longer an array.
Offending Code
private function do_display_message_details()
{
$m_message_values = '';
$m_address = APP_ROOT_PATH;
if ($this->c_arr_stored_message_data)
{
echo "I AM AN ARRAY";
}
else
{
echo "I AM NOT AN ARRAY";
}
$m_message_name = $this->c_arr_stored_message_data['message-name'];
$m_arr_stored_message_data = $this->c_arr_stored_message_data['message-retrieved-data'];
foreach((array)$m_arr_stored_message_data as $m_message_value)
{
$m_message_row = explode(',', $m_message_value);
$m_message_values .= '<tr>';
$m_message_values .= '<td>' . $m_message_row[0] . '</td>';
$m_message_values .= '<td>' . $m_message_row[1] . '</td>';
$m_message_values .= '<td>' . $m_message_row[2] . '</td>';
$m_message_values .= '</tr>';
}
$this->c_html_page_content = <<< VIEWSTOREDMESSAGEDATA
<div id="lg-form-container">
<h2>Message name: $m_message_name</h3>
<h3>Message Data</h3>
<table border="1">
<tbody>
<tr>
<th>Date</th>
<th>Time</th>
<th>Message Values</th>
</tr>
$m_message_values
</tbody>
</table>
<br />
<form method="post" action="$m_address">
<label for="anothergo">Another Message?</label>
<button name="feature" value="display_message_data">Review Stored Message Data</button>
</form>
</div>
VIEWSTOREDMESSAGEDATA;
}
Constructor to show you it is set up as an array
private $c_arr_stored_message_data;
private $c_error_message;
private $c_page_content;
// ~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
public function __construct()
{
$this->c_arr_stored_message_data = array();
$this->c_error_message = '';
$this->c_page_content = '';
}
But, if you try it on a different function, it works.
Trial Code That Works!
// ~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
public function set_stored_message_data($p_arr_stored_message_data)
{
$this->c_arr_stored_message_data = $p_arr_stored_message_data;
if ($this->c_arr_stored_message_data)
{
echo "I AM AN ARRAY";
}
else
{
echo "I AM NOT AN ARRAY";
}
}
Your "I AM AN ARRAY" checks don't work quite as you think:
$x = array();
if ($x) {
echo 'I AM AN ARRAY';
} else {
echo 'I AM NOT AN ARRAY';
}
That prints out 'I AM NOT AN ARRAY', as an empty array evaluates to false in PHP. You can use var_dump to see exactly what content your variables have.
You have a variable named $c_page_content but later you refer to $c_html_page_content. Perhaps a mistake?
If the "messages" can contain user-supplied text, then there are XSS vulnerabilities in your code. It is essential to use htmlspecialchars to render text in HTML. For example, if $m_message_row[0] is text, you must write '<td>' . htmlspecialchars($m_message_row[0]) . '</td>'. Ditto for any other values that are not supposed to contain HTML markup that are written to HTML.
Your main issue, that the data is apparently not being stored in your c_arr_stored_message_data variable, is not possible to reproduce without seeing the connecting code that calls set_stored_message_data and do_display_message_details. All I can suggest is that you make sure you're calling them in the right order on the same instance of the same class.
I'm currently having 2 pages that is "index.php", "retrieve_search_forklift.php" and "search_forklift.php".
I try to passing the "txtSearch" input from index.php using jQuery $.post method to "retrieve_search_forklift.php" for execute the select query and echo the $output.
In "search_forklift.php" will use a function to load the "retrieve_search_forklift.php" when page is load and display the $output in a table.
Index.php
$('#txtSearch').keydown(function(e) {
var code = (e.keyCode || e.which);
if((code == 13)){
txtSearch = $('#txtSearch').val();
$.post('php/retrieve_search_forklift.php',{
txtSearch : txtSearch
},
function(data){
//alert(data);
window.location.replace("search_forklift.php");
})
}
});
Retrieve_search_forklift.php
<?php
require('../database_connection.php');
if($txtSearch = $_POST['txtSearch']){
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT f_brand, f_ftype, f_image, f_code, f_description, f_sale, f_rental FROM tblforkliftdetail WHERE f_brand='Toyota'";
$result = mysqli_query ($mydatabase, $query);
$counter = 0;
while($info = mysqli_fetch_array( $result ))
{
if( $counter % 3 == 0 )
$output .= "<tr>";
$output .= "<td style='background-color:yellow; '><img src=".$info['f_image'] ." width=210px height=210px ></img></p></td>";
$output .= "<td style='background-color:black;'>";
$output .= "</td>";
if( $counter % 3 > 1)
$output .= "</tr>";
$counter++;
}
echo $output;
}
#mysqli_close($mydatabase);
?>
Search_forklift.php
$(document).ready(function(){
loadsearchtblForklift();
});
function loadsearchtblForklift(){
$('#tblsearchForklift').load('php/retrieve_search_forklift.php');
}
<table id="tblsearchForklift">
<tbody>
</tbody>
</table>
I shall simplify this.
You are making a request from A to B; then asking C to show the data that B has generated earlier. This boy, is not possible unless you store the data of B somewhere(DB/file system).
why?
A --> B is a separate request and C --> B is separate. The server does not know that it has to store the data for future request use. You have to change the approach to fulfill this logic.
My Suggestion -
Discard 'Search_forklift.php' and directly show the results in the 'index.php' page directly.
changed index.php file
$('#txtSearch').keydown(function(e) {
var code = (e.keyCode || e.which);
if((code == 13)){
txtSearch = $('#txtSearch').val();
$.post('php/retrieve_search_forklift.php',{
txtSearch : txtSearch
},
function(data){
$('#tblsearchForklift').html(data);
})
}
});
<table id="tblsearchForklift">
<tbody>
</tbody>
</table>
Or, store the result of 'Retrieve_search_forklift.php' in a txt file or into a CLOB column in database with a session key and retrieve it using the same key to display in the 'Search_forklift.php'.
This approach shall ensure that, the person after you who is going to curse everyday of their life maintaining it. May be you yourself may do that after an year or two. :) Don't get me wrong here. but i just want to make you understand the way web and programming life works.
EDIT: reading again, i got another approach (bad) idea. You can do this in one more way.
Once your ajax call in index.php is returned, POST the results to the 'Search_forklift.php' page and in there just say
<table id="tblsearchForklift"><?php echo $_POST[results]; ?></table>
I have dynamically generated table in PHP but in response this table is not being created as datatable even i have used datatable plugin in file.
I have also one table that is generated on the page ready event with same schema and it has datatable behaviour.
so whats problem with dynamically generated table?
Plz Help
Thanks.
My code is as below :
ajax.php
$projectArr=$database->select("odeskuserdetails","OdeskUserId,UserName","IsDeleted=0");
$grand=0;
for($i=0;$i<count($projectArr);$i++){
$query="SELECT count(JobStatusId) as count from jobstatus where CreatedDate BETWEEN '".$_REQUEST['dateFrom']."' AND '".$_REQUEST['dateTo']."' and StatusId=3 and UserId in (SELECT UserId FROM odsekuserassignment where OdeskUserId =".$projectArr[$i]['OdeskUserId'].")";
$result= mysql_query($query);
$row= mysql_fetch_array($result);
$k=$i+1;
$projectArr[$i]['Sr.No.']=$k;
$projectArr[$i]['Total Jobs']=$row['count'];
$grand +=$row['count'];
}
// Sort the array by Total Jobs.
usort($projectArr, function ($a, $b) {
return ($b['Total Jobs'] - $a['Total Jobs']);
});
// Table Creation Starts :
echo '<table id="table2" class="tablesorter table table-bordered table-condensed table-hover table-striped" >
<thead>
<tr>
<th><center>Sr. No.</center></th>
<th><center>Odesk Account</center></th>
<th><center>Total Jobs Applied</center></th>
</tr>
</thead>
<tbody>';
if(is_array($projectArr))
{
$cval='0';
foreach ($projectArr as $data) {
if (!is_array($data)) {
if($cval=='0')
{
$cval ='1';
echo '<tr class="allPrjRow">';
echo '<td><center>'.$projectArr["Sr.No."].' </center></td>';
echo '<td><center>'.$projectArr["UserName"]. '</center></td>';
echo '<td><center>'.$projectArr["Total Jobs"].'</center></td>';
echo '</tr>';
} }
else
{
echo '<tr class="allPrjRow">';
echo '<td><center>'.$data["Sr.No."].'</center></td>';
echo '<td><center>'.$data["UserName"].'</center></td>';
echo '<td><center>'.$data["Total Jobs"].'</center></td>';
echo '</tr>';
}
}
echo '</tr>';
// print_r($x);
}
echo '</tbody>
</table>
<div id="gtotal" style="float: right;margin-right: 200px;">Grand Total :'.$grand.'</div>';
It depends on where you have put your code snippet. Place the code which creates dynamic table at the end,when all the js gets loaded.
I am trying to get some data from Magento trough php, it works but I need to add multiple collections and now I am stuck. I am just a beginner so please forgive me :-)
I am using below code to get customer details, this works ok.
Now I need to add the customer/address to get the address details to fill the last column with the zipcode, anybody know how to do that?
<?php
function getcustomers() {
/* Magento's Mage.php path
* Mage Enabler users may skip these lines
*/
require_once ("app/Mage.php");
umask(0);
Mage::app("nl");
/* Magento's Mage.php path */
/* Get customer model, run a query */
$collection = Mage::getModel('customer/customer')
//$collection = Mage::getModel('customer/address')
->getCollection()
->addAttributeToSelect('*');
$result = array();
foreach ($collection as $customer) {
$result[] = $customer->toArray();
}
return $result;
}
?>
<html>
<head>
<title>Customers</title>
<style>
table {
border-collapse: collapse;
}
td {
padding: 5px;
border: 1px solid #000000;
}
</style>
</head>
<body>
<table>
<tr>
<td>ID</td>
<td>Lastname</td>
<td>Firstname</td>
<td>Email</td>
<td>Is Active?</td>
<td>Date Created</td>
<td>Date Updated</td>
<td>Website ID</td>
<td>Store ID</td>
<td>Zip Code</td>
</tr>
<?php
$result = getcustomers();
if(count($result) > 0){
foreach($result as $key => $value){
echo "<tr>";
echo "<td>".$value['entity_id']."</td>";
echo "<td>".$value['lastname']."</td>";
echo "<td>".$value['firstname']."</td>";
echo "<td>".$value['email']."</td>";
echo "<td>";
echo $value['is_active'] == 1 ? "Yes" : "No";
echo "</td>";
echo "<td>".$value['created_at']."</td>";
echo "<td>".$value['updated_at']."</td>";
echo "<td>".$value['website_id']."</td>";
echo "<td>".$value['store_id']."</td>";
echo "<td>".$value['zipcode']."</td>";
echo "</tr>";
}
}else{
echo "<tr><td colspan=\"7\">No records found</td></tr>";
}
?>
</table>
</body>
</html>
Just want to say that I'm currently learning Magento, so my answer will not be totally working! I hope it'll help to push you in the right direction.
Just a note, you can just use $customer->getData() to return an array.
Then you can use $customer->getId() to get the id. Which you can then pass into the Address model
foreach($collection as $customer){
// You have an instance of the Customer already, so we can just use a magic get method
$cid = $customer->getId();
// Let's load this customers address, using a chain. Load the model (instantiate the class), then call load with the customer id
// You might want to check the alias on 'customer' to ensure it has address. You can find this in /app/code/core/Mage/Customer/etc/config.xml ln.251
$address = Mage::getModel('customer/address')->load($cid);
// Maybe we should look in here just in case - for debugging
var_dump($address); // or echo get_class($address);
// Here I would try one of the magic setter methods, which map to set<Thing> so you can play with this to see if it'll work
$address->setZipCode('12345');
// Then we should be able to save it, I think, this bit I'm not sure on.
$address->save();
}
As I say, this is just what I've learnt from the Magento U videos over the last week, hope it works!