I am execute flowing query .
$query = $busdetails
->find('list',['keyField' => 'id','valueField' => 'bus_name'])
->where(['status'=>1,'is_approved'=>1]);
pr($query->toArray());
It works fine if some results found but if no results found then it shows an error Cannot convert value to bool issue. Thanks
update cakephp library file.--
cakephp/src/Database/Type/BoolType.php
Change
if ($value === true || $value === false)
by
if ($value === true || $value === false || is_null($value))
From more detail --
https://github.com/cakephp/cakephp/issues/7583
Related
Cleaning up some old code on server ... getting an error on line 228 ... pulling out snippet ... the while ($i < $num_cols) is the line with the error AH01215 "Use of uninitialized value $num_cols in numeric lt(<) at"
I added in the my and attempted checking for not defined, the code works, but I would like to get the code working without web server error log messages.
I have several of these "Use of uninitialized" errors, hoping seeing how to fix this will help me with the rest.
$sth = $h->prepare($sel);
if ($sth == 0) {
print "<XMLRSSQLERROR>ERROR: $DBI::errstr</XMLRSSQLERROR>\n";
exit;
}
if (!$sth->execute) {
print "<XMLRSSQLERROR>ERROR: $DBI::errstr</XMLRSSQLERROR>\n";
exit;
}
my $num_cols = $sth->{NUM_OF_FIELDS};
#Start the XML output
#Start the RS section and add the table name
print "<RS>\n";
print "$table\n";
#Start the SCHEMA section
print "<SCHEMA>\n";
my #columns = #{$sth->{NAME}};
my #type = #{$sth->{TYPE}};
my $i = 0;
while ($i < $num_cols) {
print "<$columns[$i]>";
if (($type[$i] == 1) or ($type[$i] == 12) or ($type[$i] == -1)) {
print "char";
} elsif (($type[$i] == 4) or ($type[$i] == 5) or ($type[$i] == -6)) {
print "int";
} elsif (($type[$i] == 2) or ($type[$i] == 6) or ($type[$i] == 7) or ($type[$i] == 8)) {
print "float";
} elsif (($type[$i] == 11) or ($type[$i] == 10) or ($type[$i] == 9)) {
print "datetime";
} else {
print "$type[$i]"
}
print "</$columns[$i]>\n";
$i += 1;
}
#End the SCHEMA section
print "</SCHEMA>\n";
The defined-or can set a default value:
my $num_cols = $sth->{NUM_OF_FIELDS} // 0;
There are various other tricks, but most of those are different ways to checking values are what you expect before you use them.
But, without seeing your SQL statements or knowing which DBI driver you are using, there's not much we can do to guess. I'd definitely want to know why that value has undef.
As others have said, it seems weird that $sth->{NUM_OF_FIELDS} is undefined. I'd definitely want to find out what's going on there.
But it looks to me like you don't need that at all. It's only there because you're using a while loop that should probably be written as a foreach loop. You could remove:
my $num_cols = $sth->{NUM_OF_FIELDS};
And replace:
while ($i < $num_cols) {
with:
foreach my $i (0 .. $#columns) {
In following code, I'm trying to create a new category (name = 'To be deleted') and then I want to delete it.
first part of the code working fine and I can see new record in the database every time I run the unit test
but I'm having a problem with recode deletion. what's wrong with my code
public function testCategoryDeletion()
{
$user = \App\User::find(1);
//dd($user->name);
$category = \App\Category::create(['name' => 'To be deleted']);
//dd($category->id);
$response = $this->actingAs($user, 'api')
->json('DELETE', "/api/category/{$category->id}")
->assertStatus(200)->assertJson([
'status' => true,
'message' => 'Category Deleted',
]);
}
Test case output
PS C:\xampp\htdocs\Chathura\Vue_Laravel_API> ./vendor/bin/phpunit
PHPUnit 7.5.7 by Sebastian Bergmann and contributors.
. . . . . . . 7 / 7 (100%)
Time: 1.53 minutes, Memory: 18.00 MB
OK (7 tests, 65 assertions)
PS C:\xampp\htdocs\Chathura\Vue_Laravel_API>
In database, recode is created but not deleted,
I fixed the controller as follows and now its working,
public function destroy(Category $category)
{
$status = $category->delete();
return response()->json([
'status' => $status,
'message' => $status ? 'Category Deleted' : 'Error Deleting Category'
]);
}
API routes
Route::group(['middleware' => 'auth:api'], function(){
Route::resource('/task', 'TaskController');
Route::resource('/category', 'CategoryController');
Route::get('/category/{category}/tasks', 'CategoryController#tasks');
});
I'm writing a regex pattern to split MySQL CREATE statements into column definition arrays. So far, it works great for everything aside from SET columns. Here's the process:
$lines = explode("\n", $create_sql);
foreach ($lines as $line) {
$line = str_replace('NOT NULL', 'NOT_NULL', $line);
$pattern = '/`(.*)`[\s]*([^\s]*)[\s]*(NOT_NULL|NULL)[\s]*(.*),/';
$search = preg_match($pattern, $line, $matches);
if ($search !== false && count($matches) === 5) {
$columns[$matches[1]] = array(
'type' => $matches[2],
'null' => $matches[3] === 'NULL',
'extra' => $matches[4],
);
}
}
This process works great on a column with a definition like this:
`id` INT(11) NOT NULL AUTO_INCREMENT,
...but fails on SET columns. How can I best accommodate for the extra quotes and parentheses in this line?
`platform` SET('iOS', 'Android') NULL DEFAULT NULL,
To summarize, I need to integrate a pattern to match SET('one', 'two', n) in a string.
First just let slightly modify your pattern expression, first for readability (\s* instead of [\s]*), then to ensure working even with lowercase statements :
$pattern = '/`(.*)`\s*([^\s]*)\s*(NOT_NULL|NULL)\s*(.*),/i';
Then, to answer your question, prepare the pattern depending on a SET is present or not in the line:
$sub_pattern = stripos($line, ' SET(') ?
'SET\([^\)]*\)\s*[^\s]*'
: '[^\s]*';
$pattern = '/`(.*)`\s*(' . $sub_pattern . ')\s*(NOT_NULL|NULL)\s*(.*),/i';
Note that, however, this code is not secured against syntax errors in the source lines.
// Input: $sql
$match = '(
([^(),]+?| # no parens, or contains ():
[^(),]+?
\( [^)]+? \) # (123), (enum...), etc
[^(),]*?
) \s*(,\s*|$) # separator or terminator
)';
preg_match('/(CREATE\s+TABLE.*?\()(.*)(\)[^()]*(;|$))/si', $sql, $m);
list($x, $pre, $list, $post, $z) = $m;
$list = trim($list);
$list = preg_replace('/\s+/', ' ', $list);
$list = preg_replace("/$match/sx", "$1
", $list);
$list = trim($list);
// Output:
echo "<pre>
$pre
$list
$post\n</pre>\n";
Notes:
Certain quoted strings will fail to parse correctly.
I think all cases of parentheses work ok.
You will still need to parse each element in $list[], which should be one per column.
I need to get a list of the courses in moodle and count their respective sections as the number of topics and display in the form
[{"id":"1","name":"mathematics","topic_count":"20"},
{"id":"3","name":"Geography","topic_count":"5"},].
I tried the following
//initialize an array to hold the results
$result = array("id" =>0,"name" =>" ","topic_count" =>0);
$list = "[";
$courses = $DB->get_records_sql("SELECT id,shortname FROM mdl_course WHERE id >?",array(1)) or die ("Error in executing query 1");
foreach ($courses as $course){
$id = $course->id;
$null = "NULL";
$count = $DB->get_records_select("course_sections","course = ? AND name <> ?",array("course" =>$id, "name" => $null)) or die ("Error in executing query 2");
$result["id"] = $course->id;
$result["name"] = $course->shortname;
$result["topic_count"]= sizeof($count);
//append to list
$list .='{"id":"'.$result['id'].'","name":"'.$result['name'].'","topic_count":"'.$result['topic_count'].'"},';
}
$list .="]";
echo $list;
With this code I get the output
"Error in executing query 2"
But when instead of the $id I put a specific number say 2 I get the expected result with a constant count of sections (for course = 2 of course). Please help me out maybe I'm missing a very small point! I tried the get_records_sql but didn't work.
You are using an associative array for query 2
Either use
$count = $DB->get_records_select("course_sections","course = ? AND name <> ?",array($id, $null)) or die ("Error in executing query 2");
or
$count = $DB->get_records_select("course_sections","course = :course AND name <> :name",array("course" =>$id, "name" => $null)) or die ("Error in executing query 2");
UPDATE:
You can also use this to count the records
$DB->count_records_select('course_sections', "course = :course AND name <> :name",array("course" =>$id, "name" => $null));
http://docs.moodle.org/dev/Data_manipulation_API#Seeing_how_many_records_match_a_given_criterion
In SQL you check for NULL values with 'IS NOT NULL', rather than '<> "NULL"'.
You might also find it a lot safer to generate an array of objects, then use the function 'json_encode' to generate the final output.
e.g.
$list = array();
foreach ($courses as $course) {
$info = new stdClass();
$info->id = $course->id;
$info->name = $course->shortname;
$info->topic_count = $DB->count_records_select('course_sections', 'course = ? AND name IS NOT NULL', array($course->id));
$list[] = $info;
}
echo json_encode($list);
try this code.
you can change the $condition as you want.
it helps.
global $DB;
$table = 'course';
$condition = 'visible= "1" AND id!= "1" '; //is put into the where clause
$courses = $DB->get_records_select($table,$condition);
foreach($courses as $course){
echo '
'.$course->id.' '.userdate($course->startdate).' '.$course->fullname.' '.$course->summary.'
';
}
function random()
{
$anketadb = $this->load->database('anketa',TRUE);
$br = $anketadb->count_all_results('anketadata');
$nmb = mt_rand(1,$br);
if ($nmb != 1){
$nmb = $nmb - 1;
}
$count = $anketadb->get('anketadata', 1, $nmb);
return $count;
}
Why this code when i echo it in View returns ERROR:
A PHP Error was encountered
Severity: 4096
Message: Object of class CI_DB_mysqli_result could not be converted to
string
Filename: ankete/rezultatiankete.php
Line Number: 52
You should have shown us more code (controller, view etc), anyways, in your example you are using
return $count;
in this case $count; is an object and to echo it's fields you have to loop in your view like
foreach ($count->result() as $row)
{
echo $row->fieldname; // rerplace the fieldname with a real field/column name of your database
}
so if you are trying to echo the $count then you are making a mistake, it's an object, read more here.
echo doesnot work for objects use print_r(returned value) to output objects,arrays
to fetch a random column use SELECT * FROM table ORDER BY RAND() LIMIT 0,1;