PHP / SQL Query and PHP Variables - php

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);

Related

What if I don't fetch an SQL query?

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?

SELECT ... LIMIT 0,1 syntax error

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"

SQL Select latest row where value matches

I'm trying to return the row from my database, with the highest UID, where the URL column matches http://urltocheck.com.
I've tried all manner of things I can think of, and this is the closest I can get, but I'm getting an SQL syntax error.
My Table is called Adam, and I have the columns... UID (unique), URL (plus loads more). I'm trying to access the MySQL databse via PHP.
$query = "SELECT * FROM `Adam`
WHERE URL='http://urltocheck.com'
ORDER BY `UID` ASC;
LIMIT 1;";
Can anyone help please?
You shoul use order DESC and remove the ";" after ASC
$query = "SELECT * FROM `Adam`
WHERE URL='http://urltocheck.com'
ORDER BY `UID` DESC
LIMIT 1";
Try like this. Also, remove ; at this line ORDER BY UID ASC; (didn't noticed that earlier) because of which limit 1 not coming to picture.
SELECT * FROM `Adam`
WHERE URL='http://urltocheck.com'
and `UID` = (select max(`uid`) from `Adam`)
with the highest UID
You should order by UID desc and limit to 1.
You can also ORDER BY MAX ID.
<?php
$query = "SELECT * FROM `Adam`
WHERE URL='http://urltocheck.com'
ORDER BY MAX(`UID`) DESC;";
This is executed faster.
$query = "SELECT * FROM `Adam`
WHERE URL='http://urltocheck.com'
ORDER BY MAX(`UID`);";
?>

$wpdb->wp_users returning empty value for

I have a code Example:
function custom_func(){
global $wpdb;
$wpdb->flush(); //tried with and without this line
$getTest = 'SELECT * FROM $wpdb->wp_users LIMIT 1';
$arrayReturned = $wpdb->get_results($wpdb->prepare($getTest));
}
From what I've read I thought that $wpdb->wp_users is meant to have returned the database name and table name like so dbName.tableName; but it just returns an empty value.
I've tried:
$getTest = 'SELECT * FROM $wpdb->wp_users LIMIT 1';
which shows as the following to wordpress:
SELECT * FROM $wpdb->wp_users LIMIT 1
and
$getTest = 'SELECT * FROM '.$wpdb->wp_users.' LIMIT 1';
which shows as the following to wordpress:
SELECT * FROM LIMIT 1
I can't fathom why this isn't working since this is all based on literature from the wordpress codex, any thoughts?
You don't need to prefix the tables. As $wpdb->table will do it for you. Also you need to use double quotes " instead of single ' because you are using $wpdb variable in your query string.
'SELECT * FROM $wpdb->wp_users LIMIT 1';
^---------------------^^^-------------^---
Use it without table prefix and with double quotes ".
"SELECT * FROM $wpdb->users LIMIT 1";
Also you don't need to use prepared statement because as there are no user input.
Your code should look like this:
function custom_func() {
global $wpdb;
$getTest = "SELECT * FROM $wpdb->users LIMIT 1";
$arrayReturned = $wpdb->get_results($getTest);
var_dump($arrayReturned); // see results
}

Is it ok to query inside a while loop?

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);
?>

Categories