I have come across this Error I've not seen before:
Message: SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters
Referring to the following code (have simplified the function for ease of reading):
if ($frm->isValid($this->_getAllParams()) || !count($frm->getMessages())) //error points to this line of an array
{
//set session with id of user
$session = new Zend_Session_Namespace('rg');
$session->userid = $this->getRequest()->getPost('id');
//update the user
$mdl->createClient($this->_getAllParams());
//add to log - do in model
$this->_redirect('/.../...');
}
6 C:\xampp\htdocs\portal-gep-2\library\Null\Validate\Db\NoRecordExists.php(7): Zend_Validate_Db_NoRecordExists->isValid('7505020152089')
class Null_Validate_Db_NoRecordExists extends Zend_Validate_Db_NoRecordExists
{
public function isValid($value)
{
$response = parent::isValid($value);//this line
if(!$response){
$this->_messages =
array(self::ERROR_RECORD_FOUND=> "Please correct this error before continuing <a href='/data-control/idnum/id/$value'>Correct Issue</a>");
}
return $response;
}
}
The form in question has a constructor of the form:
public function __construct($formState = 'createlocal', $currentTask = null)
based on whether the form is updating an existing record or a new record it will make use of a custom validator: Null_Validate_Db_NoRecordExists.
In the specific case you talk of the form is using a Db_NoRecordExists on an existing record and hence we whould like to exclude a specific record (the current one) using one of the constructor parameters in this case: $currentTask.
$currenctTask may be an array and the validator may make use of an array variable while ensuring the Record does not exist (in the where clause). However the variable is not parsed when initially constucting the form.
Hence check that $currentTask contains what it needs to contain. The error is of your own making.
Related
Description: I have a site. I just want to keep track of a suspicious request and possible barn them only if needed. I just started to implement that feature. I have all the records of IP Addresses, but I'm not sure how to increment their visit count each time - they visit.
Goal: To increment visit_count attribute each time user visit a site
In my visitors table, I have an ip attribute
I want to check for an existing first before, I perform the saving, and other logics, but I'm just a little stuck here.
How do I check if the value already exists in the database using Laravel ?
Any hints on this will be much appreciated !
I've tried
Model : Visitor.php
class Visitor extends Model {
protected $table = 'visitors';
//Validation Rules and Validator Function
public static function validator($input, $id = ''){
$rules = array(
'ip' =>'unique:visitors,ip,'.$id,
);
return Validator::make($input,$rules);
}
}
Controller : Visitor.php
// Check for existing
$validator = Visitor::validator($ip);
if ($validator->fails()) {
$ip = Visitor::where('ip', '=', $ip)->firstOrFail();
$id = $ip['attributes']['id']; //<------ Not sure if this is a proper way
if($ip){
$visitor = Visitor::findOrFail($id);
$visitor->visit_count = $visitor->visit_count + 1 ;
$visitor->save();
}
} else {
$visitor = new Visitor;
$visitor->ip = $ip;
$visitor->visit_count = $visitor->visit_count + 1 ;
$visitor->save();
}
Result
I keep getting
Argument 1 passed to Illuminate\Validation\Factory::make() must be of the type array, string given
I believe, it from this line here $validator = Visitor::validator($ip);
The error message kind of gives it away. The Validator expects the values and the rules to be two separate arrays, each with keys denoting the columns name that needs to be validated. You have that for the rules, but not for the values being checked. This will fix your error:
return Validator::make(['ip' => $input], $rules);
I've been busy trying to create my own framework (to become more experienced in this area), and stumbled on an error I couldn't fix by searching google... wow...
I want to get data from a database, placed in an object / class. I've done it before, in a different way I learned at school, but I wanted to tweak it and make it more dynamic so I could use it in my framework.
The problem I stumbled on is the following:
SQLSTATE[HY000]: General error: could not call class constructor on line 96
This is the function in my database class:
public function getObject($query, $classRootPath)
{
try {
//Check if slashes are double already and make them if not
if(!strpos($classRootPath, "\\\\")) {
$classRootPath = str_replace("\\","\\\\",$classRootPath);
}
$statement = $this->pdo->prepare($query);
$statement->execute(\PDO::FETCH_CLASS, "Campers\\Camper"); // I want this path to be $classRootPath once it is working with this dummy data
return $statement->fetchAll();
// return $this->pdo->query($query)->fetchAll(\PDO::FETCH_CLASS, "Campers\\Camper");
} catch (\PDOException $e) {
throw new \Exception("DB receive object failed: " . $e->getMessage());
}
}
This function is nested in Database and the class is called Database / Database.php
The following class is nested in Campers and is called Camper.php
class Camper {
public $ID, $date, $camperID;
public function __construct($ID, $date, $camperID)
{
$this->ID = $ID;
$this->date = $date;
$this->camperID = $camperID;
}
}
The only reason I can think of this is not working, is that the call "Campers\\Camper" is calling on top of Database, but I don't know how to escape that. I tried with ..\ but I got errors back, and this is the closest I can get. Here it can find the class though, but it can't find the constructor of Camper...
I've tested if my db class / connection works, so that's not the fault.
The structure of my table matches my Campers class constructor.
From the PSR-4 spec:
The terminating class name corresponds to a file name ending in .php. The file name MUST match the case of the terminating class name.
You likely can't instantiate that Camper class as-is anyway. PSR-4 expects your filename to match the class. It should be located in framework/Campers/Camper.php.
This error implies more than been unable to call the constructor, it is also used to indicate than an error occurred while calling it.
In my case, an Exception was been thrown inside de constructor. If you don't print/log the stacktrace, you could easily miss it.
Enjoy!
:)
I had the same issue in at least 3 cases.
Case 1: You select something from the database that can contain a NULL value.
SELECT name FROM tableX;
In that case I do the select in that way:
SELECT IFNULL(name,'') AS name FROM tableX;
where name is a field in your class.
Case 2: You select something that is not a field in your class
class Example {
public string $name = '';
}
Then the following query will fail as id is not declared in your class
SELECT id, name FROM tableX;
case3:
your field in the class isn't initialised
class Example {
public string $name;
}
SELECT name FROM tableX;
can be solved by either initialise the field
class Example {
public string $name = '';
}
or using a constructor to declare it
BR
I have a model in Yii that contains an array of another model type. I am then trying to validate that no duplicate emails are filled out in a form, where you can fill out for n number of persons at the same time.
My current approach is to trigger a custom validation of the "outer" model that holds all the entrants, however, that model is not accessible in the view, only the array of entrants is, and if I then trigger the error on the "outer" model, it will not be displayed to the user. Therefore I would like to trigger it for the first entrant that violates the rule, but how do I go about doing that?
My code that attempts this, looks like this so far:
/*
* Custom validation rule to hinder the same e-mail being used twice.
*/
public function noRepeatingEmails($attribute, $params)
{
if (!isset($attribute)) return;
$emails = array();
foreach($this->$attribute as $user)
{
if (isset($user) && strlen(trim($user->email)) != 0)
{
$emailToAdd = strtolower(trim($user->email));
if (in_array($emailToAdd, $emails))
{
$this->addError($user, '<my error message>');
return;
}
else
{
$emails[] = $emailToAdd;
}
}
}
}
This only results in a code 500 error though:
Illegal offset type
I presume that is because it is looking for the property "user" in my model, rather than adding an error to "$user" object.
How do I best accomplish this?
I have a .NET background, so I am probably doing loads wrong here however.
If I understood correctly from your comment, you want to validate your model before saving it. For this purpose, CActiveRecord provides beforeSave() method. You need to put this method inside your model:
protected function beforeSave()
{
if(parent::beforeSave())
{
if(/* Your validation goes here*/)
return true;
else
return false
}
else
return false;
}
When the result of this method is true, save() method will be called. Otherwise save() method won't be called and therefore no record will be saved into your database.
I have the following code in a controller action:
public function someAction()
{
// ...
$promo_repo = $em->getRepository('AcmeContactlistBundle:Promotion');
$default_promo_code = $this->container->getParameter('promo_default_code');
$promo = $promo_repo->findOneByCode($default_promo_code);
if (empty($promo)) {
$promo = new Promotion();
$promo->setCode($default_promo_code);
$start_date = $this->container->getParameter('promo_default_start_date');
$expiry_date = $this->container->getParameter('promo_default_end_date');
$promo->setStartsAt(new \DateTime($start_date));
$promo->setExpiresAt(new \DateTime($expiry_date));
$em->persist($promo);
$em->flush();
}
$contact = new Contact();
$contact->setPromotion($promo); // <- Error here. See error msg below
// Some more code follows ...
}
Error Message
PHP Catchable fatal error: Argument 1 passed to
Acme\ContactlistBundle\Entity\Contact::setPromotion() must be an
instance of Acme\ContactlistBundle\Entity\Promotion, null given,
...
I have checked the SQL generated by the above statements and also checked to make sure that a record is persisted to the promotion table (if not present). The promotion object is created and persisted to the database correctly, so I don't understand that by the times it comes to assigning it to the contact variable, it has a value of null.
What is going wrong?
I'm trying to take two lines of code from an elseif statement and create a function that returns the parameters back to the parent function. It's a simple card game that searches my $Cards array for a three of a kind. Here's the original code:
elseif(count($Cards) == 3) {
$CardsNotOfValue = $this->_getCardsNotOfFaceValue($faceValue, $CardsGroupedByValues);
list($Kicker1, $Kicker2) = $this->_getSortedCards($CardsNotOfValue);
return new ThreeOfAKind(array_merge($Cards, array($Kicker1, $Kicker2)));
}
Thus far, my code looks like this:
function { if (count($Cards) == 3) {
**LINE 36** $Kicker = $this->kickerCards($faceValue, $CardsGroupedByValues); }
**LINE 55** public function kickerCards(array $kickers)
{
$CardsNotOfValue = $this->_getCardsNotOfFaceValue($faceValue, $CardsGroupedByValues);
return $this->_getSortedCards($CardsNotOfValue);
}
When I try to execute a four of a kind, I get the following error (I tried to highlight the lines in question above):
PHP Catchable fatal error: Argument 1 passed to BestHandIdentifier::kickerCards() must be an array, integer given, called in /home/dev/parameter2/BestHandIdentifier.php on line 36 and defined in /home/dev/parameter2/BestHandIdentifier.php on line 55
I'm having a bit of trouble understanding how to create ($faceValue, $CardsGroupedByValues) and pass an array for my new function to evaluate. Have I gone too far in the wrong direction to begin with?
Your function definition is:
public function kickerCards(array $kickers);
So $kickers must be an array...
You are trying to call the function with:
$this->kickerCards($faceValue, $CardsGroupedByValues);
Passing two arguments, the $faceValue which is an integer, 2nd argument is an array.
Your function definition should look like:
public function kickerCards($faceValue, array $cards);
If I could elaborate further, making some assumptions.
My assumptions:
The function take a face value and array of cards currently held
The return of the function should be the cards in that array that do not match the face values.
The Cards are an array with a value (and possibly suit) key. e.g.
$twoOfHearts = array('value'=>2,'suit'=>'hearts');
So here's a possible implementation
public function kickerCards($faceValue, array $cards) {
$kickerCards = array();
foreach($cards as $card) {
if ($card['value'] != $faceValue)
$kickerCards[] = $card;
}
return $kickerCards;
}