Stripping a URL of an ID to Query MYSQL database - php

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.

Related

How to access a table using a variable name in sql query

I have multiple tables in my database named teacher1, teacher2.... I am trying to access them using a variable $id.
I have written down the following code.
$query = "SELECT * FROM table.$id";
How could i access those different tables using a variable.
I'm not clear from the question text whether your $id variable contains the full table name, or some kind of number.
However, in either case you have to make a slight tweak to your $query variable.
If $id contains the full name of the table (i.e. teacher1):
$query = "SELECT * FROM " . $id;
If $id contains a number used to identify which teacher table it is (i.e. 1, 2, 3, etc):
$query = "SELECT * FROM teacher" . $id;
Learn to use parameters!
$stmt = $conn->prepare($query = "SELECT t.* FROM table t where t.id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
Don't munge query strings with parameter values! This introduces SQL injection risk, can introduce syntax errors that are hard to debug, and can degrade performance.

Retrieving values from MySQL using php

Here i have made an MySQL which has the columns of "id","name","username","email",age" . Where even i made the the PHP code to retrieve the data for the given id.
eg:if the user enter id=3 then it shows the datas corresponding to the id.
But now i want set multiple inputs so that user can type more than one id and it list the corresponding datas of the particular id.
My PHP Code:
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
require_once('dbConnect.php');
$sql = "SELECT * FROM user WHERE id='".$id."'";
$r = mysqli_query($con,$sql);
$result = array();
while($res = mysqli_fetch_array($r)){
array_push($result,array(
"id"=>$res['id'],
"name"=>$res['name'],
"username"=>$res['username'],
"email"=>$res['email'],
"age"=>$res['age']
)
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
}
Now this URL gives the perfect result:
"http://www.allwaysready.16mb.com/Sort.php?id=4"
Now how can i get the corresponding values for the multiple id's?
You can use array syntax to pass multiple IDs to your script and use MySQL's IN() to query against them all at once.
URL: http://www.allwaysready.16mb.com/Sort.php?id[]=4&id[]1&id[]=2
$ids = $_GET['id'];
$ids = array_map(function($id) {
return (int) $id;
}, $ids);
$ids = implode(',', $ids);
$sql = "SELECT * FROM user WHERE work IN($ids);
I cast the IDs to integers because your current code is wide open to SQL injection. You really should be using paramterized queries.
Use the "IN" condition:
If id is a number:
SELECT * FROM user WHERE id IN (89, 25);
If id is a string, put the id's in quotes:
SELECT * FROM user WHERE id IN ('89N', '15B', '25E');
Rewrite your query in PHP to use the In Query condition, paying close attention to your column definition data types. Strings must be quoted for example.

php/mySQL: querying records by id from array?

i want to query several records by id like:
$ids = array(10,12,14,16,....);
the query would be something like:
select * from users where id=10 or id=12 or id=14 or id=16 ..
is it possible to query it in a more comfortable way like (compared to php):
select * from user where in_array(id, array(10,12,14,16))
thanks
You can use IN instead of OR clauses
select * from users where id IN (put_your_array_here)
Example:
select * from users where id IN (10,12,14,16);
Note:
According to the manual for MySQL if the values are constant IN
sorts the list and then uses a binary search. I would imagine that
OR evaluates them one by one in no particular order. So IN is
faster in some circumstances.
Related post
Try this.
$id = array(10,12,14,16,....);
$ids = join("','",$id);
$sql = "select * from user where id IN ('$ids')";
OR
$ids = implode(',', $id);
$sql = "select * from user where id IN ($ids)";
You can do it like that using implode in PHP:
"select * from users where id in '".implode("','", $ids)."'"
Please be sure that your ids are safe though

Getting ID of Variable in database

I would like to get the id of an item in the database, set it to a variable, and use it. I'm quite new to all this coding stuff. I'm basing this on.
http://jameshamilton.eu/content/simple-php-shopping-cart-tutorial?PHPSESSID=99d373741727e3010a32319f1ebed001
cart.php?action=add&pdin=fbs
$product = $_GET[pdin];
I can't use an integer for 'pdin' so, id like to use its corresponding id which is an integer and plug it into this line of code which only takes integers?
$sql = sprintf("SELECT * FROM products WHERE pdin = %d;", $product);
so in i would take $product = 'pdin' find it's id $id = 'id' and plug it in to the above code
$sql = sprintf("SELECT * FROM products WHERE id = %d;", $id);
I tried reading up on this sql FROM SELECT WHERE... confused me some
I'd use a prepared statement which would also make yourself a bit safer from SQL injection. What database interface are you using from php to mysql?
Here's one option:
$product = $_GET['pdin'];
$stmt = $db->Prepare("select * from products where pdin = ?");
$res = $db->GetAssoc($stmt,$product);
btw,
if you acces array items via key, always use quotations (' or ") otherwise PHP (unnecessary) first check, if key is constant
Ok, I figured it out. I'm sorry i didn't explain it all that well last night. I have a limited brain battery per day, and last night it was depleted.
What i wanted was quite simple. I wanted to find an items associated id in the database.
$query = "SELECT * FROM products WHERE pdin = '$product'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
$productID = $row['id'];
}
Now that parts done and returns the correct id. And the 'item exists' function fires correctly.
//function to check if a product exists
function productExists($productID) {
//use sprintf to make sure that $productID is inserted into the query as a number - to prevent SQL injection
$sql = sprintf("SELECT * FROM products WHERE id = %d;", $productID);
return mysql_num_rows(mysql_query($sql)) > 0;
}
So, Mark and Michal Hatak; When you where talking about using quotations on keys, does that mean...
$sql = sprintf("SELECT * FROM products WHERE 'id' = %d;", $productID);
putting quotations around things like 'id'? And it's for security?
Forgive me, I'm a new graphic designer and not adept at code.

SELECT id WHERE id equals a passed value

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.

Categories