MySQL Select from table depending on variable [duplicate] - php

This question already has answers here:
PHP Variable in Select Statement
(7 answers)
Closed 7 years ago.
I have the following problem:
I am trying to select a result from a MySQL database table, depending on the category value:
$sql = mysql_query("SELECT * FROM products WHERE category='garniture' ORDER BY date_added DESC LIMIT 2");
The problem is that I don't want to use a static value for category (like 'garniture'), but I want this to be determined by a variable value (let's say that variable is $category). How can I manage this?

Without getting into the fact that you should not be using the MySQL Library anymore, use MySQLi or PDO instead, you would insert a variable in that string as such:
$sql = mysql_query("SELECT * FROM products WHERE category='$category' ORDER BY date_added DESC LIMIT 2");
Or if you find it easier to read:
$sql = mysql_query("SELECT * FROM products WHERE category='" . $category . "' ORDER BY date_added DESC LIMIT 2");

$sql = mysql_query("SELECT * FROM products WHERE category='$category' ORDER BY date_added DESC LIMIT 2");
Just put the variable where you want it in the string.
The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.
See the PHP manual about string interpolation.

Related

SQL, "WHERE IN" returns automatically sorted result [duplicate]

This question already has answers here:
Ordering by specific field value first
(8 answers)
Maintaining order in MySQL "IN" query
(2 answers)
Closed 5 years ago.
When I run my query with an WHERE IN statement, it seems like it automaticly sorts the product_id that are returned.
$SQL = "SELECT * FROM PIM WHERE product_id in (10,8,1,3)";
foreach($conn->query($sql) as $row) {
echo $row['product_id'] . "<br>";
}
Result:
1
3
8
10
I want them returned in the order they entered in (10,8,1,3)
Since in your original query you did not specify which order MySQL should use then is using ASC, Try using ORDER BY FIELD() like this:
SELECT * FROM PIM WHERE product_id in (10,8,1,3) ORDER BY FIELD(product_id, 10,8,1,3);
Check this great answer for more details.
Try:
select * from PIM where id in (1,3,8,10) order by find_in_set(id,'10,8,1,3');

How to select a random row in MySQL and PHP? [duplicate]

This question already has answers here:
How to SELECT random rows from table with an exact number of row?
(2 answers)
Closed 8 years ago.
My table is like this:
id,url,name,imagelink
and I'd like to do something like:
SELECT * FROM id WHERE id="randomid"
I want to get all the data from a random row like id=17,url17,name17,imagelink17 and save it in variables afterwords. e.g $currentid,$currenturl, $currentname, $currentimagelink
I've tried something like that:
"SELECT * FROM table WHERE id= ORDER BY rand() LIMIT 20";
which obviously did not work. How can I do this correctly?
As you don't want a specific row, leave the WHERE id= out of the query and it should work.
SELECT * FROM table ORDER BY RAND() LIMIT 20
will return 20 random rows,
SELECT * FROM table ORDER BY RAND() LIMIT 1
will give you only one
Try something like this:
$query = "SELECT * FROM table_name ORDER BY RAND() LIMIT 1";
$result= mysqli_query($connection, $query);
and for the variables you can have
while($row = mysqli_fetch_array($result))
{
$currenid=$row['id'];
$currenturl=$row['url'];
$currentname=$row['name'];
$currentimagelink=$row['imagelink'];
}
You can have query like this:
SELECT * FROM table_name ORDER BY RAND() LIMIT 1

How to select from 'table' WHERE column = *wildcard* [duplicate]

This question already has answers here:
MySQL Wildcard for "=" - is there one
(8 answers)
Closed 8 years ago.
When this code loads i want it to select everything and show it, and then be able to change the results with Ajax by altering the column row variable $data.
So how do i load column bbookschool with a wildcard and change it later?
$data = '_';
$Result = mysql_query("SELECT * FROM ads WHERE bbookschool = '$data' ORDER BY time desc limit 15")
i want to put a select list for values to be chosen which will be $data
Thanks
You might want to look at the LIKE operator:
SELECT foo FROM bar WHERE baz LIKE '%part-of-baz%'
Using LIKE and updating you $data should do the trick
You can use an or condition. When $data is the empty string, then the query will select everything:
SELECT *
FROM ads
WHERE bbookschool = '$data' or '$data' = ''
ORDER BY time desc
limit 15;

PHP, MySQL: how to select random records without RAND (attempt to avoid RAND()) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to request a random row in SQL?
Because of a huge table I cannot use MySQL function RAND() and trying to avoid using RAND() this way:
$a = mysql_fetch_array(mysql_query("SELECT MIN(id), MAX(id) FROM table WHERE category_id='".$var."'"));
$id = rand($a[0],$a[1]);
$id2 = rand($a[0],$a[1]);
Which doesn't work, because: in $a I have the biggest and smallest ID with the respective category_id - that's ok.
The problem brings the rows with $id and $id2 - because there are used the minimal and maximal ID values, but PHP function rand() will take some random value between minimum and maximum - and there is a big probability, that the picked out record will not belongs into category_id.
So I would like to ask you about a way, how could I fix this example.
THank you
You could try this:
$row = mysql_fetch_assoc(
mysql_query(
"SELECT count(*) as count FROM table WHERE category_id='$var'"));
$randomrow = rand(0, $row['count'] -1);
$q = mysql_query("
SELECT * FROM table
WHERE category_id='$var'
LIMIT 1 OFFSET $randomrow");

php mysql AND operator [duplicate]

This question already has answers here:
How can I write SQL for a table that shares the same name as a protected keyword in MySql? [duplicate]
(3 answers)
Closed 9 years ago.
I get a error message saying:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'key='12345' AND id='98765' LIMIT 1' at line 1
My code is:
$key = '12345';
$id = '98765';
include realpath('./inc/config.php');
$query = mysql_query("SELECT * FROM users WHERE key='{$key}' AND id='{$id}' LIMIT 1", $config) or die(mysql_error());
$result = mysql_fetch_assoc($query);
Now can anyone tell me whats wrong in this?
key is a reserved word, you need to properly quote it with backticks if you want to use it as a field name.
SELECT * FROM users WHERE `key`='{$key}' AND id='{$id}' LIMIT 1
SELECT * FROM users WHERE `key`='{$key}' AND id='{$id}' LIMIT 1
key is a reserved word
Your key and id are obviously numeric. Although adding quotes wouldn't hurt, you definitely don't need them. You edon't need brackets in any query period.
Try this:
$query = mysql_query("SELECT * FROM users WHERE key=$key AND id=$id LIMIT 1", $config) or die(mysql_error());
$result = mysql_fetch_assoc($query);
If that doesn't work just run this using PHPMyAdmin or whatever you use to run queries on your db.
SELECT * FROM users WHERE key=12345 AND id=98765
I also don't see why you would need LIMIT clause. It wouldn't break anything but if your id is actually row id it should give you a unique record.

Categories