Search field - laravel - forms

My search in laravel doesn't work. I'm trying everything, but I've got error: Class 'Bike' not found.
Index.blade:
{{Form::open(array('url'=>'/'))}}
{{Form::text('keyword', null, array('placeholder'=>'Miasto'))}}
{{Form::submit('search')}}
{{Form::close()}}
route:
Route::post('/',function(){
$keyword = Input::get('keyword');
$bikes = Bike::where('city', 'LIKE', '%'.$keyword.'%')->get();
var_dump('search results');
foreach($bikes as $bike){
var_dump($bike->city);
}

You are not returning anything.
return var_dump($bike->city);

Related

php8.1 - Deprecated Functionality: DateTime()

We use the following code that worked perfectly on php7.4, but we get a deprecated error on php8.1. But how can we succesfully rewrite this for php8.1?
Error:
Deprecated Functionality: DateTime::__construct(): Passing null to parameter #1 ($datetime) of type string is deprecated
Current code:
$today = new \DateTime();$orderdate = new \DateTime($orders->getCreatedAt());
<?php if($orderdate->diff($today)->days > 14):?>
<?php endif;?>
You can no longer do this:
new \DateTime(null);
In your exact use case, I think that PHP has highlighted a bug in your code. If the order does not have a created at date, you'll populate the variable with the date/time when the script runs, which may not be what you want:
var_dump(new \DateTime('1985-12-31 15:00:00'));
var_dump(new \DateTime(''));
var_dump(new \DateTime(null));
object(DateTime)#1 (3) {
["date"]=>
string(26) "1985-12-31 15:00:00.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(16) "Europe/Amsterdam"
}
object(DateTime)#1 (3) {
["date"]=>
string(26) "2022-09-19 12:28:23.003960"
["timezone_type"]=>
int(3)
["timezone"]=>
string(16) "Europe/Amsterdam"
}
Deprecated: DateTime::__construct(): Passing null to parameter #1 ($datetime) of type string is deprecated in /in/67OFM on line 5
object(DateTime)#1 (3) {
["date"]=>
string(26) "2022-09-19 12:28:23.003987"
["timezone_type"]=>
int(3)
["timezone"]=>
string(16) "Europe/Amsterdam"
}
Demo
If you want to use DB information:
$orderdate = $orders->getCreatedAt()
? new \DateTime($orders->getCreatedAt())
: null;
If you want to default to "now", make it explicit so nobody wonders whether it's intentional:
$orderdate = $orders->getCreatedAt()
? new \DateTime($orders->getCreatedAt())
: new \DateTime();
Last but not least... Analyse if it makes sense from the business logic standpoint to have orders with no creation date. What does that mean?

Zend Expressive Route with optional parameter

I want use a route to get the complete collection and, if available, a filtered collection.
so my route:
$app->get("/companies", \App\Handler\CompanyPageHandler::class, 'companies');
My Handler for this route:
use App\Entity\Company;
use App\Entity\ExposeableCollection;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
class CompanyPageHandler extends AbstractHandler
{
public function handle(ServerRequestInterface $request): ResponseInterface
{
$categories = new ExposeableCollection();
foreach (['test', 'test1', 'test3'] as $name) {
$category = new Company();
$category->setName($name);
$categories->addToCollection($category);
}
return $this->publish($categories);
}
}
When getting this route /companies, i get the expected collection
[{"name":"test"},{"name":"test1"},{"name":"test3"}]
So now i change the route
$app->get("/companies[/:search]", \App\Handler\CompanyPageHandler::class, 'companies');
It's all fine when i'm browsing to /companies.
But if i try the optional parameter /companies/test1 then i got an error
Cannot GET http://localhost:8080/companies/test1
my composer require section:
"require": {
"php": "^7.1",
"zendframework/zend-component-installer": "^2.1.1",
"zendframework/zend-config-aggregator": "^1.0",
"zendframework/zend-diactoros": "^1.7.1 || ^2.0",
"zendframework/zend-expressive": "^3.0.1",
"zendframework/zend-expressive-helpers": "^5.0",
"zendframework/zend-stdlib": "^3.1",
"zendframework/zend-servicemanager": "^3.3",
"zendframework/zend-expressive-fastroute": "^3.0"
},
In Zend Framework 2 and Symfony4 this route definition works fine. So im confused.
Why my optional parameter doesn't work?
That's because you are using https://github.com/nikic/FastRoute router and correct syntax would be:
$app->get("/companies[/{search}]", \App\Handler\CompanyPageHandler::class, 'companies');
or be more strict and validate search param something like this:
$app->get("/companies[/{search:[\w\d]+}]", \App\Handler\CompanyPageHandler::class, 'companies');

Mongodb '$where' query using javascript regex

I am trying to reproduce the REPLACE function in sql on mongodb.
My collection 'log' has this data in the 'text' field.
[01]ABC0007[0d0a]BB BABLOXC[0d0a]067989 PLPXBNS[0d0a02]BBR OIC002 L5U0/P AMD KAP 041800 T1200AND 2+00[0d0a0b03]
All I'm trying to do is remove the '[..]' using regex (javascript) and use contains('PLPXBNSBBR') like this so that the expression return true per the javadocs in mongo documentation.
This query below successfully works and returns the matching rows.
db.log.find({"$where":"return this.message.replace(new RegExp('0d0a02'),'').contains('PLPXBNS[]BBR') "});
However, I would need to remove the '[..]' and match like this PLPXBNSBBR.
These are the ones I tried unsuccessfully
db.log.find({"$where" : " return this.message.replace( new
RegExp('\[.*?\]', 'g'), '' ).contains('PLPXBNSBBR') " });
db.log.find({"$where" : " return this.message.replace( new
RegExp('/[(.*?)]', 'g'), '' ).contains('PLPXBNSBBR') " });
db.log.find({"$where" : " return this.message.replace( new
RegExp('//[.*//]'), '' ).contains('PLPXBNSBBR') " });
db.log.find({"$where" : " return this.message.replace( new
RegExp('[.*?]'), '' ).contains('PLPXBNSBBR') " });
From the earlier discussion it appears that if I can pass the pattern as /[[^]]+]/g, it should strip the [..] but it is not doing that and not returning the matching rows.
Okay, I was able to use chaining replace successfully to get my desired results.

Magento 2 - error creating db table from custom schema

I'm trying to create a custom module for Magento 2 and I've got to the point of defining the schema in the /Setup/InstallSchema.php
When running 'php bin/magento setup:upgrade' I get the error:
Call to undefined function Test/Connector/Setup/getConnection()
The module is enabled and correctly showing in the config file. The schema file I'm trying to run is:
<?php
namespace Test\Connector\Setup;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Ddl\Table;
class InstallSchema implements InstallSchemaInterface
{
public function install(SchemaSetupInterface $setup, ModuleContextInterface
$context) {
$installer = $setup;
$installer->startSetup();
$tableName = $installer->getTable('test_connector_settings');
if ($installer->getConnection()->isTableExists($tableName) != true) {
$table = $installer->getConnection()
->newTable($installer->getTable('ipos_connector_settings'))
->addColumn('id', Table::TYPE_SMALLINT, null, ['identity'=> true, 'nullable'=>false, 'primary'=>true], 'ID')
->addColumn('api_url', Table::TYPE_TEXT, 255, ['nullable'=>true], 'API URL')
->addColumn('api_user', Table::TYPE_TEXT, 100, ['nullable'=>false], 'API User Name')
->addColumn('api_password', Table::TYPE_TEXT, 100, ['nullable'=>false], 'API Password');
$installer-getConnection()->createTable($table);
}
$installer->endSetup();
}
}
Thanks in advance,
Please change this line
$installer-getConnection()->createTable($table); // your code line.
With
$installer->getConnection()->createTable($table);

MYSQLi PHP connect

Is the following a valid mysqli php connect insert statement?
if($mysql_query = $conn->query("INSERT INTO users (username,password,question,securityanswer) VALUES ('$uname','$upass','$selectquestion','$answer')"))
{
?>
<script>alert('successfully registered ');</script>
<?php
}
else
{
?>
<script>alert('error while registering you...');</script>
<?php
}
}
However I am getting error as "error while registering you..."
Thanks
Issue is resolved. There was an issue with the "user_id" column primary key which was being updated duplicate(0 value) with this error "Duplicate entry '0' for key 'PRIMARY'. Upon updating user_id column with auto increment in phpmyadmin, the INSERT query got updated successfully.
Using the below code to check for errors helped.
die(mysqli_error($conn));
A simple example:
<?php
//Create the connection
$con = mysqli_connect("HostName","UserName","password","DBName") or die("Some error occurred during connection " . mysqli_error($con));
// Write query
$strSQL = "SELECT username FROM MyTable";
// Execute the query.
$query = mysqli_query($con, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo $result["username"]."
";
}
// Close the connection
mysqli_close($con);
?>
Can you paste the whole block with connection statement?
Otherwise SQL statement looks fine. Excepct you should escape inputs to MySQL
if($mysql_query = $conn->query("INSERT INTO users (username,password,question,securityanswer) VALUES ('$uname','$upass','$selectquestion','$answer')"))
Why using if($mysql_query = $conn->query ?
better
if($conn->query("INSERT INTO users (username,password,question,securityanswer) VALUES ('$uname','$upass','$selectquestion','$answer')") === TRUE)