Reusing Propel query bug or my bad? - php

Simple Propel reusing query is not working here, despite my code is similar to the example on Propel website. Is this a bug or my bad?
$q = MashupSettingQuery::create()->filterByMashup($this);
var_dump($q->count(), $q->findOneByKey('redirect_uri'), $q->count());
Output is:
int 5
object(MashupSetting)[28]
protected 'startCopy' => boolean false
protected 'id' => int 9
protected 'key' => string 'redirect_uri' (length=12)
int 1
that is, resusing is not working because count() first returns 5 and then 1.
Even using MashupSettingQuery::create()->filterByMashup($this)->keepQuery(true) didn't fix the problem.

I think it's normal because just before the second count you make a findOneByKey query, and so the second count just count how many objects this specific query return.
And your query return just one object, obviously because it's a findOneByKey.

Related

Get value of object in array

I have an array with an object. The value of the object is a counter from my database.
I need to make a condition on that object.
var_dump($myArray);
return
array (size=1)
0 =>
object(stdClass)[62]
public 'count(videos_like.videos_like_id)' => string '5' (length=1)
I try to do it like so:
if($myArray[0]->count(videos_like.videos_like_id) == '5'){...}
But of course I get an error.
Does anyone have an idea?
I'd rather advise you to update your SQL query and replace code:
count(videos_like.videos_like_id)
to
count(videos_like.videos_like_id) AS videosCount
hence you won't have this problem.
PS: Even you don't have plain SQL and use any framework - it's definitely possible to provide alias to your count column.

How to insert Array to Database using firstOrCreate in Laravel?

I have an array like this and it has 120 elements in it
`array (size=120)
0 =>
array (size=8)
'name' => That the quick brown fox jumps over the lazy - 7' (length=53)
'url' => string 'google.com/zyx' (length=134)
'category' => string 'search-engine' (length=6)
1 =>
array (size=8)
'name' => string 'Mr. john brandy gave me a wall nut of quite' (length=67)
'url' => string 'yahoo.com/dzxser' (length=166)
'category' => string 'indian' (length=6)`
I want to insert them to my bookmark table which model I have created and I want to make sure duplication doesn't occur. I have found this https://laravel.com/docs/5.4/eloquent#other-creation-methods specially firstOrCreate method.
I assume I have to use foreach but I am not sure how. Can anyone help me with some workaround.
Actually you don't need firstOrCreate, you need updateOrCreate. Checking Laravel Other Creation methods You will find that method.
Say that array is in $alldata:
foreach($alldata as $data) {
MyModel::updateOrCreate($data); //the fields must be fillable in the model
}
This will run update/or create of 120 queries while cycling through the loop. The advantage is that, you cannot have a duplicate, rather if there is a repetition, its only going to perform an update to the table.
However the best way to ensure that there is no duplication in whatever way the data comes is to set it up when making your database table. You can set unique constraints on many fields if thats your case.
If you don't want duplication to occur when inserting array of records then all you have to do it set a constraint making sure fields are unique.
If you're using migrations to create databse schema you can use something like this: $table->string('name')->unique();
Now for example, this will make sure that 'name' column data is

ZF2 SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

I've got the error "SQLSTATE[HY093]: Invalid parameter number: parameter was not defined" while trying to save an array into a related InnoDB, which makes no sense to me because I've already used the same method multiple times in the same Application and the DB connection seems to work as well because I can read and delete entries without any problems.
I've checked a lot of similar questions in hope they would resolve mine but haven't found one that resolved my problem.
This is the method I use to save to create the array and save it into the DB:
public function saveBest(Besten $besten)
{
$GePunkte = (int) $besten->Punkte/$besten->Dauer;
$data = array(
'GePunkte' => $GePunkte,
'Name' => $besten->Name,
'Zeitpunkt' => $besten->Zeitpunkt,
'Punkte' => $besten->Punkte,
'Dauer' => $besten->Dauer,
'GewäKat' => $besten->GewäKat,
);
print_r($data);
$this->tableGateway->insert($data);
}
I've already used "print_r($data)" to check if the data in the array is complete because I suspected this to be the cause of the error.
print_r displayed the following:
Array ( [GePunkte] => 0.125 [Name] => Test [Zeitpunkt] => 1451480345 [Punkte] => 1 [Dauer] => 8 [GewäKat] => Natur )
At the same time I checked if the values of each param matches the datatypes set in the DB. GePunkte is set as float, Name as text, Zeitpunkt as int, Punkte as int, Dauer as int and GewäKat as text, so all values are inside the set boundaries.
I've also checked if I've got all the params named right by checking the insert sql command in Phpmyadmin and it's:
INSERT INTO `bestenliste`(`Sid`, `GePunkte`, `Name`, `Zeitpunkt`, `Punkte`, `Dauer`, `GewäKat`) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5],[value-6],[value-7])
Since Sid is created automatically this seems to be alright too.
I can't figure out why it isn't working as it should, since everything else in the application seams to work perfectly fine, and because the deadline for this application is tomorrow at midnight I'm kinda in a hurry to resolve this problem.
So does anyone know a solution to this problem ?

When this fails, why does it delete just one row? (PDO, PHP, and MySQL glitch with types)

There was a bug in an old project where only one row was being deleted where it should have deleted multiple rows because of an IN statement in the SQL.
I used the following query for PDO:
DELETE FROM messages_to_people where (receiverID=:receiverID AND messageID IN ($inStatementSubQ))
each of these parameters are just ids such as 123, 456, 789. For example, var_dump() on the messageIDArray is
array (size=3)
0 => string '1040' (length=4)
1 => string '1041' (length=4)
2 => string '1042' (length=4)
The $inStatementSubQ is a string generated with various parameters to bind later with the help of a foreach loop that loops through binding the parameters:
foreach($messageIDArray as $key=>$id){
$paramToBind = ":id".$key;
$foo = $stmt->bindParam($paramToBind, $id, PDO::PARAM_INT);
}
If there were, say, 3 rows that should be deleted, this consistently only deleted one of the three rows each time it was run. Then it occurred to me to add intval() on the IDs to make them ints. After that it worked as expected.
$foo = $stmt->bindParam($paramToBind, intval($id), PDO::PARAM_INT);
I'm curious, before the intval() why this works to delete just one row, PDO reports true each time it binds, and the statements execution returns true as well. I would have expected it to fail, or perhaps to succeed while deleting all with the receiver ID, but I did not expect its old behavior where it deleted one each loop.
Any insights would help me in life,
thanks in advance,
The intval() was just a red herring. Though using intval() in the actual call to bindParam() worked, that's not the core issue. I realized this when I tried $newInt = intval(id) and it repeated the behavior of deleting just one instead of all of them.
The second parameter of bindParam() is mixed &$variable and binds by reference. So bindParam was taking the last ID and using that, ignoring the others. By substituting with
//$stmt->bindParam(":id".$key, intval($id), PDO::PARAM_INT);
$stmt->bindValue(":id".$key, $id);
I get the behavior I would expect and it deletes all of them.
Problem is that you are passing a string of comma separated ids, rather than passing 3 separate ids. At a guess MySQL with pdo tried to convert that string to an integer, probably just giving you the first id.
In effect you tried to execute
DELETE FROM messages_to_people
where (receiverID=1
AND messageID IN ('1,2,3'))
which has been converted to:-
DELETE FROM messages_to_people
where (receiverID=1
AND messageID IN (1))
while what you wanted was:-
DELETE FROM messages_to_people
where (receiverID=1
AND messageID IN (1,2,3))
You need to change your code to have one parameter for pdo for each id, and pass a value for each one. Not a single parameter for all of them which is a comma separated string.

var_dump of result gives null value. But deeper inspection returns a integer [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
New Mysqli Object is Null
I just started with building my database class for my MVC framework. While building this I am experimenting with simple queries and tables in order to make it work properly.
I was trying to query the following:
SELECT * FROM mvc_test
This should return 3 rows:
1 | test
2 | test2
3 | test3
I use the following method to query:
<?php $this->result = $this->conn->query($this->q); ?>
Where $this->conn is:
<?php
$this->conn = new mysqli($this->reg->conf->database['host'],
$this->reg->conf->database['user'],
$this->reg->conf->database['password'],
$this->reg->conf->database['database']);
?>
Where $this->reg->conf->database contains all the values for host, database etc. This works, I have a connection.
Now, when I var_dump the result like this:
<?php var_dump($this->result); ?>
I get this:
object(mysqli_result)[9]
public 'current_field' => null
public 'field_count' => null
public 'lengths' => null
public 'num_rows' => null
public 'type' => null
But, as said before it should contain at least 3 rows, so I would expect num_rows to be '3'.
Now, when I var_dump the num_rows of the result like this:
<?php var_dump($this->result->num_rows); ?>
I get a 'int 3' as response.
Conclusion: in the first var_dump it's null, but with a deeper inspection I get a 3. So it reads 3 rows. When I add another row (the 4th), it returns a 4 as expected.
My question is: why is the var_dump not working properly? Why Does it say null at first, but with a deeper inspection it does have a value.
Thanks in advance, I'm really struggling with this one since I don't get any errors as well.
The object is implemented "lazily", i.e. it does not retrieve data from the server until it's actually required (i.e. you access something from the result object).
var_dump doesn't seem to trigger the property getters so they are shown as null.

Categories