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

$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
));

Related

Update Post status when post is expire

I want to update post status when a post is expiring.
I have saved expiry date in the WordPress post meta (post_price_plan_expiration_date).
I know how to get an expired post with wp_query,
But I want to use SQL query to update post status.
$todayDate = strtotime(date('m/d/Y h:i:s'));
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'featured_post',
'value' => '1',
'compare' => '=='
),
array(
'key' => 'post_price_plan_expiration_date',
'value' => $todayDate,
'compare' => '<='
),
)
);
$wp_query = new WP_Query($args);
print_r($wp_query);
This code returns me correct posts which I need, But I need to write the same query in SQL, And run that with wp_schedule_event
Any help???
You can always do the following out of a WP_Query
$wp_query = new WP_Query( $args );
echo $results->request;
Which should display the generated SQL Query.
Hope this helps.

Get images by custom field

I'm trying to display all images that have a certain custom field from the types plugin set to true. It would also work to filter them by post_content or post_excerpt but none of my attempts have worked so far.
<?
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_content' => 'foo',
'numberposts' => -1
);
?>
<? print_r(get_posts($args)); ?>
This get's all images allthough only one has the post_content foo. My attempt to use WP_Query failed miserably as well.
Any help is appreciated!
WP_Query method :
$args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'meta_query' => array(
array(
'key' => 'color',
'value' => 'blue',
'compare' => 'LIKE',
),
),
);
$query = new WP_Query( $args );
I am presuming that the reason why you failed with WP_Query is due to the following condition.
Codex states : The default WP_Query sets 'post_status'=>'publish', but attachments default to 'post_status'=>'inherit' so you'll need to explicitly set post_status to 'inherit' or 'any' as well.
http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters
get_posts method :
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'meta_key' => 'custom-field',
'meta_value' => 'custom value',
'numberposts' => -1
);
print_r(get_posts($args));
The only draw back with this method is that the meta_value needs to exactly match what was entered in the custom field. If you still like to use get_posts then use the meta_query as shown in WP_Query example above.

cakephp use "OR" "AND" in find query

i am new in cakephp so i dont know i to how write this query in cakephp . at times now i have this query
$count = $this->User->find('count', array(
'conditions' => array('User.mobileNo' => $mobileNo)));
this query is checking that if the mobile number in database is equal to the one the user has given .. i want to add another condition which is
mobile number is equal to the one the user has given the mobile number and email is equal to the one the user has given the email for example
$count = $this->User->find('count', array(
'conditions' => array('User.mobileNo' => $mobileNo))) And
'conditions' => array('User.email' => $email)))
You need only add to your conditions array:
$count = $this->User->find('count', array(
'conditions' => array(
'User.mobileNo' => $mobileNo,
'User.email' => $email
)
));
There are many examples like this in the documentation e.g..
$conditions = array("Post.title" => "This is a post", "Post.author_id" => 1);
// Example usage with a model:
$this->Post->find('first', array('conditions' => $conditions));

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.

Strange issue with Zend_Validate_Identical?

I had write the following code in my Zend Form:
$newpassword = new Zend_Form_Element_Password('newpassword');
$newpassword->setLabel("Enter your New Password :")
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator(
'NotEmpty',
TRUE,
array('messages' => array(
'isEmpty' => 'Please enter new password.'
)
)
)
->addValidator(
'Alnum',
TRUE,
array('messages' => array(
'alnumInvalid' => 'Please enter a valid new password.',
'notAlnum' => 'Please enter a valid new password.',
'alnumStringEmpty' => 'Please enter a valid new password.'
)
)
)
->addValidator('StringLength', false, array(4, 25))
->getValidator('StringLength')->setMessage("Should be 4-25 characters long.");
$retypepassword = new Zend_Form_Element_Password('retypepassword');
$retypepassword->setLabel("Retype-Password :")
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator(
'NotEmpty',
TRUE,
array('messages' => array(
'isEmpty' => 'Please enter confirm password.'
)
)
)
->addValidator(
new Zend_Validate_Identical('newpassword'),
TRUE,
array('messages' => array(
'notSame' => 'New password and confirm password are not matching. They must be same.',
'missingToken' => 'New password and confirm password are not matching. They must be same.'
)
)
)
->addValidator('StringLength', false, array(4, 25))
->getValidator('StringLength')->setMessage("Should be 4-25 characters long.");
As you can see that I had override the error messages for Zend_Validate_Identical i.e. for notSame and missignToken, but still the form is showing the default error message i.e. "The two given tokens do not match"
Can anyone please help me.
Thanks In Advance...
The $options parameter to Zend_Form_Element::addValidator gets ignored completely if you pass it a validator object (which you're doing by passing new Zend_Validate_Identical).
Instead, you want to do something closer to the way you've added your other validators:
$this->addValidator(
'Identical',
TRUE,
array('token' => 'newpassword',
'messages' => array(
'notSame' => 'New password and confirm password are not matching. They must be same.',
'missingToken' => 'New password and confirm password are not matching. They must be same.'
)
)
);