SQL/Laravel is not quoting text fields when building a query - mysql

UPDATED
I am new to Laravel and tried to test this demo https://github.com/laravel-json-api/laravel on my local Mac after installing ddev, Docker and MAMP. The problem is that the code (that I didn't write, I just downloaded without making any changes) is executing a SELECT trying to find a user with that email address but, apparently, Laravel builds the SQL sentence removing the quotes when adding the content for the field "email".
This is the error message that I get on the browser:
SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from `users` where `email` = frankie#example.com limit 1)
I use MySQL 5.7.32 and the DB collation is utf8_general_ci.
The error show in the browser when the exception is caught is:
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php
* #param array $bindings
* #param \Closure $callback
* #return mixed
*
* #throws \Illuminate\Database\QueryException
*/
protected function runQueryCallback($query, $bindings, Closure $callback)
{
// To execute the statement, we'll simply call the callback, which will actually
// run the SQL against the PDO connection. Then we can calculate the time it
// took to execute and log the query SQL, bindings and time in our memory.
try {
$result = $callback($query, $bindings);
}
// If an exception occurs when attempting to run a query, we'll format the error
// message to include the bindings with SQL, which will make this exception a
// lot more helpful to the developer instead of just the database's errors.
catch (Exception $e) {
throw new QueryException(
$query, $this->prepareBindings($bindings), $e
);
}
return $result;
}
/**
* Log a query in the connection's query log.
*
* #param string $query
* #param array $bindings
* #param float|null $time
* #return void
*/
public function logQuery($query, $bindings, $time = null)
{
$this->event(new QueryExecuted($query, $bindings, $time, $this));
if ($this->loggingQueries) {
*Arguments
"SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from `users` where `email` = frankie#example.com limit 1)"*
This is the database.php config for the demo project:
database.php demo:
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '8889'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
],
MySQL listens on port 8889
Anyone has experienced a similar situation?
Thanks

Your problem is not the quotes, there's something wrong with the SQL server internally.
Regarding the quotes:
When using the standard eloquent methods, query parameters will be sent to the server using prepared statements. This is very save and the no need four adding quotes. Internally the server handles the parameters correctly.
Whenever an error occurred, the server outputs the pure, unquoted data of received from the prepared statement. This indeed is a bit misleading, but it's not an error.

I closed this question as it is not related to how Laravel builds the SQL sentence. It is about an error trying to connect to MySQL from any PHP code on MAMP. See my new question here Error: 200 Connection refused on PHP connecting to MySQL running on MAMP

Such an error may occur when accidentaly we are passing in fields that don't match our Model's fields

Related

Laravel + MySQL + SSL-Mode - SQLSTATE[HY000] [3159]

On Linode I've setup a MySQL Database Cluster and an Ubuntu server with Apache and PHP 8.1.
When I SSH onto the Ubuntu server I'm able to connect to the cluster:
mysql --host=lin-xxx-mysql-primary-private.servers.linodedb.net --user=xxx --password --ssl-mode=required
However, when I run php artisan migrate I get the following error:
Illuminate\Database\QueryException
SQLSTATE[HY000] [3159] Connections using insecure transport are prohibited while --require_secure_transport=ON. (SQL: select * from information_schema.tables where table_schema = xxxrch and table_name = migrations and table_type = 'BASE TABLE')
at vendor/laravel/framework/src/Illuminate/Database/Connection.php:712
708▕ // If an exception occurs when attempting to run a query, we'll format the error
709▕ // message to include the bindings with SQL, which will make this exception a
710▕ // lot more helpful to the developer instead of just the database's errors.
711▕ catch (Exception $e) {
➜ 712▕ throw new QueryException(
713▕ $query, $this->prepareBindings($bindings), $e
714▕ );
715▕ }
716▕ }
+33 vendor frames
34 artisan:37
Illuminate\Foundation\Console\Kernel::handle()
I have not setup any certificates/pem files which other answers reference, but it still works from the mysqlclient.
What would I add to my .env to config\database.php to get this working?
Here's how I addressed this:
Download the cert from the Linode dashboard.
Place it in resources\certificates
In config/database.php I added:
'sslmode' => env('DB_SSLMODE', 'prefer'),
'options' => extension_loaded('pdo_mysql') && env('APP_ENV') !== 'testing' && env('APP_ENV') !== 'local' ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => resource_path('certificates/certificate.crt'),
PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT => true,
]) : [],
One thing that's important to note is that this will not work for phpunit tests.
This answer was helpful: https://stackoverflow.com/a/70468831/1343140

Use of undefined constant SIGKILL - assumed 'SIGKILL' in Laravel 5.7 queue

I'm getting this error "Use of undefined constant SIGKILL - assumed 'SIGKILL'" from my AJAX request, that starts this artisan command ->
Artisan::call('queue:work', [
'connection' => 'database',
'--memory' => '700',
'--tries' => '1',
'--timeout' => '35000',
'--queue' => 'updates'
]);
I'm using Laravel 5.7 as framework for application.
Jobs are managed from database, configuration ->
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 18000,
],
Problem appeared recently.. That is weird, because troubles wasn't here before and all this "system" worked just fine. Now worker get some jobs done just fine, but then it drops to error, and writes to table "failed_jobs" in DB this ->
ErrorException: PDOStatement::execute(): MySQL server has gone away in /srv/migration-xxxxxx-xxxx-xxxxxx/www/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458
As DB I'm using Microsoft Azure MySQL DB. Microsoft specialist after consultation find nothing .. server is working correctly. Queries are just fine, not that big to fail.
Please help, don't know what to do, or what is wrong...

CakePHP returns ?? when querying MySQL for Chinese Characters

We started adding Chinese language support to our application. Our DB Charset is set to UTF8 and I can successfully query from MySQL CLI and see the word in Chinese characters
However, when I try to use CakePHP query method "findAll", the value is returned as ?? instead of the Chinese characters
Our DB config in database.php looks like this:
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => true,
'host' => 'localhost',
'login' => 'root',
'password' => '******',
'database' => '******',
'prefix' => '******',
'encoding' => 'utf8'
);
Also we have this line set in core.php:
Configure::write('App.encoding', 'UTF-8');
We don't have any views set for this, we are using REST APIs so we are mainly just doing an "echo" in the Controller method for whatever response we get from the DB.
I also tried to create a test file and write this code in it:
<?php echo '基本' ?>
And it worked fine.
Any suggestions on how to get this to work?
Turned out that I needed to install php-mbstring which wasn't installed
Once I installed it and restarted apache, it worked like a charm

Laravel failing to connect to DB after 4.2 upgrade

I just upgraded my Laravel install from 4.1.(something) to 4.2.7 using the steps recommended here: http://laravel.com/docs/upgrade
Now I'm getting this error on every page:
PDOException (2002)
SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '' (111)
MySQL is not running locally, but it's not supposed to be. I don't have any configuration for connecting to local MySQL, my development SQL server is remote. Why is it trying to connect to local?
Is there some config change that isn't mentioned in the upgrade guide? Everything was peachy in 4.1.
From my app/config/database.php file:
'default' => 'mysql',
...
'connections' => array(
'mysql' => array(
'driver' => 'mysql',
'host' => 'myrealdb.us-east-1.rds.amazonaws.com',
'database' => 'myrealdbname',
'username' => 'myrealuser',
'password' => 'myrealpass',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'database_port' => '3306',
'unix_socket' => '',
),
...
);
I tried php artisan clear-compiled and php artisan dump-autoload just in case. No effect.
Edit: I submitted a fix for this that has been merged into the 4.2 branch. You shouldn't have to worry about this error anymore.
I got it! This appears to be a change in the way Laravel uses the database configuration, I hope this answer helps others.
The short version is: if your connection is configured like mine (in the question), delete the unix_socket entry from the array.
Previously, I always copied and edited the default entries in the connections array, leaving in the unix_socket parameter as empty. Apparently now there's a check that assumes if unix_socket is present, it should use a socket DSN string. The empty string in my config passed the check. You can see how this happens in /vendor/laravel/framework/src/Illuminate/Database/Connectors/MySqlConnector.php. The functions getDsn, getSocketDsn, and getHostDsn tell the story.
Pasted because this will eventually change:
protected function getDsn(array $config)
{
return isset($config['unix_socket']) ? $this->getSocketDsn($config) : $this->getHostDsn($config);
}
...
protected function getSocketDsn(array $config)
{
extract($config);
return "mysql:unix_socket={$config['unix_socket']};dbname={$database}";
}
...
protected function getHostDsn(array $config)
{
extract($config);
return isset($config['port'])
? "mysql:host={$host};port={$port};dbname={$database}"
: "mysql:host={$host};dbname={$database}";
}

Kohana - Database_Exception [ 2 ]: mysql_connect() 2

I am trying to setup my database config as demonstrated here: http://kowsercse.com/2011/09/04/kohana-tutorial-beginners/
I have cut and pasted the database.php with my mysql credentials. I then get an error which I fixed by renaming the file to Database.php. the next issue is that my credentials don't change no matter what I put in.
The error shows:
Database_Exception [ 2 ]: mysql_connect() [function.mysql-connect]: Access denied for user 'ivanh'#'localhost' (using password: NO)
MODPATH/database/classes/Kohana/Database/MySQL.php [ 67 ]
62 catch (Exception $e)
63 {
64 // No connection exists
65 $this->_connection = NULL;
66
67 throw new Database_Exception(':error',
68 array(':error' => $e->getMessage()),
69 $e->getCode());
70 }
71
72 // \xFF is a better delimiter, but the PHP driver uses underscore
So no matter what I insert, username, host and password values do not change.
My code in Database.php is then copied from: http://kohanaframework.org/3.3/guide/database/config
firstly with my own database values then after as is. With no luck.
Other info: I'm creating this on a shared unix host.
Kohana 3.1.4: Database_Exception [ 2 ]: mysql_connect(): Access denied seems like a similar issue without a resolution.
Any help would be great, thanks.
Try These Steps:
Step 1:
Go to bootstrap.php
path- kohana\application\bootstrap.php
Un-comment the below line for database access
'database' => MODPATH.'database', // Database access
Step 2:
Go to Your config folder,
create the database.php file if not created, with below codes by giving your MySql credential
Path: kohana\application\config\database.php
Notes: First create a database in your Mysql
If the problem is not solved check your MySql settings too..there may be a error
<?php defined('SYSPATH') OR die('No direct access allowed.');
return array
(
'default' =>
array
(
'type' => 'MySQL',
'connection' => array(
/**
* The following options are available for MySQL:
*
* string hostname server hostname, or socket
* string database database name
* string username database username
* string password database password
* boolean persistent use persistent connections?
* array variables system variables as "key => value" pairs
*
* Ports and sockets may be appended to the hostname.
*/
'hostname' => 'localhost',
'database' => 'CHANGE YOUR DATABASE NAME HERE',
'username' => 'CHANGE YOUR USER NAME HERE',
'password' => 'CHANGE YOUR PASSWORD HERE',
'persistent' => FALSE,
),
'table_prefix' => '',
'charset' => 'utf8',
),
'remote' => array(
'type' => 'MySQL',
'connection' => array(
/**
* The following options are available for PDO:
*
* string dsn Data Source Name
* string username database username
* string password database password
* boolean persistent use persistent connections?
*/
'dsn' => 'mysql:host=localhost;dbname=CHANGE YOUR DATABASE NAME HERE',
'username' => 'CHANGE YOUR USER NAME HERE',
'password' => 'CHANGE YOUR PASSWORD HERE',
'persistent' => FALSE,
),
/**
* The following extra options are available for PDO:
*
* string identifier set the escaping identifier
*/
'table_prefix' => '',
'charset' => 'utf8',
'caching' => FALSE,
),
);
I am going to make the following assumptions:
You are consequently writing "Database.php" because the file in APPPATH/config containing the code you copied does indeed start with a capital letter.
You haven't changed the config reader.
Database::instance() will request a config array from the Kohana::$config if none is supplied. Config_File::load() will then loop through all found /config/database.php's found in APPPATH, enabled modules and SYSPATH.
Unix filesystems are case sensitive, notice the lowercase 'd' Kohana is looking for versus your uppercase 'D'.
If you did name it 'database.php' and not 'Database.php', click on 'Environment' and then 'Included files' on the error page and make sure it is included. If it's not, do some backtracking and try to find out when things stop behaving as they should, followed by why.
Edit: I don't know how I missed the "renamed it to Database.php" part, but that did not fix anything.