illegal string offset(codeigniter 3) - php

Hi been trying to retrieve records from my database, but I keep getting this error "Severity: Warning Message: Illegal string offset " in several fields.
controller
public function get_discount(){
if($this->session->has_userdata('logged_in')){
// redirect(base_url());
}
else{
$output = array();
$output['error']="failed";
$coupon_code=$this->input->post('coupon_code');
$product_price=$this->input->post('product_price');
$condition=array('coupon_code'=>$coupon_code,
'product_price'=>$product_price
);
$count['discount']= $this->Form_model->get_discount('coupon',$condition);
foreach($count['discount'] as $row)
{
echo json_encode($count['discount']);
if($count > 0){
$discount = $row['discount'] / 100;
$total = $discount * $product_price;
$array['discount'] = $row['discount'];
$array['product_price'] = $product_price - $total;
$output['success']="success";
echo json_encode($output);
}
}
}
}
this is my model
public function get_discount($data){
$sql = "SELECT * FROM coupon WHERE (coupon_code = ? ) AND status= 'valid' ";
$query = $this->db->query($sql, array($data['coupon_code']));
$result = $query->row() ;
if($query->num_rows()==1){
return $result;
}
}
This is my view
<form action="/get_discount" method="post">
<div class="form-group">
<h4 class="text-warning">*Optional</h4>
<label>Coupon Code</label>
<input class="form-control" name="coupon_code" type="text" id="coupon_code" />
<input type="hidden" value="<?php echo $product->product_price?>" id="price" />
<div id="result"></div>
<br style="clear:both;" />
<button class="btn btn-primary" id="activate">Activate Code</button>
</div>
</form>
<div class="form-group">
<label>Total Price</label>
<input class="form-control" type="number" value="<?php echo $product->product_price?>" id="total" readonly="readonly" lang="en-150" />
</div>
</div>
</div>

You're calling get_data() with too many arguments. It only $condition should be the only argument.
$count['discount']= $this->Form_model->get_discount($condition);
The error is because $data is the first parameter, which you're passing the string 'coupon' to in your call.

Related

displaying php in an echo nested in html

I'm trying to echo a piece of text with PHP nested in it, anyone know how? I've tried it like this:
function update_category(){
global $connection;
if (isset($_GET['edit'])) {
$edit_cat_key = $_GET['edit'];
$query = "SELECT * FROM categories WHERE cat_id = {$edit_cat_key }";
$edit_cat_query = mysqli_query($connection, $query);
echo '<form action="categories.php" method="post">
<div class="form-group">
<label for="new-cat-title">New name of category</label>
<input value="<?php if(isset($cat_title)){echo $cat_title;} ?>" type="text" class="form-control" name="new-cat-title">
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" name="submit" value="Rename Category">
</div>
</form>';
while($row = mysqli_fetch_assoc($edit_cat_query)) {
$cat_title = $row['cat_title'];
$cat_id = $row['cat_id'];
}
}
}
It prints: <?php if(isset($cat_title)){echo $cat_title;} ?>
I've tried it like this:
<input value="' . <?php if(isset($cat_title)){echo $cat_title;} ?> . '" type="text" class="form-control" name="new-cat-title">
I'd do it like this (showing only the echo part inside the php code):
echo '<form action="categories.php" method="post">
<div class="form-group">
<label for="new-cat-title">New name of category</label><input value="';
if(isset($cat_title)){echo $cat_title;};
echo '" type="text" class="form-control" name="new-cat-title"></div>
<div class="form-group">
<input class="btn btn-primary" type="submit" name="submit" value="Rename Category">
</div>
</form>';
This echoes the two strings (in single quotes) and in between them the variable depending on the condition, keeping the double-quote pairs of the attribute values intact.
Echo is a php statement. You use it to display an output, as a string. What you need is, replacing echo ' with ?> and </form>'; with </form><?php. These closing(?>) and opening(<?php) tags let you decide which part of your document should be processed as PHP. So PHP will ignore the rest of the document.
Based on Johannes' answer I managed to figure out an answer. I need to close the PHP tags and instead of echoing the wished result, put it in the while loop.
Like this:
function update_category(){
global $connection;
if (isset($_GET['edit'])) {
$edit_cat_key = $_GET['edit'];
$query = "SELECT * FROM categories WHERE cat_id = {$edit_cat_key }";
$edit_cat_query = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($edit_cat_query)) {
$cat_title = $row['cat_title'];
$cat_id = $row['cat_id'];
?>
<input value="<?php echo $cat_title; ?>" type="text" class="form-control" name="cat_title">
<?php
}
}
}

PHP practice function ($result) can't be called

I am doing PHP practice and I am stuck on this part.
My problem is when I do simple math like 1+1 or 1/1 etc. The $result won't display. I am confused about which part of my code is causing the problem. Please enlighten me on my mistakes
Thank you.
<?php
$first_num = $_POST['first_num'];
$second_num = $_POST['second_num'];
$operator = $_POST['operator'];
$result = '';
function cal_result($first_num,$second_num,$operator){
if (is_numeric($first_num) && is_numeric($second_num)) {
switch ($operator) {
case "Add":
$result = $first_num + $second_num;
break;
case "Subtract":
$result = $first_num - $second_num;
break;
case "Multiply":
$result = $first_num * $second_num;
break;
case "Divide":
$result = $first_num / $second_num;
}
return $result;
}
}
?>
<form action="simple_calculator.php" method="post" id="quiz-form">
<p>
<input type="number" name="first_num" id="first_num" required="required" value="<?php cal_result($first_num,$second_num,$operator); ?>" /> <b>First Number</b>
</p>
<p>
<input type="number" name="second_num" id="second_num" required="required" value="<?php cal_result($first_num,$second_num,$operator); ?>" /> <b>Second Number</b>
</p>
<p>
<input readonly="readonly" name="result" value="<?php echo $result; ?>"> <b>Result</b>
</p>
<input type="submit" name="operator" value="Add" />
<input type="submit" name="operator" value="Subtract" />
<input type="submit" name="operator" value="Multiply" />
<input type="submit" name="operator" value="Divide" />
</form>
I think you are confused by the short open tag
if I print
<?=$result;?>
or
<?=cal_result($first_num,$second_num,$operator);?>
this is the same thing like
<?php echo $result;?>
or
<?php echo cal_result($first_num,$second_num,$operator);?>
If you call a function that ´returns´ values, and you want to use them , you must also print them out...
also check out global variables. If you want to use $result outside the function scope you must declare it a global variable.
<?php
$result = '';
$first_num = 0;
$second_num = 0;
$ops = array( "+",
"-",
"×", // HTML : × , ASCII CODE : 158
"÷"); // HTML : ÷ , ASCII CODE : 246
// checking if the first number is what he should be
if ( isset($_POST['first_num']) &&
!empty($_POST['first_num']) &&
is_numeric($_POST['first_num']) )
{
$first_num = $_POST['first_num'];
}
// checking if the second number is what he should be
if ( isset($_POST['second_num']) &&
!empty($_POST['second_num']) &&
is_numeric($_POST['second_num']) )
{
$second_num = $_POST['first_num'];
}
function cal_result($first_num,$second_num,$operator){
// optionally you can assign global
global $result;
// here we prevent injection by acceptint only operators from the ops array
if (isset($_GET['operator']) && in_array($_GET['operator'],$ops)) {
switch ($_GET['operator']) {
case $ops[0]: // first element of array ops is Add
$result = $first_num + $second_num;
// remember this function is just returning the $result
// variable it is not printing it, you will have to assiging
// the function to a variable if you want to use the
return $result;
break;
case $ops[1]: // second element of array ops is Subtract
$result = $first_num - $second_num;
return $result;
break;
case $ops[2]: // third element of array ops is Multiply
$result = $first_num * $second_num;
return $result;
break;
case $ops[3]: // fourth element of array ops is Divide
// divide by zero problem
if($second_num !== 0){
$result = $first_num / $second_num;
}else{
$result = "Err: Div By Zero";
}
return $result;
break;
}
}
}
}
?>
<p>
<!--// now you have 2 possibilities : //-->
<!--// first you can call the global variable $result //-->
<label for="quiz-form"><?=$result;?></label>
<!--// the second possibility is to call the function //-->
<label for="quiz-form"><?=cal_result($first_num,$second_num,$operator);?></label>
<b>Result</b>
</p>
<!-- for post you should also set enctype for security reasons -->
<form action="simple_calculator.php"
method="post"
id="quiz-form"
enctype="application/x-www-form-urlencoded">
<p>
<input type="number"
name="first_num"
id="first_num"
required="required"
value="<?=$first_num;?>" />
<b>First Number</b>
</p>
<p>
<input type="number"
name="second_num"
id="second_num"
required="required"
value="<?=$second_num;?>" />
<b>Second Number</b>
</p>
<input type="submit" name="operator" value="+" alt="Add" />
<input type="submit" name="operator" value="-" alt="Subtract" />
<input type="submit" name="operator" value="×" alt="Multiply" />
<input type="submit" name="operator" value="÷" alt="Divide" />
</form>

ZF2 Ajax call returns all information instead of just the id being sent

I'm trying to select one contract from the dropdown list, but it looks like the Ajax call is returning information for all contracts instead of just the id being sent. Bare in mind that I'm very new to ZF2.
// view.phtml
<script>
function loadContractId(id)
{
$.getJSON('<?php echo $this->basePath();?>/ajax/getId/'+id+'', function(data) {
$("#ctrid").text(data["arr"][0].ctr_id);
$("#ctrspec").text(data["arr"].ctr_spec);
$("#ctrnutype").text(data["arr"].ctr_nu_type);
$("#ctrlocationcity").text(data["arr"].ctr_location_c);
$("#ctrlocationstate").text(data["arr"].ctr_location_s);
$.each(data["arr"], function (index, item) {
console.log(item);
});
});
$("#contact_holder").css('visibility','visible');
}
</script>
<div id="loc_placement_panel" class="p0pup">
<form name="loc_placement_form" method="post" action="<?php echo $this->basePath(); ?>/booking/view/add">
<input type="hidden" name="ph_id" value="<?php echo $ar["ph_id"]; ?>">
<input type="hidden" name="pres_status" value="2">
<input type="hidden" name="ph_name" value="<?php echo $ar["ctct_name"]; ?>">
<!--<input type="hidden" name="addon" value="see below">-->
<strong>Placements</strong><br/><br/>
<label><strong>Contract:</strong></label>
<select name="contactlist" id="contactlist" onchange="loadContractId($('#contactlist').val())">
<?php
foreach ($ctrLT as $row=>$ar_contracts)
{
echo "<option value='".$ar_contracts['ctr_id']."'>";
echo $ar_contracts['ctr_no'];
echo "</option>";
}
?>
</select>
<div id="contact_holder" style="visibility: hidden">
<strong>Ctr id: </strong><span id="ctrid" ></span><br/>
<strong>Spec: </strong><span id="ctrspec" ></span><br/>
<strong>Nurse Type: </strong><span id="ctrnutype" ></span><br/>
<strong>City: </strong><span id="ctrlocationcity" ></span><br/>
<strong>State: </strong><span id="ctrlocationstate" ></span><br/>
</div>
<label><strong>User Name:</strong></label>
<input type="text" name="loc_location" id="loc_location" value="<?php echo $ar["ctct_name"]; ?>" />
<label><strong>$ltcontracts:</strong></label>
<textarea id="txtArea" rows="10" cols="100" name="loc_location" id="loc_location" value=""><?php '<pre>'; print_r($ltcontracts); '</pre>';?></textarea>
<br/><br/>
<!-- <input type="submit" value="Submit" id="loc_placement_submit_btn" name="loc_placement_submit_btn" /> -->
<input type="button" value="Cancel" id="loc_placement_cancel_btn" />
</form>
</div>
// AjaxController.php
// LT contracts
public function getId($id) {
$id = (int) $id;
return $this->getResortObject('retainedResort',$id);
}
// LT contracts
public function getIdAction() {
$result = new \stdClass();
$arr = $this->getContractsTable()->selectLtContracts($id);
$result->code = Response::STATUS_CODE_200;
$result->arr = $arr;
$json = Json::encode($result);
$response = $this->getResponse(); //new Response();
$response->setStatusCode($result->code);
$response->getHeaders()->addHeaders(array('Content-Type'=>'application/json'));
$response->setContent($json);
return $response;
}
// ContractTable.php
I tried also with selected id, ( $select->where('ctr_id = ?', $id); ) but it didn't work.
public function selectLtContracts($id = 0, array $ar = null) {
$this->table='allcontracts';
$select = new Select($this->table);
$select->where->like('ctr_no', '%LT');
$resultSet = $this->selectWith($select);
$ar = array();
if($resultSet)
{
$i=0;
foreach ($resultSet as $row) {
$ar[$i]['ctr_id']=$row->ctr_id;
$ar[$i]['ctr_no']=$row->ctr_no;
$ar[$i]['ctr_spec']=$row->ctr_spec;
$ar[$i]['ctr_nu_type']=$row->ctr_nu_type;
$ar[$i]['ctr_location_c']=$row->ctr_location_c;
$ar[$i]['ctr_location_s']=$row->ctr_location_s;
$ar[$i]['ctr_nurse']=$row->ctr_nurse;
$ar[$i]['ctr_type']=$row->ctr_type;
$ar[$i]['ctr_marketer']=$row->ctr_marketer;
$ar[$i]['ctr_recruiter']=$row->ctr_recruiter;
$i+=1;
}
}
return $ar;
}
This is what I'm getting from my console when I select a single contract from the dropdown list:
Any idea?
Basically I forgot to include in getIdAction() the single 'id' parameter from route:
$id = (int) $this->params()->fromRoute('id', 0);
and in the ContractsTable.php I needed to add equalTo() predicate:
...
if($id!='' && $id > 0)
$where->equalTo('ctr_id', $id);
$select->where($where);
...

PHP Nesting Not Working

My code below doesnt seem to work. ANyone can help with the reason? It checks for the first variable $editID, but the next one '$key' doesnt work.
Every help will be greatly appreciated.
Code below:
<?php
$editID = $_POST['editID'];
if (isset($editID)) {
$key = $_POST['Key'];
if (isset($key)) {
$clientName = $_POST['clientName'];
echo $clientName;
} else {
$owner = $current_user->ID;
global $wpdb;
$sql="SELECT * FROM clients WHERE clientID=$editID";
$clients = $wpdb->get_results($sql);
foreach ($clients as $client)
{
<form role="form" method="POST">
<div class="form-group">
<label>Client Name</label>
<input class="form-control" name="clientName" value="<?php echo $client->clientName;?>" required>
</div>
<input type="hidden" id="Key" name="Key" value="<?php echo $key; ?>">
<button value="submit" type="submit" class="btn btn-default">Update</button>
</form>
<?php
}
}
} else {
echo "Nothing to edit? Please go back.";
}
?>

How to pass a variable from model to controller in codeigniter

How can I pass a variable from the model to the controller?
Here is my model:
public function edititem($id){
$query = $this->db->query('SELECT * FROM tblitem WHERE item_id = "$id"');
foreach ($query->result() as $row){
$name = $row->item_name;
$description = $row->item_description;
$price = $row->item_price;
}
And here is my controller
public function editItem(){
$this->load->helper('form');
$this->load->model('ItemModel');
$this->ItemModel->edititem($this->input->get('id'));
$name = $this->input->post('name');
$description = $this->input->post('description');
$price = $this->input->post('price');
$data['items'] = $this->ItemModel->itemlist();
$this->load->view('item/item_edit',$data);
}
In which when the user clicks "Edit Item", it will populate the form with the selected row.
<form action="<?php echo base_url().'item/edititem' ?> " method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="name" class="form-control" id="name" name="name" placeholder="Name" value="<?php echo set_value('name'); ?>">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" rows="3" name="description"><?php echo set_value('description'); ?></textarea>
</div>
<div class="form-group">
<label class="sr-only" for="price">Amount (in pesos)</label>
<div class="input-group">
<div class="input-group-addon">Php</div>
<input type="text" class="form-control" name="price" id="price" placeholder="Amount" value="<?php echo set_value('price'); ?>">
<div class="input-group-addon">.00</div>
</div>
</div>
<button type="submit" class="btn btn-primary">EDIT ITEM</button>
</form>
If it is from model to controller, You can make an array and store that 3 fields. (I assume there is only single row returned by your query since you are using id as where).
$result = array();
foreach ($query->result() as $row)
{
$result['name'] = $row->item_name;
$result['description'] = $row->item_description;
$result['price'] = $row->item_price;
}
return $result;
You can access it in the controller using:
$data['items']['name'];
$data['items']['description']
$data['items']['price']
Or in your view as
$items['name'];
$items['description'];
$items['price'];
Here your model looks like this
public function edititem($id){
$query = $this->db->query('SELECT * FROM tblitem WHERE item_id = "$id"');
if ($query->num_rows() > 0) {
$row = $query->row_array(); // row_array return single row and result_array return multiple row
return $row['dt'];
And your controller looks like this
public function editItem(){
$this->load->helper('form');
$this->load->model('ItemModel');
$item_details=$this->ItemModel->edititem($this->input->get('id'));
here you use foreach loop
foreach ($item_details as $key=>$value){
//do this in $data array
} //now you can use the specific data to your view.
$this->load->view('item/item_edit',$data);
}
Your Model:
This may useful if your want to return a specific 1 row without using result()
public function edititem($id){
$this->db->select('*');
$this->db->from('tblitem ');
$this->db->where('item_id ',$id);
return $query = $this->db->get()->custom_row_object(0, 'ItemModel');
}
Your Controller: Call the edititem($id) from ItemModel (your model)
public function editItem(){
$item_id=$this->uri->segment(3); //added this
$this->load->helper('form');
$this->load->model('ItemModel');
$item_details=$this->ItemModel->edititem($item_id); //added this
$data['item_name'] = $item_details->name;
$data['item_desc'] = $item_details->description;
$data['item_price'] = $item_details->price;
//now you can use the specific data to your view.
$this->load->view('item/item_edit',$data);
}
In your view, you can use the variable like:
$item_name;
$item_desc;
$item_price;
eg:
<input type="text" name="item_name" value="<?php echo $item_name;?>" />

Categories