So I was wondering what if at the end of a simple SQL query in PHP like this:
$sentence = $connection->prepare("
SELECT * FROM posts_comments WHERE comment_on = $id ORDER BY date DESC LIMIT 2
");
$sentence->execute();
return $sentence->fetchAll();
I didn't put the fetchAll() function, so it would be like this:
$sentence = $connection->prepare("
SELECT * FROM posts_comments WHERE comment_on = $id ORDER BY date DESC LIMIT 2
");
$sentence->execute();
Will there be any difference in the result or it would be the same?
Related
I have two mysql query as follows
$sql1 = mysqli_query($mysqli, "SELECT * FROM manualp WHERE client_id=75 AND date between '$currentdate' and '$prevdate' ");
$sql2=mysqli_query($mysqli, "SELECT * FROM manualp WHERE client_id=75 order by date DESC LIMIT 1");
Is there any way i can join them together ? and get them in a array . For example
Both query are joined into $sql3 . I would like to post result having value $sql2 showing last
while($result = mysqli_fetch_array($sql3)) {
POST RESULTS HERE
}
Based on your comments, because you're using ORDER BY and LIMIT in your query, you actually need to wrap that second query in a subquery to perform a UNION.
SELECT * FROM manualp WHERE client_id=75 AND date between '$currentdate' and '$prevdate'
UNION
SELECT * FROM (SELECT * FROM manualp WHERE client_id=75 order by date DESC LIMIT 1) t1
I thought this would be simple but I'm having a tough time figuring out why this won't populate the the data array.
This simple query works fine:
$queryPrice = "SELECT price FROM price_chart ORDER BY id ASC LIMIT 50";
$resultPrice = mysqli_query($conn, $queryPrice);
$data = array();
while ($row = mysqli_fetch_array($resultPrice)) {
$data[] = $row[0];
}
But instead I want it to choose the last 10 results in Ascending order. I found on other SO questions to use a subquery but every example I try gives no output and no error ??
Tried the below, DOESN'T WORK:
$queryPrice = "SELECT * FROM (SELECT price FROM price_chart ORDER BY id DESC LIMIT 10) ORDER BY id ASC";
$resultPrice = mysqli_query($conn, $queryPrice);
$data = array();
while ($row = mysqli_fetch_array($resultPrice)) {
$data[] = $row[0];
}
I also tried specifying the table name again and using the IN, also doesn't work:
$queryPrice = "SELECT price FROM price_chart IN (SELECT price FROM price_chart ORDER BY id DESC LIMIT 10) ORDER BY id";
$resultPrice = mysqli_query($conn, $queryPrice);
$data = array();
while ($row = mysqli_fetch_array($resultPrice)) {
$data[] = $row[0];
}
In both examples my array is blank instead of returning the last 10 results and there are no errors, so I must be doing the subquery wrong and it is returning 0 rows.
The subquery doesn't select the id column, so you can't order by it in the outer query. Also, MySQL requires that you assign an alias when you use a subquery in a FROM or JOIN clause.
$queryPrice = "SELECT *
FROM (SELECT id, price
FROM price_chart
ORDER BY id DESC LIMIT 10
) x ORDER BY id ASC";
$resultPrice = mysqli_query($conn, $queryPrice) or die (mysqli_error($conn));
$data = array();
while ($row = mysqli_fetch_assoc($resultPrice)) {
$data[] = $row['price'];
}
You would have been notified of these errors if you called mysqli_error() when the query fails.
Your second query is the closest. However you need a table alias. (You would have seen this if you were kicking out errors in your sql. Note you will need to add any field that you wish to order by in your subquery. In this case it is id.
Try this:
SELECT * FROM (SELECT price, id
FROM price_chart ORDER BY id DESC LIMIT 10) as prices
ORDER BY id ASC
You must have errors, because your SQL queries are in fact incorrect.
First, how to tell you have errors:
$resultPrice = mysqli_query (whatever);
if ( !$resultprice ) echo mysqli_error($conn);
Second: subqueries in MySQL need aliases. So you need this:
SELECT * FROM (
SELECT id, price
FROM price_chart
ORDER BY id DESC LIMIT 10
) AS a
ORDER BY id ASC";
See the ) AS a? That's the table alias.
for($nr = 0; $nr < 2; $nr++){
print $nr; print(gettype($nr)); // prints 0integer
$result = mysqli_query($con,"SELECT * FROM phcdl_files
ORDER BY file_id DESC LIMIT '$nr',1")
or die(mysqli_error($con));
}
Trying to run the query above but I'm having troubles because of syntax.
Running it on PhpMyAdmin with Limit 0,1 works good however
Any idea what's the problem?
Try with -
"SELECT * FROM phcdl_files ORDER BY file_id DESC LIMIT $nr,1"
I think the issue is that you're adding quote around the 0.
Your SQL query should look like:
"SELECT * FROM phcdl_files ORDER BY file_id DESC LIMIT $nr, 1"
remove single quotation of $nr veriable from query
QUERY = "select * from tb_name order by id desc limit $nr , 1"
I have two tables in one database. I am querying the first table limit by 10 then loop the results. And inside the while loop, I am doing again another query using a data from the first query as a parameter. Here is an example of the script:
<?php
$con = mysql_connect(host,username,password);
mysql_select_db(game_server);
//My first query
$q1 = mysql_query('SELECT * FROM game_characters ORDER BY score DESC LIMIT 10');
while($character = mysql_fetch_object($q1)){
//My second query
$q2 = mysql_query('SELECT * FROM game_board WHERE id="'.$character->id.'"');
$player = mysql_fetch_object($q2);
}
?>
So if I have a result of 100 rows, then the second query will execute 100 times. And I know it is not good. How can I make it better. Is there a way to do everything in one query? What if there is another query inside the while loop where a data from the second query as a parameter is used?
P.S.: I am doing a rankings system for an online game.
You can do it in one query if you use JOINs.
SELECT * FROM game_board AS b
LEFT JOIN game_characters AS c ON b.id = c.id
ORDER BY c.score DESC
LIMIT 10
You can also use nested query
SELECT * FROM game_board AS b WHERE
id IN (SELECT id FROM game_characters AS c ORDER BY score DESC LIMIT 10)
You can also put all game_character.id into an array, and use
$sql = "SELECT * FROM game_board AS b WHERE b.id IN (" . implode(', ', $game_character_ids) . ")";
Why not using JOIN?
This way there will be no queries within the while loop:
$con = mysql_connect(host,username,password);
mysql_select_db(game_server);
//My first query
$q1 = mysql_query('
SELECT *
FROM game_characters gc
LEFT JOIN game_board gb ON gc.id = gb.id
ORDER BY score DESC
LIMIT 10
');
while($character = mysql_fetch_object($q1)){
// do Your stuff here, no other query...
}
A better approach here would be to collect all the IDs in a concatenated string str in form 'id1', 'id2', 'id3', ... and use:
select * from game_board where id in (str)
What about if you do something like the following:
<?php
$con = mysql_connect(host,username,password);
mysql_select_db(game_server);
//My first query
$q1 = mysql_query('SELECT * FROM game_characters ORDER BY score DESC LIMIT 10');
while($character = mysql_fetch_object($q1)){
//My second query
$characters .= " ' $character->id ' ,"
}
$q2 = mysql_query("SELECT * FROM game_board WHERE id in (substr($characters,0,strlen($characters - 2))");
$player = mysql_fetch_object($q2);
?>
I have this query below:
$msgg = mysql_query("SELECT *
FROM mytable
WHERE time>$time
AND id='someid'
ORDER BY id ASC
LIMIT $display_num",$myconn);
see this line: AND id='someid' <-- someid ...
OK, the query above returns 2 results as expected...
Now for the problem....
-- I have a variable myVar and it's content is "someid" (without quotes)...same as the string 'someid'
When I do this:
$msgg = mysql_query("SELECT *
FROM mytable
WHERE time>$time
AND id=myVar
ORDER BY id ASC
LIMIT $display_num",$myconn);
See: myVar <-- this variable contans .. someid
The second query returns no results.
Update: When using ... AND id='$myVar' it sees $myVar as empty for some reason.
Put a $ in front of myVar:
$msgg = mysql_query(
"SELECT *
FROM mytable
WHERE time > $time
AND id = '$myVar'
ORDER BY id ASC
LIMIT $display_num", $myconn
);
You forgot the dollar sign and the single quotations:
AND id='$myVar'
Additionally, you may want to consider using heredoc:
$query = <<<MYSQL
SELECT *
FROM mytable
WHERE time>$time
AND id='$myVar'
ORDER BY id ASC
LIMIT $display_num
MYSQL;
$msgg = mysql_query($query, $myconn);