In the phtml file shows all my database in a table including price, id etc , and then in the php file Details when the user try to press rent it takes the Id of the item and store it in the shop using the method add I keep getting this error
Fatal error: Function name must be a string.
The reason why I store the id of the item from the database so when the user check out I ll retrieve all the information using the id of the item been selected by the user. and also I am using array list to store more then one item, another thing to mention they way of getting the id of the item is by the local variable $tem = $_POST(['$dvdDetails->getDvdId()']); in the adding cart file but i am not really sure if its store the right value as there is a foreach loop and The duration of the variable will be distorted by the end of the method so how can i get the the id of the item been selected.
<?php
require_once('Models/Product.php');
class Shop {
private $_products = array();
public function getProducts()
{ return $this->_products;}
public function addProduct(Product $product)
{ $this->_products[] = $product;
return $this;
}
}
?>
<?php
class Option {
private $_optionKey;
private $_optionValue;
public function getKey()
{ return $this->_optionKey; }
public function getVlue()
{
return $this->_optionValue;
}
public function setOption($key, $value)
{
$this->_optionKey = $key;
$this->_optionValue = $value;
return $this;
}
}
?>
<?php
require_once('Models/Option.php');
class Product {
private $_options = array();
public function getOptions()
{ return $this->_options; }
public function addOption(Option $option)
{ $this->_options[] = $option;
return $this;
}
}
?>
//SHow all
<?php require('template/header.phtml') ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table class="datatable">
<tbody>
<?php foreach ($view->dd as $dvdDetails) {
echo '<tr> <td>'
.'<img src="images/'. $dvdDetails->getPhotoDetails() .'"alt="no picture" height="240" width="820" />' .'<br><br>'.'<font size="3" color="#2E2E2E"><center>'. $dvdDetails->getDvdPhoto(). '</center></font>'.
'<br><br><br>'. '<font size="2" color="blue"><strong>Genre: </strong></font>'. $dvdDetails->getDvdGenre() .
'<br><br>'. '<font size="2" color="blue"><strong>Director: </strong></font>'. $dvdDetails->getDvdDirector() . '<br><br>' .'<font size="2" color="blue"><strong>Ritels: </strong></font>'. $dvdDetails->getDvdRitels() .
'<br><br>' . '<font size="2" color="blue"><strong>Price for rent: </strong></font>'. $dvdDetails->getDvdId()) .
'<br><br>' .
'<div class="ghassar">' .
'<div id="op"> <label>Number of days </label> <select name="days" > <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option>
</select>
<br><br><br><br>
</div>
<div>
<input type="submit" value="Add to the basket" name="rent" id="buttom1" />
</div> ' . '<br><br>' .
'<br><br>' .'<div>'.
'</td> </td> </tr>';
} ?>
</tbody>
</table>
<?php require('template/footer.phtml') ?>
// adding to the cart
<?php
require_once('Models/Dvd_sql.php');
require_once('Models/Shop.php');
$view = new stdClass();
$view->dd = 'SQL';
$dvd_sql = new Dvd_sql();
$view->dd = $dvd_sql->fetchAllStudents(); //->fetchAllStudents();
if (isset($_POST['rent']))
{
$tem = $_POST(['$dvdDetails->getDvdId()']);
$shop = new Shop(); $shop->addProduct($tem);
}
require_once('Views/dvdDetails.phtml');
I think what you're trying to do is get the ID of the DVD from the form page into the form processing page. Assuming that's it, there are a couple of problems with the way you're going about that.
First, $_POST['$dvdDetails->getDvdId()'] is looking in the post data for a string key literally matching the string '$dvdDetails->getDvdId()'. Strings in single quotes aren't interpolated by PHP, and even with double-quotes you really want to stick with simple variables and/or use {$brackets}.
Second, it seems to me that the object $dvdDetails does not even exist in the form processing script. I only see it in the form display code, and that does not automatically transfer it over to the processing script. You'll need to explicitly pass the data you need in the form. For that, you can do something like this:
In the form (following your string concatenation style)
'<input type="hidden" name="item_id" value="' . $dvdDetails->getDvdId() . '">' .
in the processing script
$item_id = $_POST['item_id'];
Edit
The first time around, I missed the fact that you're looping over many DVD items. In that case, my advice would lead to many item_id inputs and only one (the last, I think) will be seen by the processing script. Your "days" selector will suffer from the same problem. In this case, I think simplest solution would be to create a separate form for each DVD and use my advice above. That way only one copy of "days" and "item_id" get sent when you submit the form for a particular DVD.
Related
I building on top of an existing PHP based application to ability to update menu items name and prices.
I have generated a dynamic form which is populated with the results form the database. The idea is that the user can update the item name or price to update the information in the database.
The form works fine, but I am having dome trouble getting the info out of the form. each Item has a separate ID so I need to essentially do a foreach through the form and call the update function each time with the respective item id.
I can handle the DB side of things fine, but the application I am building on has a 'getInput' function to check input exists and to get the input form the form and I would like to use this.
This is the getInput function:
public static function exists($type = 'post') {
switch($type) {
case 'post':
return (!empty($_POST)) ? true : false;
break;
case 'get';
return (!empty($_GET)) ? true : false;
break;
default:
return false;
break;
}
}
public static function get($item) {
if(isset($_POST[$item])) {
return $_POST[$item];
} else if(isset($_GET[$item])) {
return $_GET[$item];
}
return '';
}
}
The problem I have is when calling this function it only returns the last item form the form. Is there a way i can iterate though the form and get each item?
This is the dynamic form and the getInput code so far:
$menuItems = DB::getInstance()->get('menu_items', array('cat_id', '=', $cat_id ));
if($menuItems->count()) {
echo '<form class="updateMenu" action="" method="post">';
echo '<table class="gridtable gridtableMenu">';
echo '<tr><th>Item Name</th><th>Item Price</th></tr>';
foreach($menuItems->results() as $item) {
echo '<tr>';
echo '<td class="menu-name"><input type="text" name="itemName" value="' . $item->item_name . '" required></td>';
echo '<td class="menu-price"><input type="number" step="any" name="itemPrice" value="' . $item->item_price . '" required></td>';
echo '<input type="hidden" name="id" value="' . $item->id . '">';
echo '</tr>';
}
echo '</table>';
echo '<input type="submit" name="updateMneu" value="Update Menu">';
echo '</form>';
} else {
echo '<div class="error">No items have been added to this menu</div>';
}
} // close categories foreach
} // close if category set
if(isset($_POST['updateMneu'])) {
echo Input::get('id'), '</br>';
echo Input::get('itemName'), '</br>';
echo Input::get('itemPrice'), '</br>';
} //close if isset updateMenu If
So I would like a foreach I think around this section:
if(isset($_POST['updateMneu'])) {
echo Input::get('id'), '</br>';
echo Input::get('itemName'), '</br>';
echo Input::get('itemPrice'), '</br>';
//update ite in the database, and move to gthe next item.
} //close if isset updateMenu If
I will handle data validation and what not later on.
As posted by 'noobHere' the answer was to set the input types name as arrays. e.g. name="itemName[]" instead of name="itemName"
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 a newbie to multidimensional array's
I have a form that stores data into an array.
I would like my users to re-use the form and store data to the array.
So my idea was a multidimensional array that stores a new array everytime the form is used.
But my problem is that I have no idea how to do this.
Here is my form:
$customer = '';
$customer .= '<tr><td>customername:<br/><input type="text" name="customer[customername]" value="" /> </td></tr>';
$customer .= '<tr><td>customertitle 1:<br/><input type="text" name="customer[customertitle1]" value="" /> </td></tr>';
$customer .= '<tr><td>customeremail 1:<br/><input type="text" name="customer[customeremail1]" value="" /> </td></tr>';
$customer .= '<tr><td>customertitle 2:<br/><input type="text" name="customer[customertitle2]" value="" /> </td></tr>';
$customer .= '<tr><td>customeremail 2:<br/><input type="text" name="customer[customeremail2]" value="" /> </td></tr>';
echo $customer;
This saves the form in an array:
if(isset($_POST['Submit'])) {
$customer = $_POST['customer'];
And this shows the first value of the array:
$customers = array(get_option('customer'));
foreach($customers as $customer){
echo $customer["customername"];
}
I hope this makes sence to anyone!!!!
Yes figured it out
Here goes for the ones that wish to know:
First create a function to get the current array.
Save the new value from the form with update_option
function savearray (){
if(isset($_POST['Submit'])) {
// get the option
$customers = get_option( 'customers' );
// add new data to the option
$customers[] = $_POST['customers'];
// save it back to the db
update_option( 'customers', $customers );
}
Then create a form that places data in arrays by name
<?php
$customers = '';
$customers .= '<tr><td>Name:<br/><input type="text" name="customers[name]" value="" /> </td></tr>';
$customers .= '<tr><td>Contact 1:<br/><input type="text" name="customers[contact1]" value="" /> </td></tr>';
echo $customers;
?>
So this works....
Now the next step.
I want to only show the name of the costumer and create a link to the data of the specific costumer.
So I did this:
<?php
$customers = get_option('customers');
foreach($customers as $val){
echo ''.$val["name"] . '<br>';
}
?>
This tells me that I want to view the name of all costumers in tha array and create a link.
I have no idea how to target the specific data in the array.
Anyone?????
I think you need to use ArrayObject
Ex:
<?php
// add a new consumer in your new array
$consumer["name"] = "John Doe";
$consumer["email"] = "toto#yopmail.com";
...
$a = new ArrayObject();
$a->append($consumer)
// for get a consumer in the array
foreach ($arr as $key => $value)
{
// Some instruction
}
?>
Hope it will help you
I've done some searches and I've come up with no clear answer. I'm not a javascript person at all and am pretty clueless. PHP I understand however, and to me this should work. I should also note, that this script used to use document.all for it's javascript, which I've tried to update to getElementById() when possible (since document.all was throwing an error in firebug).
Now for the most part, the page displays fine, albeit without the javascript changes that are supposed to happen.
I must also apologize for the archaic nature of the code, I inherited this code when I took over as internet guy for our gaming club. This code is for the purchase of fictional items using fictional credits.
When I click an item to "buy" it (or maybe not whichever) The background of that row is supposed to turn green, and the credits are supposed to be subtracted from my total account (or reverse if I uncheck the box). Clicking the submit button adds this stuff I clicked to another sheet, and subtracts the actual amount from my account.
Currently I get a "tr615 is undefined" error This is the PHP generated code for the element as shown below.
If someone can help me figure this out it would fantastic. I just can't seem to find an answer after a few days of searching google and here.
PHP Snippet of relevent code: (we use custom functions on our site ie: entry)
For instance say $id=615
<?php
while (list ($id, $name, $class, $desc, $range, $damage, $cost,$hide) = entry ($items) )
{
if ($hide =='0')
{
$JavaScriptArrayParms .= '"' . $id . '",';
$list .= $id . ',';
?>
<tr id="tr<?php echo $id; ?>"> //Thus tr615 for this example
<td>
<input type="checkbox" name="chk<?php echo $id; ?>" onclick="updateStoreTable(this.form, this, <?php echo $id; ?>)" />
<input type="hidden" name="cost<?php echo $id; ?>" value="<?php echo $cost; ?>" />
</td>
<td><?php echo $name; ?></td>
<?php if (! in_array($catid, $noclass)){ echo "<td>$class</td>";}?>
<td><?php echo $desc; ?></td>
<?php if (! in_array($catid, $norange)){ echo "<td>$range</td>";}?>
<td><?php echo $damage; ?></td>
<td><?php echo $cost; ?></td>
</tr>
<?php
}
}
?>
</table>
<input type="hidden" name="list" value="<?php echo $list; ?>" />
<input type="button" value="Purchase!" onclick='validatePurchase(this)' />
<input type="reset">
</form>
Relevant JS: (which used to be document.all.store... or just document.all.. in some cases. I hope I fixed it the right way)
<script language="javascript">
var startmoney = <?php echo $currMoney; ?>;
function canAfford(t,id)
{
if(t.checked) return;// don't touch if checked for buying.
//alert("canAfford("+t+","+id+");");
//t.disabled = false;
eval("document.store.getElementByID(foo).disabled = false;");
eval("document.store.getElementByID(foo).checked = false;");
eval("document.getElementByID(tr"+id+").style.background = '#000000';");
}
function cantAfford(t,id)
{
//alert("cantAfford("+t.disabled+","+id+")-- "+t+";");
//alert("before disable");
//t.disabled = true;
eval("document.store.getElementByID(chk"+id+").disabled = "+true+";");
//alert("After disable");
eval("document.store.getElementByID(chk"+id+").checked = false;");
eval("document.getElementByID(tr"+id+").style.background = '#555555';");
}
function getCost(id)
{
return eval("document.store.getElementByID(cost"+id+").value");
}
function buying(t,id)
{
eval("document.getElementByID(tr"+id+").style.background = 'green';");
document.store.credits.value -= getCost(id);
}
function notbuying(t,id)
{
eval("document.getElementByID(tr"+id+").style.background = '#000000';");
var creds = new Number(document.store.credits.value);
var cost = new Number(getCost(id));
document.store.credits.value = (creds + cost);
}
function updateStoreTable(f,t,id)
{
var ids = new Array(<?php echo $JavaScriptArrayParms; ?>);
if(t.checked)
buying(t,id);
else
notbuying(t,id);
for(i = 0; i<ids.length; i++)
{
cost = new Number(getCost(ids[i]));
creds = new Number(f.credits.value);
//alert("COST: " +(cost)+"\nCREDITS: "+creds+"\nID: "+ids[i]);
// alert("'"+ (cost) + "' > '" + (creds) +"'\n"+(eval(cost > creds)));
// alert("f.chk"+ids[i]+".checked");
if(eval("f.chk"+ids[i]+".checked")) { continue; } //ignore already carted items
if(eval(cost > creds))
cantAfford(eval("f.chk"+id),ids[i]);
else
canAfford(eval("f.chk"+id),ids[i]);
}
}
1st issue:
it has to be getElementById()
(a lower-case d at the end)
2nd:
When using eval, the code will be evaluated as:
document.getElementById(tr615).style.background = '#000000';
..what will force the error, because the tr615 is not enclosed by quotes, so javascript expects a variable tr615.
the line must look like this:
eval("document.getElementById('tr"+id+"').style.background = '#000000';");
But: Why do you use eval here, this can be done without eval:
document.getElementById('tr'+id).style.background = '#000000';
I inserting a form data in mysql database using oop php in a pre made project.all work is coorrect but after submit any success and failed message is not showing.
my form sample code is:
performance.php->
<h1>Employee Review Form</h1>
<form name="product" action="" method="post" id="customForm">
<table>
<tr>
<td>Review Employee Id</td>
<td><input type="text" name="rcode" id="rcode" class="genInputBox" /></td>
</tr>
<tr>
<td>Domain Knowledge(Subject Matter)</td>
<td><select name="dk" id="dk">
<option value="">Plz Select Ratting </option>
<option value="5">5</option>
<option value="4">4</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
</select></td>
</tr>and more...............
<input type="submit" value="register" id="submit" name="form_submit"/>
</td></tr>
</table>
</form>
and form submit process
<?php
if(isset($_POST) && isset ($_POST["form_submit"])){
$valArr=array("review_emp_id"=>$_POST['rcode'],"subject_matter"=>$_POST['dk']);
$per_obj = new Performance();
$per_obj->addPreformance($valArr, "employee_performance");
}
?>
and my class performance page is:
<?php
require_once("admin/includes/class_common_lib.php");
require_once("class.userinfo.inc.php");
class Performance extends DataAccess{
var $db_obj = null;
public function __construct() { //for database connectivity
$this->db_obj = new DataAccess();
}
public function addPreformance($key_values = array(), $table = null) {
$this->db_obj->table_name = $table;
$this->db_obj->addRecord($key_values);
}
}
?>
and in class common lib add record function code is:
// Function for Add Record
function addRecord($key_values)
{
$cols="";
$vals="";
foreach($key_values as $key=>$value)
{
if ($key!="submit" and $key!="PHPSESSID" and $key!="image_name" and $key!="submit_button" and $key!="ext" and $key!="ext2" and $key!="img_name" and $key!="mode" and $value!="" and $key!="gpl" and $key!="ip1" and $key!="ip2" and $key!="ip3" and $key!="ip4"){
$cols .= "`".$key."`,";
is_string($value)? $vals .= "'".addslashes($value)."'," : $vals .= "'".$value."',";
}
}
$cols = substr($cols, 0, -1);
$vals = substr($vals, 0, -1);
$insert_qry="insert into ". $this->table_name ."(". $cols .") values(". $vals .")";
$r=mysql_query($insert_qry);
$this->msg = (!$r) ? f_add_msg : s_add_msg;
return $r;
}
Its a very big project and I do all the process which is done previous by other person.
now I want to show msz of data is submit in database or not (success or failed)after submission of form.
and I found these line in config file
define ("s_add_msg", "Record successfully added.");
define ("f_add_msg", "Record not added. Please try again.&error=1");
I know its lengthy code, but I need to show what happens.
all function Is working correctly,but
how can I show success or failed message in performance.php page?please help
It's common in programming to use the Post/Redirect/Get pattern in situations like this. Without seeing your entire codebase a quick fix for this might be to change your form submit like this:
<?php
if(isset($_POST) && isset ($_POST["form_submit"])){
$valArr=array("review_emp_id"=>$_POST['rcode'],"subject_matter"=>$_POST['dk']);
$per_obj = new Performance();
$per_obj->addPreformance($valArr, "employee_performance");
$redirectLink = "someOtherUrl.php?m=" . urlencode( $per_obj->db_obj->msg );
header( 'Location: ' . $redirectLink );
die();
}
?>
This will redirect to the new URL you have specified where you should be able to retrieve the status message using $_GET['m'].
Eventually you'd want to handle this in a much cleaner way across the system but if you're just trying to fix legacy code that will at least get you started.