Trying to compare PDO statements - php

I am grabbing two random rows from my table. I then want to compare them to make sure that they are not the same rows. If they are I want to keep selecting a random row until I get on that is not the same.
Currently I am selecting random rows fine my issue comes up when I hit the while loop trying to get a different row. I get the following error "Call to a member function fetch() on a non-object"
for ($i = 1; $i <= $cycles; $i++) {
$t1 = $dbtemp->query("SELECT * FROM `test` ORDER BY RAND() LIMIT 1");
$t2 = $dbtemp->query("SELECT * FROM `test` ORDER BY RAND() LIMIT 1");
$winner = $t1->fetch(PDO::FETCH_ASSOC);
$loser = $t2->fetch(PDO::FETCH_ASSOC);
if($winner['id'] == $loser['id']) {
while($winner['id'] == $loser['id']) {
$t2 = $dbtemp->query("SELECT * FROM `content` ORDER BY RAND() LIMIT 1");
$loser = $t2->fetch(PDO::FETCH_ASSOC); // Error occurs on this line
}
}
Any suggestions on how I should or could go about making this work would be great.

Why don't you do like this:
$t1 = $dbtemp->query("SELECT * FROM test ORDER BY RAND() LIMIT 2");
And then:
$players = $t1->fetchAll(PDO::FETCH_ASSOC);
$winner = $players[0];
$loser = $players[1];

Related

Select last row mysqli

$select1 = mysqli_query($conn, "SELECT robotid FROM robotidsz ORDER BY robotid DESC LIMIT 1");
for ($i = $select1; $i <= 9999999; $i++) {
Above is my code, this should search from the last "RobotID known in the table to 9999999.
If i change $select1 to 1000000 this functions from 1000000-9999999 correctly however using this code nothing happens?
You need to extract the result from your query. At the moment, you're assigning $i an initial value of the Resource returned.
The following demonstrates how to solve this:
$select1 = mysqli_query($conn, "SELECT robotid FROM robotidsz ORDER BY robotid DESC LIMIT 1");
$result = mysqli_fetch_object($select1);
for ($i = $result->robotid; $i <= 9999999; $i++)
{
// Do your stuff...
}

How to select the maximum value of a column in MySQL

I want to select the maximum value of a column of my table. I'm using PHP and MySQL. This is what I have so far:
$max = "SELECT MAX(Id) FROM trialtabel2";
$max1 = mysqli_query($dblink, $max);
echo= $max1;
My debugger is just saying that it is a query returning a 0 boolean value (false). I cannot find a specific answer anywhere on the internet.
You need to fetch the data from the mysqli_result object that was returned to you when you executed your query using mysqli_query.
$max = "SELECT MAX(Id) as id FROM trialtabel2";
$max1 = mysqli_query($dblink, $max);
$row = mysqli_fetch_assoc($max1); // this was missing
$id=$row['id'];
echo $id;
Note: I removed the loop because with MAX query without any grouping you will get only 1 row returned. If you had multiple rows in result set you would need to loop through all of them
two ways
first is as people described
$max = "SELECT MAX(Id) as max_id FROM trialtabel2";
$max1 = mysqli_query($dblink, $max);
$row = mysqli_fetch_assoc($max1);
$max_id=$row['max_id'];
echo $max_id;
second is ordering and limiting
$max_id = 0;
$max = "SELECT id FROM trialtabel2 order by id desc limit 0,1";
$max1 = mysqli_query($dblink, $max);
while($row = mysqli_fetch_assoc($max1)){
$max_id=$row['id'];
}
echo $max_id;
In Your code you missing the fetch statement. you need to fetch from the resultset. see above what you are missing.
Try using this..,
$max = "SELECT MAX(Id) as maxId FROM trialtabel2";
$max1 = mysqli_query($dblink, $max);
$row = mysqli_fetch_assoc($max1);
echo $row['maxId'];
Hope this helps..
$max = "SELECT Id FROM trialtabel2 order by id desc limit 1";
$max1 = mysqli_query($dblink, $max);
$result = mysqli_fetch_assoc($max1);
pre($result);

Limit query results after receiving result

I'm having sort of an issue with sorting and giving sort of a ranking while having pagination.
$query = "SELECT * FROM users WHERE approved=1 ORDER BY Likes DESC LIMIT $start_from, $num_rec_per_page";
$result = mysqli_query($conn,$query);
$i=1;
while($row = mysqli_fetch_assoc($result)){
echo 'Rank: '.$i++.'. Name:'.$row[Name].'Likes: '.$row[Likes].'<br>';
}
This way, every page rank is given all over again.
My question is, how to Limit query only AFTER receiving all data,
or maybe some advice on doing other way of pagionation.
UPDATE:
Fixed the problem by changing $i=1; to $i=$start_from+1;
Limiting the $i ?
$maxPerPage = 20;
$i = 0;
while($i < $maxPerPage && $row = mysqli_fetch_assoc($result)){
echo 'Rank: '.$i++.'. Name:'.$row[Name].'Likes: '.$row[Likes].'<br>';
}
But LIMITING in mysql (in your case) is better than getting all rows and fetching just some.

MySQL displaying 1 result within while loop...however theirs actually 2 results?

I recently combined 2 queries into 1 (to optimize performance)...1 query for checking the count, and the other for the results, the count is to ensure their is actual results their before proceeding with the loop.
Heres the PHP code:
<?php
$query = 'SELECT id, title, COUNT(id) FROM submissions ORDER BY sub_time DESC LIMIT 50';
$result = mysql_query($query);
$count = mysql_result($result, 0, 2);
mysql_data_seek($result, 0); //mysql_result resets the internal pointer...
if ($count > 0) {
$i = 0;
while ($output = mysql_fetch_assoc($result)) {
++$i;
//etc..
}
}
?>
The problem is it now returns 1 result? - when theirs actually 2 results inside (as I've checked via PHPMyAdmin aswell as running the following code - see below), I've narrowed down the problem, its because the COUNT(id) has been combined with the intial results query; that its behaving like this.
Because if I do the following:
<?php
$query = 'SELECT id, title FROM submissions ORDER BY sub_time DESC LIMIT 50';
$result = mysql_query($query);
$i = 0;
while ($output = mysql_fetch_assoc($result)) {
++$i;
//etc..
}
?>
It returns 2 results...
So my question is how do i resolve this but achieve what I'm after?
I would recommend that you remove the COUNT(id) and use the mysql_num_rows() function to check how many rows were returned before trying to loop through them.
Your code could then look like this:
<?php
$query = 'SELECT id, title FROM submissions ORDER BY sub_time DESC LIMIT 50';
$result = mysql_query($query);
$count = mysql_num_rows($result);
if ($count > 0) {
$i = 0;
while ($output = mysql_fetch_assoc($result)) {
++$i;
//etc..
}
}
COUNT is an aggregate function that typically is used with the GROUP BY clause. I don't believe it is meaningful in the query as you used it.

How do I get previous and next rows even though some rows have been deleted?

I have the following PHP functions that determine the next and previous rows in a database. However, there are lots of occasions when rows can be deleted and therefore my functions will not work as all they do is decrement the auto_increment field.
For example, current row 5. My function gives: 4 (previous) and 6 (next). What if 6 and 7 is deleted. My best idea is to keep querying until I get a row, but this seems inefficient, is there a better way?
Thanks all
//function to get next tweet
function getNextTweet($key, $direction){
$sql = "SELECT tweet_id FROM tweets WHERE tweet_key = '$key' LIMIT 1";
$result = mysql_query($sql) or die("DB Error : ". mysql_error());
$result = mysql_fetch_assoc($result);
if($direction=='next'){
$tweet_id = $result['tweet_id'] + 1;
}else{
$tweet_id = $result['tweet_id'] - 1;
}
$sql = "SELECT * FROM tweets WHERE tweet_id = '$tweet_id' LIMIT 1";
$result = mysql_query($sql) or die("DB Error : ". mysql_error());
return mysql_fetch_assoc($result);
}
Assuming you don't have a bajillion records...
Previous:
SELECT *
FROM table
WHERE (id < currentID)
ORDER BY id DESC
LIMIT 1
Next
SELECT *
FROM table
WHERE (id > currentID)
ORDER BY id ASC
LIMIT 1
If you run a modern version of MySQL, you can simplify your function into
function getNextTweet($key, $direction)
{
$cmp = ($direction == 'next') ? '>' : '<';
$order = ($direction == 'next') ? 'ASC' : 'DESC';
$sql = "SELECT *
FROM tweets
WHERE tweet_id $cmp (SELECT tweet_id FROM tweets WHERE tweet_key = '$key' LIMIT 1)
ORDER BY tweet_id $order
LIMIT 1";
$result = mysql_query($sql) or die("DB Error : ". mysql_error());
return mysql_fetch_assoc($result);
}
As long as "tweet_id" is indexed, the query will be very fast, even for millions of records.
One last thing, make sure that $key is properly validated! Otherwise, anyone can inject SQL in your query, that's a huge security flaw. If $key is anything but a hash key, it should at least go through mysql_real_escape_string()

Categories