I want to pass comma separated string to IN clause. My controller code is as:-
$batchpost = $this->input->post('batch');//print_r($batch);
$batch_id = '';
for($i=0;$i<count($batchpost);$i++ ) {
$batch_id = $batch_id . $batchpost[$i] . ',';
}
$batch_string = rtrim($batch_id, ',');
$batch = str_replace(",", ",", $batch_string) ;
$list = $this->admin_model->get_attendance_datatables($batch);
Here $batchpost will return array value, and I want to convert it to a comma separated string and pass to the model.
My model code is as:-
$this->db->select('offline_student.*,batch.batch_name,offline_course.course');
$this->db->from($this->table8);
$this->db->join('offline_course', 'offline_course.id = offline_student.course', 'left');
$this->db->join('batch', 'batch.id = offline_student.batch', 'left');
$this->db->where('offline_student.status', 'Active');
$this->db->where_in('batch.id', $batch);
$this->db->order_by('offline_student.id', 'asc');
Suppose in a row for batch column having two value(2,3)in database, if I pass only '2' or '2,3' to model, query will return my result, but when i pass only 3, It's not showing that record.
Remove the following lines:
$batch_id = '';
for($i=0;$i<count($batchpost);$i++ ) {
$batch_id = $batch_id . $batchpost[$i] . ',';
}
$batch_string = rtrim($batch_id, ',');
$batch = str_replace(",", ",", $batch_string) ;
...and make it like this:
$batchpost = $this->input->post('batch');//print_r($batch);
$list = $this->admin_model->get_attendance_datatables($batchpost);
you don't need to convert $batchpost to comma separated string, because where_in() method expects an array on it's second param.
See the docs of where_in(), here https://www.codeigniter.com/userguide3/database/query_builder.html#looking-for-specific-data
Related
So the code below gets a name from a db(which is a string) and it outputs with "" and a comma.Well it was suppose to, but for some reason it only adds the quotation marks and not the commas.I need it to add the commas too.Thank for you help.
<?php
$sl = "SELECT _eName FROM vrt;";
$ret = mysqli_query($conn, $sl);
$resultck = mysqli_num_fields($ret);
if ($resultck > 0){
while ($row = mysqli_fetch_assoc(($ret))){
$b = $row['e_Name'];
$temp = array($b,);
$req = "'" . implode ( "' , '", $temp ) . "'";
echo $req;
}}
?>
You're echoing each row, your not building out $temp with all rows then imploding, so it would only contain the one item.
Instead, simply do:
<?php
$conn = ...
$result = mysqli_query($conn, "SELECT e_Name FROM vrt");
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
$data = array_map(fn($row) => $row['e_Name'], $data);
echo "'" . implode ("' , '", $data) . "'";
?>
implode joins array elements with a string. Your variable $temp contains only a single element, so there is nothing to join and the element itself is returned.
I have a code in php it takes a well formatted string such as 'field,operator,value' and produces a WHERE statement to MySQL database query.
if the two fields names below end with the same characters such as '*id' such as 'id' and 'classid' it produces strange behavior. such as the following:
$where = $_GET['where'];
$tokens = multiexplode(array("^", "~", "(", ")"), $where);
$where = str_replace("^", " AND ", $where);
foreach ($tokens as $item) {
if (!empty($item)) {
$where = str_replace($item, getOperand($item), $where);
}
}
echo 'WHERE '.$where;
function multiexplode($delimiters, $string)
{
$unifydelimters = str_replace($delimiters, $delimiters[0], $string);
$conditions = explode($delimiters[0], $unifydelimters);
return $conditions;
}
function getOperand($item)
{
$extokens = explode (",", $item);
switch (trim($extokens[1])) {
case 'eq':
return trim($extokens[0]) . " = '" . trim($extokens[2]) . "' ";
break;
default:
return "";
break;
}
}
tested with :
http://localhost/test/test.php?where=id,eq,1^classid,eq,19
ALways show: id = '1' AND classid='1' 9
Not: id = '1' AND classid='19'
But if any other field ends differently from the other such as:
http://localhost/test/test.php?where=id,eq,1^class,eq,19
It correctly shows: id = '1' AND class='19'
Any idea why this is happening??
Thanks,
The problem is that when you search for the first expression id,eq,1 for the replacement in the string
id,eq,1^classid,eq,19
You will find two positions:
id,eq,1^classid,eq,19
^ ^
id,eq,1 |
id,eq,1
This means you will do two replacements, even though you wanted only replace one.
To solve this problem you don't need to work with the original input string $where. Instead you can use the already create array in $tokens and change the individual array elements. You can use array_map() to do that, like this:
$changed = array_map('getOperand', $tokens);
Then you can put the array together to a string with ' AND ' as the separator:
$result = implode(' AND ', $changed);
This will finally generate the following result:
id = '1' AND classid = '19'
Keep in mind that you should use prepared statements to avoid SQL injections, see How can I prevent SQL injection in PHP?
this is my code :
<?php
$sss = "SELECT tanggal_awal FROM libur_nasional GROUP BY tanggal_awal ASC";
$qqq = mysqli_query($konek,$sss);
$arr = array();
while ( $tam = mysqli_fetch_array($qqq)) {
$date = $tam['tanggal_awal'];
$reformat_date = date("n-j-Y", strtotime($date));
$arr[] = $reformat_date;
}
$array_date = implode(",", $arr);
?>
> output : 8-9-2018,8-10-2018,8-17-2018
> output i want to is : "8-9-2018", "8-10-2018", "8-17-2018"
could someone help me to get the output i want, thank before.
You can make your code a bit shorter:
$sss = "SELECT tanggal_awal FROM libur_nasional GROUP BY tanggal_awal ASC";
$qqq = mysqli_query($konek,$sss);
while ( $tam = mysqli_fetch_array($qqq)) {
$arr[] = date("n-j-Y", strtotime($tam['tanggal_awal']));
}
$array_date = '"' . implode('", ', $arr) . '"';
In php you don't need to declare an array before pushing values to it.
Your $date variable is not needed as it's just a copy of the $tam['tanggal_awal'] value.
$reformat_date is also not needed as you can place it in the array directly.
The imploding is what is placed between the items, by having ", there you just need to add a " at each end of the string.
$arr=['8-9-2018','8-10-2018','8-17-2018'];
$array_date = '"'.implode('", "', $arr) . '"';
echo $array_date;
Output ---> "8-9-2018", "8-10-2018", "8-17-2018"
Try to implode your array like this.
I have a string and I would want to get the values/fields from it. However, the values are # separated.
Also, from one copy to the next it is comma separated.
As shown below;
$transaction = "
[2018-01-10 12:50:07.822#SAMUEL#TITUS],
[20120605152613#KEN#NAUGH],
[20120705152645#JOHHY#BRAVO]";
I need to loop through this string getting the values separated by the # for one record the to the next record separated by a comma.
The order of the fields is [TIME#FIRST_NAME#SECOND_NAME].
I can't think of a way to get this done.
Anyone?
Use explode to parse string into array
<?php
$transaction = "[2018-01-10 12:50:07.822#SAMUEL#TITUS],[20120605152613#KEN#NAUGH],[20120705152645#JOHHY#BRAVO]";
$parsed = explode(",", $transaction);
foreach($parsed as $val){
$val = explode("#", $val);
$first_name = $val[1];
$last_name = str_replace("]", '', $val[2]);
echo $first_name." ".$last_name."<br>"; // get firstname & lastname
}
?>
You can use the following solution using explode and array_map:
$transaction = "
[2018-01-10 12:50:07.822#SAMUEL#TITUS],
[20120605152613#KEN#NAUGH],
[20120705152645#JOHHY#BRAVO]";
//normalize the string and remove the unnecessary chars.
$transaction = str_replace(['[', ']', "\n"], '', $transaction);
//get all the rows as array.
$rows = explode(',', $transaction);
//create the columns in rows.
$row_arr = array_map(function ($row) {
return explode('#', $row);
}, $rows);
//info of the first row.
echo $row_arr[0][0]; // time
echo $row_arr[0][1]; // firstname
echo $row_arr[0][2]; // lastname
//run through the rows to output.
foreach ($row_arr as $row_item) {
echo 'Time: '.$row_item[0].', Firstname: '.$row_item[1].', Lastname: '.$row_item[2]."<br>";
}
demo: https://ideone.com/3uYcSw
I have a string like this,
sidePanel[]=1&sidePanel[]=2&sidePanel[]=4
And if I need to add another value to the string I do this:
$sidePanel = explode('&', $_SESSION['sidePanel']);
array_push($sidePanel, 'sidePanel[]=3');
$sidePanel = implode('&', $sidePanel);
Which returns this:
sidePanel[]=1&sidePanel[]=2&sidePanel[]=4&sidePanel[]3
Now how can I make it so that it will always insert after the array 'sidePanel[]=2' when I explode it at &?
I do not want it in numerical order although this example will return it in numerical order, as the string can change to be in any order.
I cannot use array_splice as I understand this uses the key of the array, and as the position of sidePanel[]=2 can change it will not always be the same.
You can indeed use array_splice, but you have to find the position of your insertion point first:
$sidePanelArr = explode( '&', $_SESSION['sidePanel'] );
// find the position of 'sidePanel[]=2' in array
$p = array_search( 'sidePanel[]=2', $sidePanelArr );
// insert after it
array_splice( $sidePanelArr, p+1, 0, 'sidePanel[]=3' );
$sidePanelSt = implode( '&', $sidePanelArr );
You could also splice the string right into your original string without exploding and re-imploding.
The function substr_replace() is your friend:
$sidePanelSt = $_SESSION['sidePanel'];
// find the position of 'sidePanel[]=2' in string
// (adding '&' to the search string makes sure that 'sidePanel[]=2' does not match 'sidePanel[]=22')
$p = strpos( $sidePanelSt.'&', 'sidePanel[]=2&') + strlen('sidePanel[]=2' );
// insert after it (incl. leading '&')
$sidePanelSt = substr_replace( $sidePanelSt , '&sidePanel[]=3' , $p, 0 );
See : http://codepad.org/5AOXcHPk
<?php
$str = "sidePanel[]=1&sidePanel[]=2&sidePanel[]=4";
$sidePanelArr = explode('&', $str);
$newVal = 'sidePanel[]=3';
$insertAt = 2 ;
$newArr = array_merge(array_slice($sidePanelArr, 0,$insertAt),
array($newVal),
array_slice($sidePanelArr,$insertAt)
);
$sidePanel = implode('&', $newArr);
echo $sidePanel,PHP_EOL ;
?>
You could turn it into an array using parse_str and locate the value you want to insert it after:
// Turn it into an array
$url = parse_str($_SESSION['sidePanel']));
// What value do we want to insert it after
$insert_after = 2;
// The value you want to insert
$sidePanel = 3;
// Find the position of $insert_after
$offset = array_search($insert_after, $url['sidePanel']);
// Slice the array up (based on the value)
$url['sidePanel'] = array_merge(array_slice($url['sidePanel'], 0, $offset),
array($sidePanel),
array_slice($url['sidePanel'], $offset));
// Turn it back into a string
echo http_build_query($url);