Error updating table in codeigniter when there is single quote - php

please help me get through with this.
Everytime I update data from database there is '\' added before the single quote.
For example I have an input that has a value=I'm ok after updating there is '\' will be added.
Sample code from my Model
function update_questionnaire() {
$Cid1 = $this->input->post('Cid1');
$Cid2 = $this->input->post('Cid2');
$Cdata = array(
array(
'choices_id' => $Cid1,
'questionnaire_id_fk' => $Qid,
'choices' => $choice1
),
array(
'choices_id' => $Cid2,
'questionnaire_id_fk' => $Qid,
'choices' => $choice2
)
);
$question = $this->db->escape_like_str($this->input->post('question', TRUE));
$this->db->update_batch('choices', $Cdata, 'choices_id');
}
And sample code from my Controller
$this->form_validation->set_rules('choice1', 'Choice 1', 'required|trim');
$this->form_validation->set_rules('choice2', 'Choice 2', 'required|trim');
And sample code from my View
<?php
$i=0;
foreach ($query as $row):
$i++;
echo '<input type="text" name="choice' . $i . '" id="choice_' . $row->choices_id . '" value="' . trim_slashes($row->choices) . '" class="form-control"/>';
endforeach;
?>

Related

How to get foreach loop with item array into a input form

I have to following foreach loop
$data = array(
"success" => false,
"results" => array()
);
foreach ($cart->get_contents() as $item) {
$data['items'][] = array(
'description' => urlencode($item['name']),
'amount' => urlencode($item['price']),
'quantity' => urlencode($item['qty'])
);
}
$data['success'] = true;
Now I would like to for the following for each item
<input type="hidden" name="' . $field . '" value="' . htmlentities($value) . '">
where the $field would be the item description, and the htmlentities($value) would be the corresponding value from the loop.
Any help welcome as I am not sure where to start, sorry if this is very obvios
I think (if I understand you) that you can achieve this like:
$data = [
'success' => false,
'items' => [] // Probably itemsm not results??
];
foreach ($cart->get_contents() as $item) {
$data['items'][] = array(
'description' => urlencode($item['name']),
'amount' => urlencode($item['price']),
'quantity' => urlencode($item['qty'])
);
}
$data['success'] = true;
foreach ($data['items'] as $item) {
echo "<input type='hidden' name='" . $item['description'] . "'' value='" . htmlentities($item['amount']) . "'>";
}
I also updated the code a little.

How to transform a collection into a custom key/value array with nested arrays

I need to return my collection into an array that Chatfuel, and specifically Messenger, understands. When calling User::get(), I get a collection of all the users, but I need to map it out to the JSON array that Chatfuel expects.
I've previously (when I was using raw PHP and no framework), done it like so:
<?php
$det = array();
while ($row = mysqli_fetch_assoc($results)) {
$row_array['title'] = $row['book-title'] . " | " . $row['edition'] . " Edition";
$row_array['image_url'] = $row['image-url'];
$row_array['subtitle'] = $row['author'];
if (!empty($_SESSION['loggedinuniid'])) {
$urllink = "https://example.com/textbook/?isbn=" . $row['isbn'] . '&uni=' . $_SESSION['loggedinuniid'] . '&submit';
} else {
$urllink = "https://example.com/textbook/?isbn=" . $row['isbn'] . '&submit';
}
$row_array['item_url'] = $urllink;
if ($row['rrs'] == 0) {
$row_array['buttons'] = array(array('type' => 'web_url', 'url' => $urllink, 'title' => 'See Textbook'));
} else {
$row_array['buttons'] = array(array('type' => 'web_url', 'url' => $urllink . '#selling', 'title' => 'Buy Textbook (' . $row['rrs'] . ')'));
}
array_push($det, $row_array);
}
$row_array['title'] = "Find Textbooks on example";
$row_array['subtitle'] = "Search for textbooks sold by your classmates at uni!";
$row_array['image_url'] = "";
$urllink = "https://example.com/";
$row_array['item_url'] = $urllink;
$row_array['buttons'] = array(array('type' => 'web_url', 'url' => $urllink, 'title' => 'See All Textbooks'));
array_push($det, $row_array);
$final = array(
'messages' => array(
array("attachment" => array(
"type" => "template", "payload" => array(
"template_type" => "generic", "elements" => $det,
),
),
),
array("text" => "Hope this helps! You can also always search on example.com!"),
),
);
$post_data = json_encode($final);
exit($post_data);
And, while it got the job done, it isn't really readable or clean.
What's the best way to take an existing collection, and map it out to a custom key/value array I need?

why this query repeat the first and the last name in this code

when i run this query i have the result in the right why but name and the father name repeated in all lines . i want it just one time . i put for example the 1773 id number to test it .
<?
$query = mysql_query("
SELECT *
FROM students,grades,subjects
WHERE
students.id_students = grades.id_students AND
grades.id_subjects = subjects.id_subjects AND
students.id_students = 1773 ;
");
while ($row = mysql_fetch_assoc($query)
){
$id_students = $row['id_students'];
$firstname = $row['firstname'];
$surename = $row['surename'];
$father = $row['father'];
$marks = $row['marks'];
$class = $row['class'];
$name = $row['name'];
echo "$firstname" . "$surename";
echo "$marks" ." " . "$name" ;
echo "<br>";
echo "$class";
}
?>
Use just one table in FROM clause and for others use JOIN.
SELECT s.*,
g.*,
su.*
FROM students s
JOIN grades g
ON g.id_students = s.id_students
JOIN subjects su
ON su.id_subjects = g.id_subjects
WHERE s.id_students = 1773
Due to the previous answer which will be deleted, this should be what you need. $data array is the same as you get from database.
<?php
$data = array(
0 => array(
'id_students' => 1,
'firstname' => 'Fuad',
'surename' => 'Bro',
'father' => 'fathers name',
'marks' => 30,
'class' => 1,
'name' => 'itd'
),
1 => array(
'id_students' => 1,
'firstname' => 'Fuad',
'surename' => 'Bro',
'father' => 'fathers name',
'marks' => 120,
'class' => 1,
'name' => 'biography'
),
2 => array(
'id_students' => 1,
'firstname' => 'Fuad',
'surename' => 'Bro',
'father' => 'fathers name',
'marks' => 120,
'class' => 1,
'name' => 'informatic'
)
);
$last_name = '';
foreach ($data as $row) {
if ($row['firstname'] != $last_name) {
echo '<b>' . $row['firstname'] . ' ' . $row['surename'] . ' (father: ' . $row['father'] . ')</b><br>';
}
echo 'class: ' . $row['class'] . '<br>';
echo 'subject name: ' . $row['name'] . '<br>';
echo 'marks: ' . $row['marks'] . '<br><br>';
$last_name = $row['firstname'];
}
/*
output:
Fuad Bro (father: fathers name) -- name and father's name just once
class: 1
subject name: itd
marks: 30
class: 1
subject name: biography
marks: 120
class: 1
subject name: informatic
marks: 120
*/
?>

How to echo checkbox group with multidimentional array

I need help to get the data from my checkbox-group with multidimensional array options to reflect in my post page(single.php code). Radio type is working well but the checkbox-group type is not. I added on the bottom the sample code found in my single.php for the radio type which query the data to my post page for your reference.
Here's the array from my metabox.php code:
<?php
// array
$prefix = 'wtf_';
$meta_box = array( 'id' => 'site',
'title' => 'Program Details',
'page' => 'post',
'context' => 'normal',
'priority' => 'high',
'fields' => array(
array('name' => 'Principal Return',
'desc' => 'Principal Return After Expiry or Not',
'id' => $prefix . 'principal',
'type' => 'radio',
'options' => array(
array('name' => ' Yes ', 'value' => 'Yes-after expiry'),
array('name' => ' No ', 'value' => 'No-included on the interest')
)
),
array(
'name' => 'Compounding',
'desc' => 'Choose if compounding is allowed or not',
'id' => $prefix . 'compounding',
'type' => 'radio',
'options' => array(
array('name' => ' Yes ', 'value' => 'Allowed'),
array('name' => ' No ', 'value' => 'Not Allowed'),
array('name' => ' Re-purchase', 'value' => 'Yes thru re-purchase')
)
),
array ('name' => 'Payment Processors',
'desc' => 'Payment Processsor Accepted',
'id' => $prefix.'processors',
'type' => 'checkbox_group',
'options' => array(
array('label' => ' Liberty Reserve ', 'value' =>'LR'),
array('label' => ' SolidTrustPay ', 'value' =>'STP'),
array('label' => ' EgoPay ', 'value' =>'EgoPay'),
array('label' => ' Perfect Money ', 'value' =>'PM'),
array('label' => ' Payza ', 'value' =>'Payza'),
array('label' => ' PayPal ', 'value' =>'PayPal'),
array('label' => ' Bankwire ', 'value' =>'Bankwire')
))))
// Callback function to show fields in meta box
function mytheme_show_box() {
global $meta_box, $post;
// Use nonce for verification
echo '<input type="hidden" name="mytheme_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';
echo '<table class="form-table">';
foreach ($meta_box['fields'] as $field) {
// get current post meta data
$meta = get_post_meta($post->ID, $field['id'], true);
echo '<tr>',
'<th style="width:20%"><label for="', $field['id'], '">', $field['name'], '</label></th>',
'<td>';
switch ($field['type']) {
case 'text':
echo $statetemt;
break;
case 'textarea':
echo $statetemt;
break;
case 'select':
echo $statetemt;
break;
case 'radio':
foreach ($field['options'] as $option) {
echo $statetemt; }
break;
case 'checkbox':
foreach ($field['options'] as $option) {
echo $statetemt;}
break;
case 'checkbox_group':
foreach ($field['options'] as $option) {
echo '<input type="checkbox" value="'.$option['value'].'" name="'.$field['id'].'[]" id="'.$option['value'].'"',$meta && in_array($option['value'], $meta) ? ' checked="checked"' : '',' />',$option['label']; }
echo '<br /><span class="description">'.$field['desc'].'</span>';
break;
}
//From my single.php code <<<<=================
<div class="sdinfo"><strong>Principal Return</strong>:<span><?php $principal = get_post_meta(get_the_ID(), 'wtf_principal', true);
if (isset($principal[0])) {
echo $principal ;
} else if (isset($principal[1])) {
$principal = get_post_meta(get_the_ID(), 'wtf_principal', true);
echo $principal;
} else {_e('Not Available');} ?></span></div>
<div class="sdinfo"><strong>Program Started</strong>:<span> <?php $started = get_post_meta(get_the_ID(), 'wtf_started', true); if (isset($started[0])) { echo $started;
} else {_e('Not Available');} ?></span></div>
<div class="sdinfo"><strong>Compounding</strong>:<span>
<?php $compounding = get_post_meta(get_the_ID(), 'wtf_compounding', true);
if (isset($compounding[0])) {
echo $compounding ;
} else if (isset($compounding[1])) {
$compounding = get_post_meta(get_the_ID(), 'wtf_compounding', true);
echo $compounding;
} else if (isset($compounding[2])) {
$compounding = get_post_meta(get_the_ID(), 'wtf_compounding', true);
echo $compounding;
} else {_e('Not Available');} ?></span></div>
?>
This give me an output from post meta like this:
admin screenshot
This is the output from my post page. :
post page screenshot
Please help!.. I am not a programmer hope you can share me an answer in much details.Thank you in advance!
All what you need is point an array using var_dump($array) to check where and what data you need from arrays fields.
Second you need to get foreach() function. For example you want grab an array of data:
'priority' => 'high', should be as example:
echo $meta_box["priority"] which will result as value of array: high
If you are not sure and not familiar with array use as simple:
foreach ($meta_box as $arr)
{
var_dump($arr);
#then play and manipulate how to grab a fields a data:
foreach ($arr["fields"][""] as $fa)
{
var_dump($fa["name"]);
var_dump($fa["desc"]);
var_dump($fa["desc"]);
}
#...
}
Learn how to grab via var_dump() if you unsure with array of data.
Payment Processors LR STP EgoP
echo $meta_box["fields"][""]["name"];
Than you need grab a data of an array:
foreach ($meta_box["fields"][""]["options"] as $options)
{
foreach ($options as $options_key)
{
foreach ($options_key as $opt_val)
{
$result .= ' '.$opt_val;
}
}
}

can I add array to where clause to update_batch in codeigniter

I am using codeigniter update_batch function.
I want to pass an array as the third parameter (where clause) to update_batch.
$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name 2' ,
'date' => 'My date 2'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name 2' ,
'date' => 'Another date 2'
)
);
Instead of this:
$this->db->update_batch('mytable', $data, 'title');
I want to do this:
$this->db->update_batch('mytable', $data, array('title','name'));
So multiple where conditions added.
Is this possible?
You could do this by creating your method for batch update in your model Test_model for example because Codeigniter does not supports multiple where condition in native update_batch, so example below:
public function update_batch_custom($table_name, $data, $indexes) {
if (empty($data) || empty($indexes)){
return 'Data or indexes must not be empty';
}
$db = $this->load->database('test_db', TRUE);
$sql = 'UPDATE ' . $table_name . ' SET ' . "\n";
//columns on which is done actual update
$columns = [];
foreach ($data[0] as $key => $value) {
if (!in_array($key, $indexes)){
$columns[] = $key;
}
}
/*
* forming WHEN .. THEN sql parts and WHERE condition
*/
$parts = [];
$where = [];
foreach ($data as $row) {
foreach ($columns as $column) {
$sql_part = ' WHEN (';
foreach ($indexes as $index) {
$sql_part .= $index . '= \''.$row[$index] . '\' AND ';
$where[$index][] = $row[$index];
}
$sql_part = substr($sql_part, 0, -4);
$sql_part .= ') THEN \'' . $row[$column] . '\'';
$parts[$column][] = $sql_part;
}
}
/*
* connecting WHEN .. THEN parts for each column to be updated
*/
foreach ($columns as $column) {
$sql .= $column .'= CASE ';
foreach ($parts[$column] as $sql_part) {
$sql .= $sql_part;
}
$sql .= ' ELSE ' . $column . ' END,';
}
/*
* adding WHERE part
*/
$sql = substr($sql, 0, -1);
$sql .= ' WHERE ';
foreach ($indexes as $index) {
if ( count($where[$index]) > 0){
$unique_where = array_unique($where[$index]);
$sql .= $index . ' IN (\'' . join('\',\'', $unique_where) . '\') AND ';
}
}
$sql = substr($sql, 0, -4);
$sql .= ';';
return $db->query($sql);
}
You can use below code to update your data:
$this->db->update("TableName",[dataarray],[where condition array]);
This update_batch function does not allow WHERE parameter, but you can try splitting it before calling the function.
Try this:
$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name 2' ,
'date' => 'My date 2'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name 2' ,
'date' => 'Another date 2'
)
);
$this->db->where('name','My Name 2');
$this->db->update_batch('mytable', $data, 'title');
Controller:
$chunk1 = array_chunk($data,100);
for($i=0;$i < count($chunk1);$i++) {
$this->upload_model->update_data($chunk1[$i],'My Name 2');
}
Model:
public function update_data($data='',$name=''){
$this->db->where('name',$name);
$this->db->update_batch('mytable', $data, 'title');
}
Remember, my WHERE parameter is a static value.
You could always do this:
$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name 2' ,
'date' => 'My date 2'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name 2' ,
'date' => 'Another date 2'
)
);
$this->db->where(array('title' => 'title', 'name' => 'name'));
$this->db->update_batch('mytable', $data);
Not tested.
UPDATE This lacks the required where parameter in update_batch().

Categories