SELECT id WHERE id equals a passed value - php

I am passing the "id" value from one page media_main.php to another player.php via:
<a href="javascript:;" onclick="return popitup('player.php?pid=<?php echo ("$row->id");?>')" title="Listen">
On the player.php page I would like to select certain data WHERE the id equals that id that was passed. So far I have this:
$query = "SELECT id, media_date, media_title, given_by, filename FROM media WHERE id = ?? ORDER BY id DESC";
I'm not sure how to work the WHERE clause since it will change and not be a static number. I only want to select the data when the id to equal the passed id value.

Additionally to Clive's response, if you know that the ID is only numerical, you can cast it to an Integer instead of escaping it.
If there is any erroneous input it will just cast it to 0.
$pid = (int) $_GET['pid'];
$query = "SELECT id, media_date, media_title, given_by, filename FROM media WHERE id = '$pid' ORDER BY id DESC";

From the looks of your code you're passing the ID in via a URL parameter (pid), in which case you just need to escape the string to prevent SQL injection and build your query up using the resulting id:
$pid = mysql_real_escape_string($_GET['pid']);
$query = "SELECT id, media_date, media_title, given_by, filename FROM media WHERE id = '$pid' ORDER BY id DESC";
It would probably be wise to check that the passed value is numeric.
Also, if id is a primary/unique key then you can remove the ORDER BY clause from the query as it will make no difference.
EDIT
The answer has been updated as suggested in the comments below to include quotes around the SQL argument.

Related

Check which columns were modified in an UPDATE query

When we update a MySQL record with php, we can check if it has effect using:
$mysqli->affected_rows;
But how do I check which column has been modified?
Example, in my table have the columns: id / name / age
In a record we have the data: 1 / Woton / 18
If I send an: UPDATE mytable SET name = 'Woton', age = '20' WHERE id = '1'
Only the age field has changed. How can I determine this?
You cannot directly get the updated columns from the query result.
It can be get from some php query. Firstly we will have to select the row from database which we are going to update in a array variable. Than run the update query for the same row.
Lastly get the same row from database from select query in the new array variable.
Finally we get two arrays.
We can get the updated column with the array_diff_assoc php function.
See the below code for the same.
$sql = "SELECT * from mytable where id=1 limit 1";
$prev = mysqli_fetch_assoc(mysqli_query($conn, $sql));
//Get the column data in the array. Before update.
$sql = "UPDATE mytable SET name = 'Woton', age = '20' WHERE id = '1'";
$conn->query($sql);
// Update data
$sql = "SELECT * from mytable where id=1 limit 1";
$updated = mysqli_fetch_assoc(mysqli_query($conn, $sql));
// Again run the select command to get updated data.
$UpdatedColumns=array_diff_assoc($updated,$prev);
In a different note: If QueryLog has been enabled in the DB then you (or your script in PHP or Python or any) can easily see/read which part of the content has been updated and even you can monitor the DB.
The good news is, even you can target which table, which query etc.

Retrieve table ID from selected row

So I've been stuck on this for a while and I can't find anything on google for this specific thing.
I have this small snippet of code
$link = mysqli_connect("localhost", 'username','password',"database");
$sql = "SELECT * FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
Which should select the latest table by order of id's right?
Well what I want to do is return this id. So if I have 5 items/rows I want to grab the latest (5 in this case) id of the table, and return it. With the eventual goal of using this returned id in javascript but that's a worry for later, right now I just want it in plaintext where the result should only be the id.
This is probably a duplicate question but I can't for the life of me find what I should google to get there
EDIT:
I guess I should clarify further. I know I'm able to do
$sql = "SELECT ID FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
but whenever I try to actually retrieve it/print it its returned as a string instead of the ID.
EDIT 2: I, thanks to some comments, have managed to figure it out. Sorry for the badly worded everything, I'm new to this and as I said don't know how to word it.
SOLUTION:
After just throwing away the $sql thing I added:
$result = mysqli_query($link,"SELECT * FROM `uploads`");
Then I simply did
echo mysqli_num_rows($result);
To echo out the number of rows/what I called the "ID".
Sorry for all the confusion, thanks to those that tried to help. To the others there's no need to be rude.
If I understood your question correctly, you want to get the ID field only, so you have two options:
Option 1 (Recommended)
Given your code
$sql = "SELECT * FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
Change it to:
$sql = "SELECT ID FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
This way, your getting just that ID field you're after. Nothing else is returned from each row.
Option 2
Keep your sql query as it is, and get the ID field from each row in your results (it's an array, so you can retrieve only one field by using its index or name).
Of course, I assume there's an ID field in your table!
Just select the ID.
SELECT id
FROM uploads
ORDER BY id DESC
LIMIT 1;
Simply select what you want.
$sql = "SELECT id FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
The * means you want to select every column there is. However, SQL gives you the possibility to select the specific columns you want. You could also do something like
$sql = "SELECT id, name, title, somethingelse FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
and you'd receive these 4 fields as an array.

SQL "LIKE" If empty returns all rows

Hello I have 2 textboxes and i want to give to the user the option to choose one in order to find results. The user can search through the id or the name. My problem is because i use LIKE%field% when the user chooses to search through the id the name field stays empty and returns all the table rows. I want to have results only if the user enters some value in the textbox. This is my sql query. I'm using mysql
"SELECT * FROM properties WHERE ID='$id' OR Name LIKE '%$name%'"
Thank you all
If the user has to select which field to search, you can do:
if ($_POST['search'] == 'id') {
$sql = "SELECT * FROM properties WHERE ID='$id'"
} else {
$sql = "SELECT * FROM properties WHERE Name LIKE '%$name%'"
}
You can do this in a single query (values are checked from the query itself):
"SELECT * FROM properties WHERE ('$id'='' OR ID='$id') AND ('$name' ='' OR Name LIKE '%$name%')"
Explanation:
First condition:
The query will select records with ID='$id' only when $id is not empty.
If $id is empty, query will not go for the second part ID='$id'
Second condition:
The query filters records with Name LIKE '%$name%' only when $name is not empty.
If $name is empty, query will not go for Name LIKE '%$name%'.
NB: This technique is extremely useful when you have numerous parameters to check, rather than using a bunch of if...elses at php side.

Sort rows in the same order specified in MySQL IN()

Have some IDs:
$ids = "'55-30269','50-30261','50-30254','50-30257','50-30268','50-30253'";
Have this query:
$sql = "SELECT * FROM `report` WHERE `id` IN ($ids)";
I want the rows to be in the same order like specified in $ids.
Instead of that I get order by which these rows were originally inserted in table.
Also, i'm not sure why do I need each of id to be placed in quotes '55-30269', but query is not getting executed other way. E.g. $ids = "55-30269,50-30261,50-30254,50-30257,50-30268,50-30253";
Because the data type of ID is string. String literals must be wrap with single quotes. If you want to order the result based on the specified ID, use FIELD() for custom reordering.
SELECT *
FROM report
WHERE ID IN ($ids)
ORDER BY FIELD(ID, $ids)
FIELD()
The reason why you are not getting exact result when passing ID without single quotes,
$ids = "55-30269,50-30261,50-30254,50-30257,50-30268,50-30253"
is because MySQL performs arithmetic on the values.
55-30269 = -30216
50-30261 = -30211
...

Stripping a URL of an ID to Query MYSQL database

if i have a category page that im rendering by querying the subcategories in my database, then if i click on one of the subcategories it sends me to
mydomain.com/product_list.php?id=subcategory.
is there a way take the subcategory from the url to query the database to only show the products in that subcategory?
i think it'll look something like:
$sql = mysql_query("SELECT * FROM products");
This can be obtained from $_GET DOCs.
$subcategory_id = $_GET['id'];
So this would become:
if(array_key_exists('id', $_GET) and is_numeric($_GET['id'])) {
$subcategory_id = (int) $_GET['id'];
$SQL = "SELECT * FROM products WHERE subcategory_id = $subcategory_id";
}
Note I have cast the input variable to an integer to prevent SQL injection etc. As the ID must always be a number.
If you need to pass in a string then use mysql_real_escape_string() DOCs on it first and don't type cast to an integer (int):
if(array_key_exists('id', $_GET)) {
$subcategory_id = mysql_real_escape_string($_GET['id']);
$SQL = "SELECT * FROM products WHERE subcategory_id = '$subcategory_id'";
}
$query = mysql_query("SELECT * FROM `products` WHERE `id` = " . mysql_real_escape_string($_GET['id']);
Of course, that's assuming the table name is products, and the ID columns is id.
Your question is a little confusing. I think to start some tutorials on PHP should be looked at, and the different types of http requests.
What you are looking at is called a GET request. You can access all key, value pairs after the ? in a url through the superglobal $_GET this is an associate array containing all key => values.
So as per above $_GET['id'] is the value you want. But please before you begin look at SQL injection, it is too easy to think that that value can be used directly to make a query.

Categories