pdo connection error - pdo

<?php
$config['db'] = array (
'host' => 'localhost'
'username' => 'root'
'password' => ''
'dbname' => 'phplogin'
);
$db = new PDO("mysql:host={$config['db']['host']};dbname={$config['db']['dbname']}",
$config['db']['username'], $config['db']['password']);
?>
receives error: "Parse error: syntax error, unexpected ''username'' (T_CONSTANT_ENCAPSED_STRING), expecting ')' in C:\webroot\wamp\www\index.php on line 4"
My question is:
Can you highlight or comment on the lines I have to insert my information such as localhost, databasename, table, root, "", etc. Also if you see any changes that need to be made.

When you get errors, you can find the mistake by looking in the error message
The T_CONSTANT_ENCAPSED_STRING parser token error occurs due to an unexpected quote, so all you had to do is look at your code to notice that you don't have commas in the array declaration as stated by Johnny000. You always have to look the error messages and interpret their meaning. That's coding 101 in my opinion.

The error is because you forget to seperate the arrayvalues with ,
Here the right code
<?php
$config['db'] = array (
'host' => 'YOURHOST',
'username' => 'YOURUSERNAME',
'password' => 'YOURPASSWORD',
'dbname' => 'YOURTABLE'
);
$db = new PDO("mysql:host={$config['db']['host']};dbname={$config['db']['dbname']}",
$config['db']['username'], $config['db']['password']);
?>

Related

Auth::attempt() does not return anything

I'm using laravel 4.
This is my Seeder
User::create(array(
'name' => 'Rubber Gajulu',
'username' => 'awesome',
'email' => 'awesome#awe.com',
'password' => Hash::make('awesome'),
));
And this is where I am testing the Auth::attempt() function
Route::get('testlogin',function(){
$userdata = ['email'=> 'awesome#awe.com','password'=> 'awesome'];
echo Auth::attempt($userdata);
if (Auth::attempt($userdata))
echo 'SUCCESS!';
else
echo 'FAILURE!';
});
It just returns FAILURE. The first echo does not return anything.
Your controller code is wrong. It should be this:
Route::get('testlogin',function(){
$userdata = ['email'=> 'awesome#awe.com','password'=> 'awesome'];
if (Auth::attempt($userdata))
echo 'SUCCESS!';
else
echo 'FAILURE!';
});
Otherwise in your current code you are trying to login the user twice, so the second one fails.
Check if logs/laravel.log shows any error on hitting this url.
Share that.
Okay I found my mistake
Thanks to Isabell Knauers answer
My model had
$table->string('password',32)
Data was being truncated to 32 characters. Now I changed it to
$table->string('password',100)
and everything works as intended

Query Builder giving a parameters bound error

I'm using Yii 1.1.15 and am trying to create a query. but when i do i get a no parameters where bound error This is my code below. From the doc it looks like i'm doing everything right.
$user = Yii::app()->db->createCommand()
->select()
->from('ABC')
->where('id=:id0 AND id=:id1 AND id=:id2', array(':id0'=> '07Q00G', ':id1'=>'07Q01A', ':id2'=>'07Q02A'))
->execute();
CDbCommand failed to execute the SQL statement: SQLSTATE[HY093]: Invalid parameter number: no parameters were bound. The SQL statement executed was: SELECT *
FROM `ABC`
WHERE id=:id0 AND id=:id1 AND id=:id2
also when i used ->query() instead of ->execute() it echo's this. and doesnt replace the variables
CDbDataReader Object ( [_statement:CDbDataReader:private] => PDOStatement Object ( [queryString] => SELECT * FROM `ABC` WHERE id=:id0 AND id=:id1 AND id=:id2 ) [_closed:CDbDataReader:private] => [_row:CDbDataReader:private] => [_index:CDbDataReader:private] => -1 [_e:CComponent:private] => [_m:CComponent:private] => )
Any idea what i'm missing here?
Instead of execute() you should do queryAll()
so It should be
$user = Yii::app()->db->createCommand()
->select()
->from('ABC')
->where('id=:id0 AND id=:id1 AND id=:id2', array(':id0'=> '07Q00G', ':id1'=>'07Q01A', ':id2'=>'07Q02A'))
->queryAll();

cakephp see the compiled SQL Query before execution

My query gets the timeout error on each run. Its a pagination with joins.
I want to debug the SQL, but since I get a timeout, I can't see it.
How can I see the compiled SQL Query before execution?
Some cake code:
$this -> paginate = array(
'limit' => '16',
'joins' => array( array(
'table' => 'products',
'alias' => 'Product',
'type' => 'LEFT',
'conditions' => array('ProductModel.id = Product.product_model_id')
)),
'fields' => array(
'COUNT(Product.product_model_id) as Counter',
'ProductModel.name'
),
'conditions' => array(
'ProductModel.category_id' => $category_id,
),
'group' => array('ProductModel.id')
);
First off, set the debug variable to 2 in app/config/config.php.
Then add:
<?php echo $this->element('sql_dump');?>
at the end of your layout. This should actually be commented out in your default cake layout.
You will now be able see all SQL queries that go to the database.
Now copy the query and use the SQL EXPLAIN command (link is for MySQL) over the database to see what the query does in the DBMS. For more on CakePHP debugging check here.
Since your script doesn't even render you can try to get the latest log directly from the datasource with:
function getLastQuery()
{
$dbo = $this->getDatasource();
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
return $lastLog['query'];
}
This needs to be in a model since the getDatasource() function is defined in a model.
Inspect the whole $logs variable and see what's in there.
One more thing you can do is ....
Go to Cake/Model/DataSource/DboSource.php and locate function execute() and print $sql variable.
That should print the sql.
This certainly is not be the cleanest way (as you are changing Cake directory) .. but certainly would be quickest just to debug if something is not working with sql.
Try...
function getLastQuery($model) {
$dbo = $model->getDatasource();
$logData = $dbo->getLog();
$getLog = end($logData['log']);
echo $getLog['query'];
}
Simple way to show all executed query of your given model:
$sqllog = $this->ModelName->getDataSource()->getLog(false, false);
debug($sqllog);
class YourController extends AppController {
function testfunc(){
$this->Model->find('all', $options);
echo 'SQL: '.$this->getLastQuery();
}
function getLastQuery()
{
$dbo = ConnectionManager::getDataSource('default');
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
return $lastLog['query'];
}
}
or you can get all the query by adding following line in to the function execute() in lib/Cake/Model/DataSource.php
Debugger::dump($sql);
set the debug variable to 2 in app/config/config.php.
echo $this->Payment->save();
Out put like =>SQL Query: INSERT INTO photoora_photoorange.payments VALUES (*******)
[insert query][2]
set the debug variable to 2 in app/config/config.php.
And

Insert statement not working using execute(array()) of PDO Extension

$stmt = $conn->prepare("INSERT INTO user VALUES ('',:username,md5(:password),'',1,'','',:email,'',0,0,'',:cover,:dateofbirthYear:dateofbirthMonth:dateofbirthDay,NOW(),:sex,:country)");
$stmt->execute(array(
':username' => $username,
':password' => $password,
':email' => $email,
':cover' => $cover,
':dateofbirthYear' => $dateofbirthYear,
':dateofbirthMonth' => $dateofbirthMonth,
':dateofbirthDay' => $dateofbirthDay,
':sex' => $sex,
':country' => $country
));
For some reason this insert statement is not working. I am very new in PDO so I do not know much about it. What am I doing wrong?
this statment gives me this error :
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens' in /home/manga/public_html/new/register.php:80 Stack trace:
#0 /home/manga/public_html/new/register.php(80): PDOStatement->execute(Array)
#1 {main} thrown in /home/manga/public_html/new/register.php on line 80
You have prepared your query in the wrong way
INSERT INTO user VALUES ('',:username,md5(:password),'',1,'','',:email,'',0,0,'',
:cover,:dateofbirthYear:dateofbirthMonth:dateofbirthDay,NOW(),:sex,:country
// ^ These need to either single or separated
For what you are trying, you can do it this way
//Prepare the date of birth earlier
$dob = $dateofbirthYear.$dateofbirthMonth.$dateofbirthDay;
//Then pass it as a single $variable
$stmt = $conn->prepare("INSERT INTO user VALUES ('',:username,md5(:password),'',1,'','',:email,'',0,0,'',:cover,:dob,NOW(),:sex,:country)");
$stmt->execute(array(
':username' => $username,
':password' => $password,
':email' => $email,
':cover' => $cover,
':dob' => $dob, // <-- Problem solved
':sex' => $sex,
':country' => $country
));
// Then it will execute
The exact error message you have is:
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
This means that the number/names of parameters you have passed (the array() in execute) does not match with the number/names of parameters you have in the prepare() SQL-query.
If you compare that with the other questions that contain SQLSTATE[HY093] you will see that it is often related to code that is large and bad formatted which is hard to read. That makes it hard to count. And then you have an oversight of something and then the error happened.
Just fix it and done, for example you can not make one parameter out of three names:
,:dateofbirthYear:dateofbirthMonth:dateofbirthDay,
Instead just pass one parameter for the birthday:
, :dateofbirth,
You can also make your code a bit more readable:
$stmt = $conn->prepare(
"INSERT INTO user
VALUES (
'', :username, md5(:password), '', 1, '', '', :email, '', 0, 0, '',
:cover, :dateofbirth, NOW(), :sex, :country
)"
);
$stmt->execute(array(
':username' => $username,
':password' => $password,
':email' => $email,
':cover' => $cover,
':dateofbirth' => $dateofbirthYear . $dateofbirthMonth . $dateofbirthDay,
':sex' => $sex,
':country' => $country
));
And then you have a security problem with the password hash:
md5(:password)
Instead do proper password hashing, see the PHP FAQ about Safe Password Hashing.
Corrected prepared query:
$stmt = $conn->prepare("INSERT INTO user VALUES ('',:username,md5(:password),'',1,'','',:email,'',0,0,'',:cover,:dateofbirthYear,:dateofbirthMonth:,dateofbirthDay,NOW(),:sex,:country)");
//:dateofbirthYear,:dateofbirthMonth:,dateofbirthDay place holders are seprated
$stmt->execute(array(
':username' => $username,
':password' => $password,
':email' => $email,
':cover' => $cover,
':dateofbirthYear' => $dateofbirthYear,
':dateofbirthMonth' => $dateofbirthMonth,
':dateofbirthDay' => $dateofbirthDay,
':sex' => $sex,
':country' => $country
));

zend framework 2 autentification using DbTable failure

I have followed the zend instructions for implement my web Authentication using a database table.
It's exactly the same code, but when render the page, the following exceptions appears:
Zend\Authentication\Adapter\Exception\RuntimeException
File:
C:\xampp\htdocs\pfc\vendor\ZF2\library\Zend\Authentication\Adapter\DbTable.php
Mensaje:
The supplied parameters to DbTable failed to produce a valid sql statement, please
check table and column names for validity.
produced by this other:
Zend\Db\Adapter\Exception\InvalidQueryException
File:
C:\xampp\htdocs\pfc\vendor\ZF2\library\Zend\Db\Adapter\Driver\Mysqli\Statement.php
Mensaje:
Statement couldn't be produced with sql: SELECT `users`.*, (CASE WHEN `password` = ?
THEN 1 ELSE 0 END) AS `zend_auth_credential_match` FROM `users` WHERE `mail` = ?
Seems to be that Statement.php can not execute the sql of above, but I send the sql by phpmyadmin replacing the ? for strings and work ok.
I am sure that $dbAdapter works ok also because I have tested it and the columns name are
"mail" and "password".
This in my code, also I put the $dbAdapter test code.
$dbAdapter = new DbAdapter(array( //This DbAdapter Work ok sure!!
'driver' => 'Mysqli',
'database' => 'securedraw',
'username' => 'root',
'password' => ''
));
$fp = function($name) use ($dbAdapter) { return $dbAdapter->driver->formatParameterName($name);};
$sql = 'SELECT * FROM ' . $qi('users') . ' WHERE id = ' . $fp('id');
$statement = $dbAdapter->query($sql);
$parameters = array('id' => 1);
$sqlResult = $statement->execute($parameters);
$row = $sqlResult->current();
$mail = $row['mail'];
$password = $row['password']; //until here test $dbAdapter exitly!!
//Start the auth proccess!!
$authAdapter = new AuthDbTableAdapter($dbAdapter);
$authAdapter->setTableName('users')
->setIdentityColumn('mail')
->setCredentialColumn('password');
$authAdapter->setIdentity('josep')
->setCredential('josep');
$authResult = $authAdapter->authenticate(); //This is the fail method!!!
After more research on the subject, I discovered that if changed the driver of the dbAdapter to pdo_mysql, authenticate method works ok.
The problem is I don't want use PDO because the SGBD won't change in the future.
Somebody know because happen this?
This may seems old but I was able to solve this error. This error is caused from you MySQL version.
This one works for me. All you need to do is to remove the driver_options from your db setup, this code is usually located at your global.php or .local.php from your Config file.
Change FROM:
'db' => array(
'driver' => 'Pdo_Mysql',
'dsn' => 'mysql:dbname=dbName;host=localhost',
'username' => 'dbUser',
'password' => 'dbPass',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
),
TO
'db' => array(
'driver' => 'Pdo_Mysql',
'dsn' => 'mysql:dbname=dbName;host=localhost',
'username' => 'dbUser',
'password' => 'dbPass',
),
Thank you. This solution solved my problem.