extracting a query result in cakephp 3 - php

Hello everyone will see I have the following query
$query = $this->PreguntasAlternativas->find();
$query->select(['id_alternativa' => $query->func()->max('id_alternativa')
])->where(['id_pregunta' => $idquestion]);
This returns me such an arrangement
query(array)
0(object)
id_alternativa(null)
and what I want is to get the value returned me to then do a validation, not how to retrieve the value returned by the query me to do something like
if($query == null){
$result = 1;
}else{
$result = +1;
}
please help

Queries are lazily executed, and as such your query will be a Cake\ORM\Query object. You will need to execute the query in order to be able to process the results.
If you add ->toArray() to your query, this will cause it to be executed and converted to an array. This will allow you to work with the results.

my fues solution this, change the structure of my query
$query = $this->PreguntasAlternativas->find('all', ['conditions' => ['id_pregunta' => $idquestion]]);
$result = $query->max('id_alternativa');
if(!$result['id_alternativa']){
$result['id_alternativa'] = 1;
} else {
$result['id_alternativa'] += 1;
}
Thanks

Related

Rows number check in PHP

I am trying to check if there were any records (more than 0) in my database table:
$ifExists = DB::select('SELECT COUNT(*) FROM `characters` WHERE userid = ?', array(Auth::id()));
Now I am checking if there are more than 0:
if($ifExists > 0){
return Redirect('/board');
}
else{
return view('intro');
}
It always takes me to the /board. But there are many rows in this database table.
The echo $ifExists; shows me [{"COUNT(*)":0}]
How do I check this number?
Try it this way:
$ifExists = DB::table('characters')->where('userid', Auth::id())->count();
If you do it like in your question, you will receive an array of objects.
If you only want to check for existens of entries and do not need the count, you can just use the exists() function whitch will return you a boolean:
$ifExists = DB::table('characters')->where('userid', Auth::id())->exists();
if($ifExists){
return Redirect('/board');
}else{
return view('intro');
}
Been a while since I've done PHP, but from the looks of it you get a result object from the database. That object is 1 object.
I think that's why it's always redirecting to /board.
Not sure how to do this in PHP, but you want to get the value of "COUNT(*)" from the object for your if statement. Hope that helps :)

mysql query search with "If" statement

So, I have following php query:
for($i = 0; $i < sizeof($cat_result) ; ++$i) {
$query_p = "SELECT * FROM $table WHERE id = %d";
$results[] = $wpdb->get_row($wpdb->prepare($query_p, $cat_result[$i]));
}
The search relies on $cat_result which contains numerous numbers.
For example, let say $cat_result contains the following number: '1,3,5,21,35`
Using these 5 numbers, the query will look for the db info.
However, there are scenarios where some number (for example, "21") do not exist in the db.
Then, I get PHP NOTICE: trying to get property of non-object.
How do I write "if" statement so that if the id (in this case "21") does not exist, then it simply ignores the query? (It is hard to explain what I mean by "ignore". I still want the query to do the search but if it does not find what it is looking for, then simply ignore the error).
I think you should restructure your query. That way, as long as your data is sanitized (to prevent injection as im not sure if it comes from the user or not), you can just do the following:
$cat_result = implode(",", $cat_result);
$query_p = "SELECT * FROM $table WHERE id in ( $cat_result )";
$rslt = $wpdb->get_results($query_p);
// loop result
That way, it will fetch you all in that list.
Try this:
for($i = 0; $i < sizeof($cat_result) ; ++$i) {
$query_p = "SELECT * FROM $table WHERE id = %d";
$row = $wpdb->get_row($wpdb->prepare($query_p, $cat_result[$i]));
if ($row) {
$results[] = $row;
}
}
I don't know WordPress, but I suspect get_row returns false when there are no more rows of results. Your code was putting false into $results when that happened, and later code was then trying to use that as an object.

PHP MYSQL mysql_fetch_array, loop. right way to go?

I have a query that returns a few rows, and I have the following lines of code to retrieve them:
$result_set = mysql_query($query);
while($net_biz_sub_data[]=
mysql_fetch_array($result_set,MYSQL_ASSOC));
My question is what is the right way to retrieve that db query data without getting the last array empty ?
When I count() it is always num of rows + 1, and I would like to correct that.
Because of the way the while loop works, you should do
while($dataz = mysql_fetch_assoc($result_set))
{
$net_biz_sub_data[] = $dataz;
}
Use
$result_set = mysql_query($query);
while($net_biz_sub_data = mysql_fetch_assoc($result_set)){
//use $net_biz_sub_data here
}

mysql_fetch_array() timing out

I am trying to query a database, but it seems to just load for an age and not do anything. It's a simple query and shouldnt take longer than a millisecond.
while($row = mysql_fetch_array(getWallPosts($userid)))
{
}
Now when I replace this code with:
echo mysql_num_rows(getWallPosts($userid));
It just displays '1' in fact there's only one record in the DB and it's just a simple SELECT statement.
Here's the getWallPosts function:
function getWallPosts($userid, $limit = "10")
{
$result = dbquery("SELECT * FROM commentpost
WHERE userID = ".$userid."
ORDER BY commentPostID DESC LIMIT 0, ".$limit);
return $result;
}
Also, when I put the SQL string that it's executing into MySQL's query browser. It takes no time at all.
Any ideas?
You appear to be looping indefinitely because you're retrieving a new set (one record) of data each time.
$result = getWallPosts($userid);
while ($row = mysql_fetch_array($result)) {
//printf($row[0]);
}
You need to get the data once and loop through it. Your code is getting the data, running the loop and then getting the data again.
Try:
$posts = getWallPosts($userid);
while($row = mysql_fetch_array($posts))
{
//Code to execute
}
Its an infinite loop. The expression in the while always executes so it will always be true.
You're returning a new result set each time the while statement executes. You should call getWallPosts first, assign it to $results, and then loop over it.

Counting num_rows issue

I have a query like this:
SELECT * FROM configurations WHERE ID = userID
I then have logic like this:
if ($query->num_rows() > 0) {
foreach($query->result() as $row) {
// display data
}
else {
// display no data found message
}
But when I try to do this:
count($query->num_rows())
it is always 1, no matter how many results are returned. If 1 or more are returned the "if" is executed. If there are no results returned the "else" is executed. Yet, the count never changes. What is going on?
You can't count() a number, it works fine. If you only want number of records from table use COUNT() in SQL...
$sql = mysql_query("SELECT COUNT(0) AS count FROM configurations WHERE ID = userID");
$sql = mysql_fetch_assoc($sql);
$count = $sql["count"];
Otherwise just assign $count = $query->num_rows(); as #chriso stated.
Firstly else { should be } else { - you're missing a brace
Secondly, count() is used to count the number of elements in an array. Since $query->num_rows() returns a number rather than an array, you don't need to use count(). In your case, count() was telling you that there's one number, not what the actual number was!
Try:
$count = $query->num_rows();
echo $count;
You're getting an integer with $query->num_rows(), so when you run that integer through the count() function it is designed to return 1.
http://us2.php.net/manual/en/function.count.php
If var is not an array or an object
with implemented Countable interface,
1 will be returned. There is one
exception, if var is NULL, 0 will be
returned.

Categories